Android: Loading Dialog for Activity

4.7k views Asked by At

I'm trying to implement the code from showing dialog while loading layout by setContentView in background and http://developer.android.com/guide/appendix/faq/commontasks.html#threading to show a loading dialog while my activity is loading, but having difficulty.

I have class variables defined for the UI elements in my view, and also strings for the data which is loaded on another thread from the database:

private TextView mLblName, mLblDescription, etc...
private String mData_RecipeName, mData_Description...

I also have the handlers defined:

private ProgressDialog dialog;
final Handler mHandler = new Handler();
final Runnable mShowRecipe = new Runnable() {
    public void run() {
        //setContentView(R.layout.recipe_view);
    setTitle(mData_RecipeName);
    mLblName.setText(mData_RecipeName);
    mLblDescription.setText(mData_Description);
    ...
    }
};

In onCreate, I'm trying too show the dialog, then spawn the loading thread:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
    setContentView(R.layout.recipe_view);
    showData();
}

protected void showData() {
    // Fire off a thread to do some work that we shouldn't do directly in the UI thread
    Thread t = new Thread() {
        public void run() {
            mDatabaseAdapter = new ChickenPingDatabase(ShowRecipe.this);
        mDatabaseAdapter.open();

        mTabHost = getTabHost();

        mLblName = (TextView)findViewById(R.id.lblName);
        mLblDescription = (TextView)findViewById(R.id.lblDescription);
        ...

        Cursor c = mDatabaseAdapter.getRecipeById(mRecipeId);
        if(c != null){
            mData_RecipeName= c.getString(c.getColumnIndex(Recipes.NAME));
                    mData_Description= c.getString(c.getColumnIndex(Recipes.DESCRIPTION));
            ...
                    c.close();
        }

        String[] categories = mDatabaseAdapter.getRecipeCategories(mRecipeId);
        mData_CategoriesDesc = Utils.implode(categories, ",");

        mHandler.post(mShowRecipe);

        }
    };
    t.start();
}

This loads the data, but the progress dialog isn't shown. I've tried shuffling the call to spawn the separate thread and show the dialog around, but can't get the dialog to show. It seems this is a fairly common request, and this post seemed to be the only answered example of it.

EDIT: For reference, a blog post demonstrating the way I eventually got this working.

1

There are 1 answers

1
Zarah On BEST ANSWER

Since what you want is pretty much straight-forward, I would recommend that you use an AsyncTask. You can control the showing/hiding of the dialog in onPreExecute() and onPostExecute(). Check out the link, there's a good example in there.