我注意到在 AsyncTask 中发生崩溃的某些设备上存在问题。它在我的平板电脑和智能手机上运行没有问题,但我的朋友在他的设备上遇到了问题。
这是我的一个 AsyncTask 的主体示例:
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;
}
日志:
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 中,该 HttpContext 是从 GlobalValues.getLocalContext() 中检索的,在应用程序首次启动并由我的所有 AsyncTasks 共享时设置。我不明白 NullPointerException 可能会在哪里抛出。
我查看了其他问题/答案,但没有找到解决方案。
- LocalContext 是共享的
- InputStream 在 HttpResponse response = 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);
全球价值观 -
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 会丢失。任何想法如何在不丢失数据的情况下重新实例化值或变量?