我正在Android Studio中制作应用程序,并且无法设置匿名类中字段的值。
我知道“ receivedNumber”总是与“ -1”不同,并且值“ isExist”必须为“ true”,但在日志中为“ false”。 int字段也会发生同样的事情-始终返回0。 我应该怎么做才能在匿名类中正确设置字段并在我的主类中使用它们。
private void isNumberExist()
{
String URL = "some url...";
final boolean[] isExist = new boolean[1];
objectRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
int receivedNumber = response.getInt("id");
if (receivedNumber == -1) {
isExist[0] = false;
} else {
isExist[0] = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//error
}
}
);
Log.e("isExist","value"+ isExist[0]);
requestQueue.add(objectRequest);
requestQueue.cancelAll(this);
}
答案 0 :(得分:0)
它将始终为false
,因为在执行http(s)请求之前您正在登录isExist[0]
请尝试这个
private void isNumberExist()
{
String URL = "some url...";
final boolean[] isExist = new boolean[1];
objectRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
int receivedNumber = response.getInt("id");
if (receivedNumber == -1) {
isExist[0] = false;
} else {
isExist[0] = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
// New log location
Log.e("isExist","value"+ isExist[0]);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//error
}
}
);
requestQueue.add(objectRequest);
requestQueue.cancelAll(this);
}