代码之家  ›  专栏  ›  技术社区  ›  Chud37

在JsonObjectRequest中写入布尔值

  •  0
  • Chud37  · 技术社区  · 7 年前

    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(不同于那些已经存储在共享首选项中的ID),然后下载新的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 . 我怎样才能把数据传进来传出去?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Eirini Graonidou    7 年前

    您可以创建一个新类,并让它实现接口,在您的例子中,您希望丰富接口的定义 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();
    

    注意:请遵守规范惯例标准,使规范更具可读性。(例如骆驼箱和没有蛇:)