ultrasamad
ultrasamad

Reputation: 368

Code under volley response not firing

I have this basic example, but the problem is that Anything I write under the volley on response is not firing even a Toast. Below is my code.

public class MainActivity extends AppCompatActivity {

private static final String URL = "http://192.168.10.1/holycare/install.php";
private Button mGetJsonButton;
RequestQueue requestQueue;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    requestQueue = Volley.newRequestQueue(this);

    mGetJsonButton = (Button) findViewById(R.id.get_json_btn);
    mGetJsonButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        Toast.makeText(MainActivity.this, jsonObject.toString(), Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
            requestQueue.add(stringRequest);
        }


    });


}

}

My back end code, the URL is pointing to has no problem as it returns a json response. The code in the JsonException catch part is rather giving the response. That is strange.

[
   {
       "id": "1",
       "title": "Welcome to 2017",
       "date_created": "2017-02-17 11:04:12",
       "body": "Hello to all staff of Holy Medical Center, We welcome you all to 2017. Wishing you all a properous New year"
  },
  {
    "id": "2",
    "title": "Special Announcement",
    "date_created": "2017-02-17 11:15:50",
    "body": "All National Service Persons are expected to meet at the conference room at exactly 2:00 PM for a very important meeting"
  }
]

Upvotes: 1

Views: 152

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191738

[
   {

You have an array of objects, not one object.

Your exception likely says it expected a { character, but got a [. For example,

org.json.JSONArray cannot be converted to JSONObject

So, you want new JSONArray(response)

Or use Volleys JSONArrayRequest

Upvotes: 2

Related Questions