Search code examples
androidandroid-activitypreference

android preference activity


I have a preference activity and want that if one of its items is clicked it will start a background work and show a nice progress bar in foreground until the background task finishes. how to do it???

Code writtenis:

 public boolean onPreferenceClick(Preference preference) {
  showProgressDialog();
  new Thread(new Runnable() {
   public void run() {
    doSomething();
    hideProgressDialog();
   }       //Runnable.run()
  }).start();
  return false;
 }
});

But the above code is not showing progress dialog. and ANR error occurs.

Thanks.


Solution

  • Add following code in your activity class:

    // Need handler for callbacks to UI Threads
        // For background operations
        final Handler mHandler = new Handler();
    
        // Create Runnable for posting results
        final Runnable mUpdateDone = new Runnable() {
            public void run() {
                progDialog.hide();      
                // Do your task here what you want after the background task is finished.           
            }
        };
    

    Write following code in onPreferenceClick:

    progDialog = ProgressDialog.show(AddPhoto.this, "", "Uploading Photo...");
                new Thread() {
                    public void run() {
                        // Start your task here.....                                                        
                        mHandler.post(mUpdateDone);
                    }
                    }.start();
    

    Let me know if doesn't work for you!