Adrian Adrian - 4 months ago 54
Android Question

how to use progress with Asynctask get method?

I want to use progress bar... but As i searched, progress bar can not use with Asynctask.get. but I have to use .get and progress in Asynctask.

I made very simple source.
how can i changed to show progress bar in main thread??

please help me. thanks!!
I want to use both get method and ui progress. Thanks.

public void onCreate(Bundle savedInstanceState) {
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AAA asyncTask = new AAA();
try {
((AAA) asyncTask).execute(null, null, null,null).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class AAA extends AsyncTask<Object, String, Object> {
private ProgressDialog progDailog = null;


@Override
protected void onPreExecute() {
super.onPreExecute();
progDailog = new ProgressDialog(ViewTestActivity.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
}

@Override
protected Object doInBackground(Object... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return params;
}

@Override
protected void onPostExecute(Object result) {
progDailog.dismiss();
}
}

Answer

Do it before calling AsyncTask

public void onCreate(Bundle savedInstanceState) {
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            AAA asyncTask = new AAA();
            try {
                progDailog = new ProgressDialog(ViewTestActivity.this);
                progDailog.setMessage("Loading...");
                progDailog.setIndeterminate(false);
                progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progDailog.setCancelable(true);
                progDailog.show();
                ((AAA) asyncTask).execute(null, null, null,null).get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}
public class AAA extends AsyncTask<Object, String, Object> {
    private ProgressDialog progDailog = null;


    @Override
    protected Object doInBackground(Object... params) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return params;
    }

    @Override
    protected void onPostExecute(Object result) {
        progDailog.dismiss();
    }
}
Comments