Reputation: 2377
I am running an Async(doInBackground) task in android.
I need to populate a progress bar for the task. So i am showing a progressDialog in onPreExecute,
The signature of ProgressDialog.show is Show(Context,Title,message)
But what would be the Context here?
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(???, "Loading", "Please Wait");
}
Upvotes: 1
Views: 325
Reputation: 2464
Add this function in your class
private Context getDialogContext() {
Context context;
if (getParent() != null)
context = getParent();
else
context = this;
return context;
}
In your asynctask use it as follows
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(getDialogContext(), "Loading", "Please Wait");
}
Upvotes: 1
Reputation: 2707
you can pass current activity view reference like MainActivity.this
Upvotes: -1
Reputation: 718
You can pass the activity context in the AsyncTask constructor to create the ProgressDialog :
MyAsyncTask constructor :
public MyAsyncTask(Context context){
progressDialog = new ProgressDialog(context, "Loading", "Please wait...");
}
onPreExecute method :
@Override
protected void onPreExecute()
{
progressDialog.show();
}
or store the context and create the dialog in the onPreExecute methods (but I prefer use the first way) :
public class MyAsyncTask extends AsyncTask{
private Context mContext;
public MyAsyncTask(Context context){
this.mContext = context;
}
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(this.mContext, "Loading", "Please Wait");
}
}
And in activity when you declare MyAsyncTask, you pass the activity:
MyAsyncTask asyncTask = new AsyncTask(this);
asynchTask.execute();
Upvotes: 1
Reputation: 831
Context can be only of Activity ,Service or Brodcast not of any other class like Asyncktask.So put the Context of that Activity where you are using that AsyncTask class.
Upvotes: 1
Reputation: 35661
Create a constructor for your AsyncTask that takes a context as a parameter.
public class async extends AsyncTask<String, Integer, String>{
private Context context;
public async(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
// Manipulate progress bar
}
Then use this to execute it
async mTask = new async(context).execute(params);
Upvotes: 2
Reputation: 675
if you want to use only this
as context then your Asynctask should be written as an inner class of a class which extends the Activity class. Then your context is the name of the class which extends Activity. Still it is better practice to pass the context like this:
ClassExtendingActivity.this
Upvotes: 0