android – how to POST jsonobject with volley-ThrowExceptions

Exception or error:

I am developing a chatroom and have a this request to get jsonArray from my db, and i want to do a POST jsonObject request to insert msg in db:

public void getMsg(){
    String url = "http://192.168.1.57/android/leggi.php";
    final TextView chatView =(TextView) findViewById(R.id.chat);
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
            (Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
                String msg = "";
                String mittente = "";
                @Override
                public void onResponse(JSONArray response) {

                    for (int i = 0; i<response.length(); i++) {
                        try {
                            mittente = response.getJSONObject(i).get("mittente").toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        try {
                            msg += (response.getJSONObject(i).get("mittente").toString() + ":\n" + response.getJSONObject(i).get("testo").toString() + "\n");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    chatView.setText(msg);
                    //chatView.setGravity(Gravity.RIGHT);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO: Handle error

                }
            });

    MySingleton.getInstance(this).addToRequestQueue(jsonArrayRequest);

}

can i use the same volley request??? or the request must have different params??? need help 😛

How to solve:

This depens on what your servers response is when POSTing the JSONObject.

If the server responses with an JSONArray, you can build your response the same way:

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
            (Request.Method.POST, url, INSERT_HERE, new Response.Listener<JSONArray>()
    ...
{

And insert the JSON Object you want to post at the INSERT_HERE position.
If your response differs you need to change the type of Response.Listener<JSONArray>

Leave a Reply

Your email address will not be published. Required fields are marked *