I\'m trying to retrieve json data using JsonArrayRequest.Here\'s my code for doing that
public class QuestionDetailFragment extends Fragment {
private static
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);
}
}