【问题标题】:Android Volley - JsonArrayRequest returns null objectAndroid Volley - JsonArrayRequest 返回空对象
【发布时间】:2020-02-20 15:13:45
【问题描述】:

在下面的代码中,我试图将 HttpRequest 发送到我的 API 以获取以 JSONArray 形式出现的位置。我正在使用 Volley 库和 JsonArrayRequest。问题是当我在 lambda 中设置我的本地 JSONArray 变量时,我有正确的值,但是当我在函数末尾返回它时,对象为空。我猜是在请求结束之前执行返回,但我可能是错误的。

private RequestQueue requestQueue; //<----Global 

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        setContentView(R.layout.activity_map);

        //Initialization of RequestQueue Object
        requestQueue = Volley.newRequestQueue(getApplicationContext());
}

//Setting map settings, checking permissions etc..

private JSONArray getUsersLocation() {
        AtomicReference<JSONArray> result = new AtomicReference<>(new JSONArray());
        JsonArrayRequest request = new JsonArrayRequest
                (Request.Method.GET, API_URL + "getLocations", null, response -> {
                    result.set(response);
                   //Here I have correct value of result (JSONArray)
                    System.out.println(result.get()); 
                },
                        error -> {
                            Toast.makeText(getApplicationContext(), "Cannot update users' location :" + error, Toast.LENGTH_LONG).show();
                        });
        requestQueue.add(request);
        return result.get(); //<----- Here my result is NULL
    }

我希望函数 getUsersLocation() 将返回来自响应的 JSONArray 对象。

【问题讨论】:

  • Volley Http 请求是异步的,所以 jsonArray 在响应到来之前返回 null,所以让你的方法无效并在你的问题解决之后初始化你的 List onSuccessListner。

标签: android arrays httprequest android-volley


【解决方案1】:

volley 中的 Http 请求是异步的,意味着它不会阻塞执行, 因此,在您的代码中,当您创建请求时,return 语句在请求完成之前执行,因此它返回 null。 为了解决这个问题,我 segsst 你用来创建一个接口并实现回调。 这是你应该做的:

public interface HttpCallback {

     public void onSuccess(JSONArray array)

}

并将您的方法修改为:

private JSONArray getUsersLocation(HtttpCallback callback) {
    AtomicReference<JSONArray> result = new AtomicReference<>(new JSONArray());
    JsonArrayRequest request = new JsonArrayRequest
            (Request.Method.GET, API_URL + "getLocations", null, response -> {
                result.set(response);
               //Here I have correct value of result (JSONArray)
                System.out.println(result.get());
                callback.onSuccess(response):
            },
                    error -> {
                        Toast.makeText(getApplicationContext(), "Cannot update users' location :" + error, Toast.LENGTH_LONG).show();
                    });
    requestQueue.add(request);
}

【讨论】:

  • 谢谢你,伙计,它正在按照我想要的方式完美运行!我是第一次使用 Volley
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
相关资源
最近更新 更多