2017-06-06 165 views
-1

我不知道爲什麼medicine_description在onResponse之外返回null。當請求後您的日誌輸出完成,因此如何訪問onResponse外的數據?

 StringRequest stringRequest = new StringRequest(Request.Method.GET, fda_api + "acetaminophen", new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) { 
       try { 

        JSONObject json = new JSONObject(response); 
        JSONArray jArray = json.getJSONArray("results"); 
        Log.d(TAG, "readJSON: " + jArray.length()); 


        JSONObject json_data = jArray.getJSONObject(0); 
        medicine_description = json_data.getString("description"); 
        Log.i("THIS ONE IS FINE",medicine_description); 
        /*for(int i=0; i<jArray.length(); i++){ 
         JSONObject json_data = jArray.getJSONObject(i); 
         medicine_description = json_data.getString("description"); 

         Log.i("log_tag",medicine_description); 
        }*/ 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 

      } 
     }); 
     RequestQueue requestQueue = Volley.newRequestQueue(context); 
     requestQueue.add(stringRequest); 
     Log.i(TAG, "THIS RETURNS NULL: " + medicine_description); 

回答

2

Volley以異步方式工作,這意味着您無法知道響應何時會從您的web服務中獲得。它將在單獨的線程而不是UI線程上工作。

因此,無論Volley響應如何,外部代碼塊都會執行。

如果你需要函數中的字符串,你可能應該創建一個方法並在得到結果時調用它。

下面是一個例子:

public void onResponse(String response) { 
      try { 

       JSONObject json = new JSONObject(response); 
       JSONArray jArray = json.getJSONArray("results"); 
       Log.d(TAG, "readJSON: " + jArray.length()); 


       JSONObject json_data = jArray.getJSONObject(0); 
       medicine_description = json_data.getString("description"); 
       passdata(medicine_description); //create method to pass data 
       Log.i("THIS ONE IS FINE",medicine_description); 
       /*for(int i=0; i<jArray.length(); i++){ 
        JSONObject json_data = jArray.getJSONObject(i); 
        medicine_description = json_data.getString("description"); 

        Log.i("log_tag",medicine_description); 
       }*/ 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

     } 
+1

這就是所謂的'callback',是應對這種情況的適當方式。 – nbokmans

+1

謝謝@nbokmans – rafsanahmad007

1

onResponse是異步調用。請求隊列不會阻止當前線程。