我不知道爲什麼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);
這就是所謂的'callback',是應對這種情況的適當方式。 – nbokmans
謝謝@nbokmans – rafsanahmad007