Fetching data from json using jsonArrayRequest

后端 未结 1 1370
礼貌的吻别
礼貌的吻别 2021-01-29 10:45

I\'m trying to retrieve json data using JsonArrayRequest.Here\'s my code for doing that

public class QuestionDetailFragment extends Fragment {
   private static          


        
相关标签:
1条回答
  • 2021-01-29 10:59

    Thats because the JsonArrayRequest is being added to the volley queue which executes task asynchronously. So even though you are calling the Log.d("tag","data:"+data); after readQuestionDetails() the request has not executed yet, meaning data is null.

    Something like this will work:

    public class QuestionDetailFragment extends Fragment {
        private static final String url = "http://10.0.2.2:80/forumtest/readquestion.php?format=json";
        private String data;
        RequestQueue requestQueue;
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.question_details_layout, container, false);
            readQuestionDetails();
            return view;
        }
    
        private void readQuestionDetails() {
            requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
    
                    try {
                        for (int i=0;i<response.length();i++) {
                            JSONObject jsonObject = response.getJSONObject(i);
    
                            data=jsonObject.getString("user");
                            printData(data);
                        }
    
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("user",e.getMessage());
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("user", error.getMessage());
                }
            });
    
            requestQueue.add(jsonArrayRequest);
        }
    
        private void printData(String data){
            Log.d("user","data:"+data);
        }
    }
    
    0 讨论(0)
提交回复
热议问题