gpt4 book ai didi

java - 写入 JsonObjectRequest 内的 boolean 值

转载 作者:行者123 更新时间:2023-12-02 10:53:27 27 4
gpt4 key购买 nike

我正在尝试写入 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。我如何将数据传入和传出?

最佳答案

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

关于java - 写入 JsonObjectRequest 内的 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com