Search code examples
javaandroidprogressdialogpreferenceactivity

Displaying ProgressDialog within a PreferenceActivity


I've got a quite interesting issue when I try to display a ProgressDialog (the simple, spinner type) within a onPreferenceChange listener.

public class SettingsActivity extends PreferenceActivity {
  private ProgressDialog dialog;

  public void onCreate(Bundle savedInstanceState) {
    ListPreference pref= (ListPreference) findPreference("myPreference");  
    pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

      @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
        dialog = ProgressDialog.show(SettingsActivity.this, "", "Doing stuff...", true);
        SystemClock.sleep(2000);
     }
    return true;
  }
}

The ProgressDialog shows up, but not until the method (sleep in this case) has finished. What am I doing wrong?


Solution

  • You can use AsyncTask to run the function in a separate thread (see http://developer.android.com/resources/articles/painless-threading.html)

    This is probably a bit unnecessary if you just want to invoke a sleep method, but should work even for other methods that otherwise would block the UI thread.

    You could do something like this:

    private class BackgroundTask extends AsyncTask<Integer, Integer, void> {
        private ProgressDialog dialog;
    
        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(SettingsActivity.this, "", "Doing stuff...", true);
        }
    
        @Override
        protected void doInBackground(Integer... params) {
            sleep(params[0]);
        }
    
        @Override
        protected void onPostExecute(Boolean result) {
            dialog.dismiss();
        }
     }
    

    And than call it using the code below:

    new BackgroundTask().execute(2000);