我注意到在AsyncTask中發生崩潰的某些設備上存在問題。它在我的平板電腦和智能手機上沒有問題,但我的朋友在他的設備上遇到問題。Android - AsyncTask上的RuntimeException
這是我的AsyncTasks中的一個的主體的實例:
protected String doInBackground(String... params) {
String result = "";
HttpClient httpclient = GlobalValues.getHttpClient();
HttpPost httppost = new HttpPost(String.format(GlobalValues.getServiceUrl() + "%s", params[0]));
try {
HttpResponse response = httpclient.execute(httppost, GlobalValues.getLocalContext());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = GlobalValues.convertStreamToString(instream);
Log.i(params[0], params[0] + ": " + result);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
LOG:
FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
...
Caused by: java.lang.NullPointerException
...
在線路中發生的錯誤:
HttpResponse response = httpclient.execute(httppost, GlobalValues.getLocalContext());
httppost包含服務器url,它是在GlobalValues.getServiceUrl()和params []的幫助下在方法內部設置的。會話cookie存儲在一個HttpContext中,它是從GlobalValues.getLocalContext()中檢索的,當應用程序第一次啓動並由我的所有AsyncTasks共享時設置。我不明白可能拋出NullPointerException的位置。
我看過其他問題/答案,但還沒有找到解決方案。
- 的LocalContext共享
- InputStream的在響應的HttpResponse閉合= httpclient.execute(httppost,GlobalValues.getLocalContext())。
有沒有人遇到過這個& /知道可能是什麼問題?
編輯:
啓動活動 -
private DefaultHttpClient httpclient;
private HttpContext localContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpclient = new DefaultHttpClient();
localContext = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
GlobalValues.setHttpClient(httpclient);
GlobalValues.setLocalContext(localContext);
GlobalValues -
protected static DefaultHttpClient httpclient;
protected static HttpContext localContext;
public static final DefaultHttpClient getHttpClient() {
return httpclient;
}
public static final HttpContext getLocalContext() {
return localContext;
}
public static final void setHttpClient(DefaultHttpClient httpclient) {
GlobalValues.httpclient = httpclient;
}
public static final void setLocalContext(HttpContext localContext) {
GlobalValues.localContext = localContext;
}
更新:我已經發現,當有人試圖恢復應用程序的問題只發生。我通過在GlobalValues.getHttpClient()和GlobalValues.getLocalContext()中添加「if(null)re-instantiate variable」來阻止應用程序崩潰。但是,存儲在LocalContext中的會話cookie會丟失。任何想法如何重新實例化值或變量而不會丟失數據?
該行中的'NullPointerException'意味着'httpclient'已經'null' - 從您的代碼指向'GlobalValues.getHttpClient()'。你能給我們來源嗎? – dst
我忘了HttpClient - 我已經按照你的要求添加了代碼段 – lgdroid57