有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在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(与共享首选项中已存储的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) 个答案

  1. # 1 楼答案

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

    装饰性说明:请遵守代码惯例标准,使代码更具可读性。(例如骆驼箱和无_蛇:)