0
我试图将从服务器接收的cookie存储到共享首选项中,然后在扩展AsyncTask的类的重写doinbackground方法中返回JSONObject。不允许我们在SharedPreferences中存储cookie并从AsyncTask类返回JSONObject
但这显示错误在哪里我检查onpostexecute方法的字符串即
if (jsonObject.getString("firstTime").equalsIgnoreCase("true"))
,但是当我删除写入存储的cookie在sharedPreferences字符串中的代码,然后它工作正常,即声明
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
cook = cookies.toString();
// to store only the value of cookie i.e 26 character long
cook = cook.substring(38, 64);
Editor editor = sharedPreferences.edit();
editor.putString("cookie", result);
editor.commit();
这里是两种方法的完整代码。
@Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
String cook = "";
JSONObject jsonObject = null;
try {
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("type", "login"));
list.add(new BasicNameValuePair("email", editEmail.getText()
.toString()));
list.add(new BasicNameValuePair("password", editPassword
.getText().toString()));
// list.add(new BasicNameValuePair("cookie", receivedCookie));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
httpPost.setEntity(new UrlEncodedFormEntity(list));
// executing with httpPost and httpContext
HttpResponse httpResponse = httpClient.execute(httpPost);
// checking the CookieStore after logging in
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
cook = cookies.toString();
// to store only the value of cookie i.e 26 character long
cook = cook.substring(38, 64);
Editor editor = sharedPreferences.edit();
editor.putString("cookie", cook);
editor.commit();
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpResponse.getEntity()
.getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line + "\n");
}
jsonObject = new JSONObject(builder.toString());
} catch (Throwable e) {
e.printStackTrace();
}
// return result;
return jsonObject;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
// TODO Auto-generated method stub
super.onPostExecute(jsonObject);
pDialog.dismiss();
try {
if (jsonObject.getString("firstTime").equalsIgnoreCase("true")) {
startActivity(intent);
} else {
textView.setText("checking for the data");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
它背后的原因是什么以及如何在不出错的情况下实现这两个目标?
我不明白这一点︰'editor.putString(“cookie”,result);'。你不应该储存'串厨'吗? – RogueBaneling
纠正了它......但结果仍然是一样的。 – vishu
应用程序崩溃还是仅向'LogCat'打印'JSONException'?发布日志。 – RogueBaneling