ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [안드로이드] AysncTask 재사용시 뜨는 에러 구문 : Cannot execute task: the task has already been executed (a task can be executed only once)
    안드로이드(java)/에러 관련 2018. 6. 2. 22:58

    AsyncTask를 연습하는데 에러가 났습니다.

    이너클래스에 Asynctask를 상속받아 생성한  Task라는 클래스를 만들었고

    그 값을 필드에 선언하고 객체생성까지 했습니다.

    물론 필드에 객체 생성하는건 좀 아니지만...

    연습이라 그냥 이렇게 했습니다.


    그리고 필드에 선언한 그 변수값을 새로운 버튼에 넣고 실행시켰습니다.

    처음 실행시켰을때는 잘 되는데 다시 실행하면 아래처럼 에러구문을 뱉어내며 뻗어버립니다.

    java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)


    찾아보니 Asynctask 객체가 한번 사용 되면 재사용이 안되는것 같더라구요.

    그래서 필드에 객체 생성하지 않고 버튼을 누를때마다 객체가 생성되게 하니

    문제없이 잘 실행되었습니다.


    혹시 저와 같은 문제가 생기신 분들은 메서드가 실행될 때마다 객체가 생성되게끔 해보시는건 어떨까 합니다.


    아래는 에러를 수정한 이후의 전체 코드입니다.


    -- activity.xml --

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="작업 대기중"
    android:textColor="#000"
    android:textSize="30dp"/>

    <ProgressBar
    android:id="@+id/pb"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/Widget.AppCompat.ProgressBar.Horizontal"
    android:max="100"
    android:progress="0"
    android:padding="10dp" />

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="시작"
    android:onClick="startBtn"/>
    <Button
    android:id="@+id/btn2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="취소 or 초기화"
    android:onClick="cancleBtn"/>

    </LinearLayout>

    </LinearLayout>


    -- Mainactivity.java --

    package org.cis.asynctaskex;

    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ProgressBar;
    import android.widget.TextView;

    public class MainActivity extends AppCompatActivity {
    TextView textView;
    ProgressBar progressBar;
    Button btn1, btn2;
    //Task task = new Task(); 수정 전 코드
    Task task; // 수정 후 코드

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = findViewById(R.id.tv);
    progressBar = findViewById(R.id.pb);

    btn1 = findViewById(R.id.btn1);
    btn2 = findViewById(R.id.btn2);

    }

    public void startBtn(View view) {
    task = new Task(); // 수정 후 코드
    task.execute(100);
    }

    public void cancleBtn(View view) {
    if (task != null && task.getStatus() == AsyncTask.Status.RUNNING){
    task.cancel(true);
    } else {
    textView.setText("작업 대기중");
    progressBar.setProgress(0);
    }
    }

    class Task extends AsyncTask<Integer, Integer, String> {
    int value = 0;

    @Override
    protected String doInBackground(Integer... integers) {
    progressBar.setMax(integers[0]);
    while (value < progressBar.getMax()) {
    value++;
    publishProgress(value);
    try {
    Thread.sleep(50);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    return "작업 완료";
    }

    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    Log.d("AysncTask : ", "doInBackground() 메서드 실행전에 onPreExecute() 메서드 실행됨");
    }

    @Override
    protected void onPostExecute(String s) {
    super.onPostExecute(s);
    Log.d("AysncTask : ", "doInBackground() 메서드 실행후에 onPostExecute() 메서드 실행됨");
    textView.setText(s);
    btn1.setText("시작");
    btn1.setEnabled(true);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);
    Log.d("AysncTask : ", "doInBackground() 메서드 실행중간중간에 onProgressUpdate() 메서드 실행됨");
    textView.setText("진행중... " + value);
    progressBar.setProgress(value);
    btn1.setText("진행중");
    btn1.setEnabled(false);
    }

    @Override
    protected void onCancelled() {
    super.onCancelled();
    Log.d("AysncTask : ", "취소버튼 누르면 onCancelled() 메서드 실행됨");
    textView.setText("작업 대기중");
    progressBar.setProgress(0);
    btn1.setText("시작");
    btn1.setEnabled(true);
    }
    }
    }



    댓글

Designed by Tistory.