Panache
Panache

Reputation: 1721

Progress Dialog on Async Task

I have created Three Classes, namely Mainactivity which is passing context to server class extending to Asynctask. There one class named setting, which call server class for updating data in server.

Code on Mainactivity for passing Context:

Server.setActivityContext(getApplicationContext());

Code for Sever Class:

public class Server extends AsyncTask<Void, Void, Void> {


static Context mycontext;

public static void setActivityContext(Context receivingcontext) {
    mycontext = receivingcontext;
}

Dialog dialog;

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog = ProgressDialog.show(mycontext, "Updating ..", "Please wait......");
}

@Override
protected Void doInBackground(Void... params) {
//Background task       
        return null;

}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    dialog.dismiss();
}
}

I am getting an error on progressdialog when calling this server class. Though context is passed, any fixes which you can suggest.

Error:

 FATAL EXCEPTION: main

    Process: jss.smartapp, PID: 22915 android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

Upvotes: 0

Views: 609

Answers (3)

Abhishek Jaiswal
Abhishek Jaiswal

Reputation: 628

You can create a constructor for passing the context like this

public class Server extends AsyncTask<Void, Void, Void> {

private static final String TAG = "Server";
private Context mContext;

public Server(Context context){
    mContext = context;
}



Dialog dialog;

@Override
protected void onPreExecute() {
    super.onPreExecute();
    Log.d(TAG, "onPreExecute:called ");
    dialog = ProgressDialog.show(mContext, "Updating ..", "Please 
   wait......");
}

      @Override
      protected Void doInBackground(Void... params) {
      //Background task
       Log.d(TAG, "doInBackground: called");
       return null;

       }

   @Override
   protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    Log.d(TAG, "onPostExecute: called");
    dialog.dismiss();
   }
}

and call this Server class like this

 new Server(MainActivity.class).execute();

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191701

Don't use static methods. Use a proper constructor.

public class ServerTask extends AsyncTask<Void, Void, Void> {

    private Context mycontext;

    public ServerTask(Context c) {
        this.mycontext = c;
    } 

Call it with

new ServerTask(MainActivity.this).execute();

Upvotes: 1

Serega Gevelev
Serega Gevelev

Reputation: 81

You have method setActivityContext and send back activity context, not application context

Upvotes: 0

Related Questions