Skip to content Skip to sidebar Skip to footer

Progressdialog Not Getting Started In Main Thread

I made an app which can upload some data to my database. In Activity, in which the user will enter data to be uploaded, i created a ProgressDialog. The ProgressDialog is created in

Solution 1:

I think the problem is with the context of the ProgressDialog. From design perspective I believe it is better to declare the ProgressDialog as an instance variable.

publicclassYourClass{

  private ProgressDialog progressDialog; // instance variable
  ....
}

And then in the click method create it like this:

// I believe the main issue is with the context you bind to the progressDialog// provide the activity as context as an Activity extends Context
progressDialog= ProgressDialog.show(this, "Please wait...", "Connecting to server", true, true);

And lastly do not put a while loop like that inside the onClick method. It will cause the button to be sticky which is not desired and will also make UI unresponsive. Make your ConnectDBThread an AsyncTask and update the UI (like dismiss the dialog) from there through onPostExecute once background process is completed in doInBackground.

Here is a proposed solution:

publicclassInsertTaskextendsAsyncTask<String, Void, String> {

     ProgressDialog dialog;
     Context ctx;

     publicInsertTask(Context ctx){
        this.ctx = ctx;
     }

     protectedvoidonPreExecute(Void result) {
         // do UI work here
         dialog = ProgressDialog.show(ctx, "Please wait...", "Connecting to server", true, true);

     }

     protectedVoiddoInBackground(String... args) {


        // do insert operation here ... String username  = args[0];
        String password = args[1];

        ......      
        String query = .... // generate the queryString serverResponse = doDBInsert(query); // create a method to run the query and return responsereturn serverResponse;
     }

     protectedvoidonPostExecute(String result) {
         // do UI work here// display your serverResponse(result) somewhere if neededif(dialog!=null && dialog.isShowing()){
            dialog.dismiss();
         }
     }
 }

Inside onClick Method:

//If check condition is met (password = confirm password)
 new InsertTask(getApplicationContext()).execute(username, password, address ...);

Post a Comment for "Progressdialog Not Getting Started In Main Thread"