开发者

Android: Loading Dialog for Activity

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜