[英]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.