2012-05-18 48 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);