首页 > 解决方案 > 写入 JsonObjectRequest 中的布尔值

问题描述

我正在尝试写入 JSONObjectRequest 中的局部变量。这是我的代码:

JsonObjectRequest get_id_request = new JsonObjectRequest(Request.Method.GET, URL_ID, null,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                boolean load_full_data = false;
                try {

                    JSONObject jsonNotificationID = response.getJSONObject("n");


                    int notificationID = jsonNotificationID.getInt("id");

                    // Change flag to get full preferences below
                    if(notificationID > currentNotificationID) {
                        load_full_data = true;
                    }

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


            }
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

我希望能够检查服务器,如果有新的 ID(与已存储在共享首选项中的不同),然后下载新的。所以要做到这一点,我想设置我的变量load_full_data = true,然后再往下(排除这个请求):

// Get the IDs, see if they are different.
volleyQueue.add(get_id_request);

if(load_full_data) {
    Log.d(TAG, "run: Load Full Data");
    volleyQueue.add(get_full_request);
}

唯一的问题是,我无法在 JSONObjectRequest 中引用局部变量。它说它需要final。如何将数据传入和传出?

标签: javaandroid

解决方案


您可以创建一个新类并让它实现您想要丰富其定义的接口,在您的情况下Response.Listener<JSONObject> ,我不熟悉此 API,但示例代码如下:

class MyResponseListener implements Response.Listener<JSONObject> {
      boolean isGoodParam;

      MyResponseListener(boolean isGoodParam) {
         this.isGoodParam = isGoodParam;
      }

      public isGoodParam() {
         return this.isGoodParam;
      }

       @Override
        public void onResponse(JSONObject response) {
            //use your param
            if(this.isGoodParam) {
                doStuff();
            }
       }
} 

那么您的客户端代码将是:

boolean initialIsGood = true;
MyResponseListener listener = new MyResponseListener(initialIsGood);
JsonObjectRequest getIdRequest = new JsonObjectRequest(Request.Method.GET, URL_ID, null, listener,   
 Response.ErrorListener { error ->
        // TODO: Handle error
    });
//outside of the listener, assuming that the status of the boolean changed and you want to find out the new value
boolean newValue = listener.isGoodParam();

装饰说明:请遵守代码约定标准,使代码更具可读性。(例如 camelCases 和 no_snakes :)


推荐阅读