2012-05-18 116 views
-4

我遇到了我正在处理的Android程序的问题。以下方法在MyActivity中。 MyActivity有一个扩展AsyncTask的内部类InnerClass。在InnerClass的doInBackground方法中,我搜索一个数据库。该搜索的结果将传递给此方法processSearchResult。除了最后一行会引发NullPointerException之外,所有工作都会正常工作。我在创建按钮时尝试使用getApplicationContext()代替此操作,但仍抛出异常。我调试了它,发现问题出在android.content.ContextWrapper类中。在getApplicationContext()方法中是调用mBase.getApplicationContext。问题是变量mBase为空。在使用this关键字时,仍然会调用此方法,而mBase仍然为null。任何人都可以告诉我为什么mBase为空?或者,如果它实际上正常的mBase为空?创建新按钮

public void processSearchResult(ResultSet result) { 
    try { 

    int x = 1; 
    while (result.next()) { 

     String name = result.getString(1); 
     String ing = result.getString(2); 
     String ins = result.getString(3); 
     String notes = result.getString(4); 
     String type = result.getString(5); 
     String course = result.getString(6); 

     Recipe r = new Recipe(name, ing, ins, notes, type, course); 
     recipeList.add(r); 

     Button button = new Button(this); 
+0

残缺码 –

+0

MBASE?代码中的mBase在哪里? – Niranjan

+0

如上所述,mBase位于android.content.ContextWrapper类中。 –

回答

2

您无法更新从你需要publishProgressAsyncTaskdoInBackground方法的用户界面,并从onProgressUpdate方法,而不是对其进行更新。

如何发布从doInBackground

publishProgress(0); //Assuming progress is 0 

我的进步在哪里从此更新UI?

@Override 
protected void onProgressUpdate(Integer... progress){ 
    //HERE 
} 

可能不是指你在想什么。 我要做的就是保持一个私人的全球Context变量在我今后的参考代码,如:

private Context x = this; 
1

这应该是您的活动的上下文,而不是应用程序上下文。试试MyActivity.this。

1

要创建按钮,您应该使用ActivityContext,尝试

Button button = new Button(MyActivity.this);