Null Pointer Exception while retrieving JSON object

前端 未结 3 754
既然无缘
既然无缘 2021-01-24 05:35

I am new to JSON. I am using http://pnrapi.appspot.com/ to get the status of a particular train using JSON. But while trying to parse the received object i always get a null poi

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 06:16

    Carefully see your code

        try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    

    In above case if you get any JSONException then you are returning jObj which is not initialized,in short you will return null jObj.

    So you much handle that situation by checking if returned object is null.

    change your code to following

    if (jon != null)
    {
        String id = jon.getString("status");
        Toast.makeText(getApplicationContext(), id, Toast.LENGTH_LONG).show();
    }
    

提交回复
热议问题