当我使用 volley 向服务器发送请求时,它不起作用并引发运行时错误。
public class MyFCMService extends FirebaseMessagingService {
String url, title, message;
String category_id;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
title = remoteMessage.getData().get("title");
message = remoteMessage.getData().get("message");
String id = remoteMessage.getData().get("ID");
if (check(id).equals("6")) {
sendNotification(title, message);
} else {
sendNotification("khalid", "khalid");
}
}
public String check(String id) {
url = "http://www.tobeacademy.com/api/get_post/?post_id=" + id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("post");
category_id = array.getJSONObject(0).getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(this).add(stringRequest);
return category_id;
}
Volley 请求异步完成。 侦听器的 onResponse()
方法在从tobeacademy
服务器收到重新调用的数据之前不会执行。
这意味着在 check()
方法中,category_id
返回的值无效,因为它是在侦听器onResponse()
执行并定义它之前返回的。
您需要将代码重构为如下所示的内容:
public void check(String id, final String title, final String message) {
url = "http://www.tobeacademy.com/api/get_post/?post_id=" + id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("post");
String category_id = array.getJSONObject(0).getString("id");
if (category_id.equals("6")) {
sendNotification(title, message);
} else {
sendNotification("khalid", "khalid");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(this).add(stringRequest);
}