【问题标题】:Read String Value from JSON Object and show Toast Message从 JSON 对象中读取字符串值并显示 Toast 消息
【发布时间】:2018-05-11 05:44:00
【问题描述】:

我在我的应用程序中使用Volley。发出JSONObjectPOST 请求后,如果找到用户,我会得到JSONObject 作为响应。如果找不到用户,我会收到一条消息,因为找不到用户。我想显示Toast 解析 JSONObject 后未找到用户的消息。
如果找到用户,这是响应

{
        "name": ABC,
        "address": Pune,
        "status": "Married"
}  

如果找不到用户,这是响应

{
        "message":"User not Found"
}  

这是我的JSONObject POST 请求

JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST, url,jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        String error=response.getString("message");
                        if(error.equals("User not Found")){
                            coolToast.make("User Not Found",CoolToast.INFO);
                            coolToast.setDuration(CoolToast.SHORT);
                        }
                         else{
                            coolToast.make("User Found",CoolToast.SUCCESS);
                            coolToast.setDuration(CoolToast.SHORT);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            })  

从 JSONObject 读取消息后如何显示 Toast ?

【问题讨论】:

  • 你已经在实现 toast,那么到底是什么问题?
  • 未找到用户后,读取String Toast不显示。解析有问题?
  • 你忘了写 Toast 的 show() 方法。编写coolToast.show()
  • 您可以添加您的回复
  • 您正在尝试从响应中读取消息密钥,但在您的成功响应中您没有“消息”密钥。你可能想检查你的 catch 块。或使用调试器检查您的代码流

标签: android json android-volley android-toast


【解决方案1】:

创建 Toast 后,需要添加 Toast 的 show() 方法。在你的情况下添加coolToast.show()。

谢谢。

【讨论】:

  • 首先阅读 cmets 他正在使用我认为相同的库,但这不是在该库中显示敬酒的方式。
【解决方案2】:

在 try 块(第一行)中,您尝试访问不可用于成功响应的关键消息,在这种情况下,您会收到 JSONException(catch 块)。

首先使用.has(key)检查key是否存在。

内部响应首先检查名称是否存在

if(response.has("name"){
//User found
}else{
//User not found
//now access message here as response.getString("message")
}

【讨论】:

  • 用同样的方法如何同时检查JSONObject是否存在?
  • 如果您的服务返回无效的 JSONObject,您将在错误回调 (onErrorResponse) 中收到错误。
【解决方案3】:

如果你想保持相同的代码结构,你可以使用

String error=response.optString("message");

而不是

String error=response.getString("message");

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2015-02-12
    • 2011-06-16
    相关资源
    最近更新 更多