Volley JsonObjectRequest响应 [英] Volley JsonObjectRequest response

查看:142
本文介绍了Volley JsonObjectRequest响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Volley JSONObjectRequest通过JSON从服务器检索数据以实现此目的.得到JSON响应后,我想将其保存到变量中并在整个活动中使用它.下面是我的代码示例:

I'm retrieving data from my server through JSON using Volley JSONObjectRequest to achieve this. After getting the JSON response, I want to save it into a variable and use it through out the activity. Below is my code sample:

private String description;
private int status;
private boolean validateIntegrationCode() {
    if (checkNetwork()) {
        String url = "sample url";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    status = response.getInt("status");// ** STATUS IS 1 HERE **
                    description = response.getString("description");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mQueue.add(request);
    } else {
        // No network, check from SQLite
    }
    if (status == 1) { // ** STATUS IS 0 HERE **
        return true;
    } else {
        return false;
    }
}

当我在返回truefalse之前检查status值时,status的值现在为0,而description也返回null.

When I check the status value before returning true or false, the value of status is now 0 and the description also returns null.

我的JSON响应:

{"status":1,"description":"Integration code is valid"}

推荐答案

截击请求是异步调用.在收到响应之前,它不会阻塞代码.因此,正在发生的情况是在收到截击响应之前正在检查if(status==1).因此它是0.

The volley request is an asynchronous call. It doesn't block the code till the response is received. So what is happening is your check for if(status==1) is happening before the volley response is received. Hence it is 0.

您应该做什么:

1)使您的函数返回类型为void.

1) Make your function return type void.

2)在onResponse中,输入代码

if (status == 1) { // ** STATUS IS 0 HERE **
        statusBoolean = true;
    } else {
        statusBoolean = false;
}

这篇关于Volley JsonObjectRequest响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆