2017-06-06 85 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是异步调用。请求队列不会阻止当前线程。