0

當我使用volley將請求發送到服務器時,它不起作用並引發運行時錯誤。String使用volley從FirebaseMessagingService請求不起作用

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

排隊請求異步完成。直到從tobeacademy服務器收到reuqested數據後,偵聽器的onResponse()方法纔會執行。

這意味着在您的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); 
}