Reputation: 3
I've been trying to get ProgressDialog to work.
At first, I had it inside activity, but it was not showing up no matter how many permutations and combinations I tried.
Then I moved it inside AsyncTask. I'm initializing and showing it in onPreExecute, and dismissing it in onPostExecute.
@Override
protected void onPreExecute(){
try {
dialog = new ProgressDialog(context,
ProgressDialog.STYLE_SPINNER);
dialog.setTitle("Please Wait");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIcon(R.drawable.ic_error);
dialog.show();
} catch (Exception e) {
Log.e(TASK_TAG, ExceptionUtils.getStackTrace(e));
}
}
However, I'm not sure what should be used as context. When I try activity.getApplicationContext, following exception is thrown android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application.
When tried with activity, the dialog is not shown.
When I enclose the dialog.show in try / catch, it doesn't show. When it is not enclosed, it seems the Exception takes down the App.
I have a few questions -
Upvotes: 0
Views: 407
Reputation: 216
I recommend using the progressDialog inside your AsyncTask, so AsyncTask and Activity are not linked, it's possible that the activity dies and the asynctask continues his execution.
new YourAsyncTask(context).execute(...);
You have to create a custom contructor for your Asynctask:
private class YourAsyncTask extends AsyncTask<URL, Integer, Long> {
private Context context;
private Dialog dialog;
public YourAsyncTask(Context context){
this.context = context;
}
@Override
protected void onPreExecute(){
try {
dialog = new ProgressDialog(context,
ProgressDialog.STYLE_SPINNER);
dialog.setTitle("Please Wait");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIcon(R.drawable.ic_error);
dialog.show();
} catch (Exception e) {
Log.e(TASK_TAG, ExceptionUtils.getStackTrace(e));
}
}
protected Long doInBackground(URL... urls) {
...
}
protected void onPostExecute(Long result) {
if(dialog != null && dialog.isShowing()){
dialog.dismiss();
}
....
}
}
Upvotes: 1
Reputation: 7070
1.What is the recommended way of showing Progress Dialog? Is it through Async Task?
-- Depends upon your requirement. But if you have a situation where you want to do some operation in your AsyncTask
and you don't want the user to interact with your app during that time, you can show the Dialog in onPreExecute()
of AsyncTask
.
- If yes, what should be used as Context?
-- The context should be the activity context everytime you use ProgressDialog
so as to avoid the exception.
- If it is one of the two choices mentioned, why is the App throwing these Exceptions?
-- Exception is because the context is invalid. You should use Activity context;
Upvotes: 0