[英]Displaying Alert dialog or toast in Android onPostExecute
如果我得到json响应为OK,那么我需要继续进行下去,如果我遇到任何错误,那么我只想在Toast或Alert对话框中打印该错误,但无法正常工作。有人可以告诉我我的问题是什么第二,如果条件在代码? y它不能显示吐司吗?
这是我得到错误的json结果
{“结果”:“错误”,“错误”:“无效参数”}
我需要在Toast或Alert对话框中显示该无效参数。
protected void onPostExecute(String result) {
prgDialog.hide();
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
try {
JSONObject json = new JSONObject(result);
String respResult=json.getString("result");
String respId=json.getString("customer_id");
String respEmail=json.getString("customer_email");
String respError=json.getString("error");
session.createUserLoginSession(respId, respEmail);
if(respResult.equals("ok")) {
Intent I = new Intent();
I.setClass(getApplicationContext(), MainActivity.class);
startActivity(I);
finish();
}
if(respResult.equals("error")) {
Toast.makeText(getBaseContext(), respError, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
您的代码正在获取异常,因为在发生错误的情况下获得的响应json不包含以下params
"customer_id"
"customer_email"
这样写你的代码
try {
JSONObject json = new JSONObject(result);
String respResult=json.getString("result");
if(respResult.equals("ok")) {
String respId=json.getString("customer_id");
String respEmail=json.getString("customer_email");
session.createUserLoginSession(respId, respEmail);
Intent I = new Intent();
I.setClass(getApplicationContext(), MainActivity.class);
startActivity(I);
finish();
}
if(respResult.equals("error")) {
String respError=json.getString("error");
Toast.makeText(getApplicationContext(), respError, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
为什么在上面放错误变量? 它应该是
protected void onPostExecute(String result) {
prgDialog.hide();
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
try {
JSONObject json = new JSONObject(result);
String respResult=json.getString("result");
if(respResult.equals("ok")) {
String respId=json.getString("customer_id");
String respEmail=json.getString("customer_email");
session.createUserLoginSession(respId, respEmail);
Intent I = new Intent();
I.setClass(getApplicationContext(), MainActivity.class);
startActivity(I);
finish();
}
if(respResult.equals("error")) {
String respError=json.getString("error");
Toast.makeText(getApplicationContext(), respError, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
问题是您应该使用getApplicationContext()而不是getBaseContext() 。 当您的应用程序运行时,第一个始终可用,而第二个不再可用。 如您的代码所示,您位于AsyncTask的onPostExecute()中,此时您的上下文(活动?)不可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.