title: Android Add AsyncTask to PreferenceActivity to load a lot of preferences the first time
body: <p>I have an application with quite a lot of preferences. So when the user loads the Preferences the first time, it takes quite a while. So the UI is freezing while loading the prefs.</p>
  
  <p>This is why I want to add a dialog telling the user that the prefs are loading.</p>
  
  <p>The problem is, that loading the preferences is only allowed on the UI thread because when I am trying to load my preferences in the Async Task, I get this:</p>
  
  <blockquote>
    <p>ERROR/AndroidRuntime(4830): Caused by:
    android.view.ViewRoot$CalledFromWrongThreadException: Only the
    original thread that created a view hierarchy can touch its views.</p>
  </blockquote>
  
  <p>So when I add runOnUiThread() to the Async Task the whole purpose of doing it in the AsyncTask gets destroyed:</p>
  
  <pre><code>public class ApplicationPreferences extends PreferenceActivity {
  
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  
      new ProgressTask(ApplicationPreferences.this).execute();
  }
  
  private class ProgressTask extends AsyncTask&lt;Void, Void, Void&gt; {
  
      private Context context;
  
      private ProgressDialog dialog;
  
      public ProgressTask(ListActivity activity) {
          context = activity;
          dialog = new ProgressDialog(context);
      }
  
      protected void onPreExecute() {
          this.dialog.setMessage("Loading...");
          this.dialog.show();
      }
  
      @Override
      protected Void doInBackground(Void... params) {
          runOnUiThread(new Runnable() {
  
              @Override
              public void run() {
  
                  initPreferences();
  
              }
          });
  
          return null;
      }
  
      @Override
      protected void onPostExecute(Void result) {
          if (dialog.isShowing()) {
              dialog.dismiss();
          }
      }
  
  }
  
  /*
  * THIS TAKES LONG THE FIRST TIME
  */
  private void initPreferences() {
  
  
      addPreferencesFromResource(R.xml.preferences);
  
      // preferences
      ListPreference pref1 = (ListPreference) findPreference(getString(R.string.pref1));
  
      // ........ etc
  
  
  }
  
  
  
  
  public static void start(Context context) {
      context.startActivity(new Intent(context, ApplicationPreferences.class));
  }  }
  </code></pre>
  
  <p>How can I do this better?</p>