I am using a JsonObject request within onActivityCreated of my fragment. I am adding the jsonobject request to a request queue. The queue is not getting executed at all. I have put Log statement in Onresponse and Onerrorresponse. Its just like the request is not started at all. Below is my code. Please suggest if am doing something wrong. I need to pass a string to the server. So i am putting it in a jsonobject jlistname. Server will return a jsonobject back, so to receive it im using jsonobjectrequest instead of stringrequest.
RequestQueue rq;
JsonObjectRequest jsObjRequest;
JSONObject jlistname = new JSONObject();
String listname="list1";
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
searchitembtn=(ImageButton) getView().findViewById(R.id.searchitembtn);
rq = Volley.newRequestQueue(getActivity());
try {
jlistname.put("listname", listname);
} catch (JSONException e) {
e.printStackTrace();
}
jsObjRequest = new JsonObjectRequest(Request.Method.POST, getlistitems, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, "im in onresponse" + response);
System.out.println(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, "im in onerrorresponse" + error);
}
}) {
@Override
public byte[] getBody() {
return jlistname.toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
if (listtype==100||listtype==101){
-----------------------
}
else if(listtype==102){
Log.i(TAG,"mylisttypeis102: "+listtype);
Log.i(TAG,"im before adding o request queue"+jsObjRequest);
rq.add(jsObjRequest);
Log.i(TAG, "im after adding o request queue"+rq);
}
else {
-------------------
}
}
showLists();
}
UPDATE : I have added a button to the layout and in the onclicklistener of the button kept rq.add(jsObjRequest);
Then i am getting the response correctly.
But i really do not want the response on click. I want the response to be generated when the fragment is loaded as per my code in onActivityCreated.
Can someone explain why i get response only using a listener ?