我正在尝试写入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
。如何将数据传入和传出?
答案 0 :(得分: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();
化妆品说明:请遵守代码约定标准,以使代码更具可读性。 (例如camelCases和no_snakes:)