凌空响应下的代码未触发

时间:2017-02-18 12:16:19

标签: android json android-volley

我有这个基本的例子,但问题是我在响应中写下的任何东西都不会触发甚至是Toast。以下是我的代码。

公共类MainActivity扩展了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);
        }


    });


}

}

我的后端代码,URL指向没有问题,因为它返回一个json响应。 JsonException catch部分中的代码是给出响应。这很奇怪。

[
   {
       "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"
  }
]

1 个答案:

答案 0 :(得分:1)

[
   {

你有一个对象数组,而不是一个对象。

你的例外可能会说它预期{字符,但得到了[。例如,

  

org.json.JSONArray无法转换为JSONObject

所以,你想要new JSONArray(response)

或使用Volleys JSONArrayRequest