当我使用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;
}
答案 0 :(得分:0)
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);
}