2011-02-27 105 views
0

我试图执行代码showing dialog while loading layout by setContentView in backgroundhttp://developer.android.com/guide/appendix/faq/commontasks.html#threading以显示加载对话框,同时我的活动正在加载,但有困难。Android:加载活动对话框

我有其上装载另一个线程从数据库中的数据在我的视图中的UI元素定义的类的变量,并且还字符串:

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

我还处理程序定义:

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); 
    ... 
    } 
}; 

在的onCreate,我想也显示对话框,然后产卵加载线程:

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(); 
} 

这会加载数据,但不显示进度对话框。我试着洗牌调用产生单独的线程并显示对话框,但无法显示对话框。看起来这是一个相当普遍的要求,这篇文章似乎是它唯一回答的例子。

编辑:作为参考,a blog post demonstrating the way I eventually got this working

+1

没问题!您提供自己的博客文章的链接?您可以通过重写onPreExecute()并在其中显示对话框而不是onCreate来进一步使用AsyncTask的方法。确保你也测试了你的应用程序如何改变方向时的反应。确保正确处理AsyncTask,以便它不会丢失它的上下文。 @Commonsware在这里做了一个很好的演示:http://bit.ly/gFYzsP – Zarah 2011-02-27 15:31:38

回答

1

既然你想要的是非常直截了当的,我会建议你使用AsyncTask。您可以控制onPreExecute()和onPostExecute()中对话框的显示/隐藏。查看链接,这里有一个很好的例子。

+0

Wahay。这件事我一直在拉我的头发。谢谢Zarah! – Echilon 2011-02-27 14:39:25