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(与已存储在共享首选项中的不同),然后下载新的。所以要做到这一点,我想设置我的变量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
。如何将数据传入和传出?
解决方案
您可以创建一个新类并让它实现您想要丰富其定义的接口,在您的情况下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 :)
推荐阅读
- tensorflow - DNN 不同部分的不同损失函数
- sql-server - 将 varchar(max) 中的非十六进制文本转换为 varbinary
- google-bigquery - BigQuery 使用条件从其他表创建表(管理大量列)
- java - Maven多线程构建问题
- emeditor - Em-Editor 自定义 TSV
- javascript - 在每个模态中延迟加载前后图像滑块
- css - CSS 子选择器 - 选择第一个嵌套元素
- python - if (None in string) 返回真还是假?
- sql - 具有修改值的重复记录(行)(Postgresql)
- angular - Firestore:删除多个文档尝试再次删除同一个文档