[英]Why am I getting a NullPointerException with AlertDialog in an asyncTask?
我有一個運行asyncTask
的啟動屏幕,該asyncTask
從API下載數據。 在該任務的OnPostExecute
我運行下一個asyncTask
來發送存儲的電子郵件。 完成此操作后,我需要使用OK按鈕彈出AlertDialog
,以便用戶知道下載已完成。 我用這個SO問題來達到我的目的:
AsyncTask中的Android AlertDialog
現在,當我嘗試向對話框中添加屬性時,我得到了NullPointerException:
public class JSONParser extends AsyncTask<String, String, JSONObject> {
Context c;
public JSONParser(int api,Context c) {
this.api= api;
this.c = c;
}
...
protected void onPostExecute(JSONObject result) {
JSONObject output = new JSONEmailParser(c).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, new String[] {null,null,null,null}).get();
}
}
public class JSONEmailParser extends AsyncTask<String, String, JSONObject> {
Context c;
AlertDialog.Builder builder;
public JSONEmailParser(Context c){
this.c = c;
}
protected void onPreExecute(int api){
builder = new AlertDialog.Builder(SplashScreen.this);
}
...
protected void onPostExecute(JSONObject result) {
setLastUpdate();
builder.setTitle("Sales Toolkit");
builder.setCancelable(false);
builder.setMessage("Download Complete");
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
endSplash();
}
});
builder.show();
}
}
錯誤發生在builder.setTitle("Sales Toolkit");
AsyncTask#onPreExecute()
不采用int參數。 由於您的方法簽名錯誤,因此很可能永遠不會調用它,因此永遠不會設置builder
。 這是為什么應使用@Override
注釋的經典示例。
不要使用.get()執行AsyncTask,因為它將不再是異步的。 並且onPreExecute將不會被調用?
似乎未調用onPreExecute()
方法。 如果您真的不需要在onPostExecute()
方法之前的任何地方使用builder
,建議您移動
builder = new AlertDialog.Builder(SplashScreen.this);
進入onPostExecute()
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.