1

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 pointer exception. Please help.

Here is my code.

public class PNRStatusActivity extends Activity {
    private static final String TAG_CONTACTS = "contacts";
    static InputStream is = null;
    JSONObject jObj = null;
    static String json = "";
    JSONArray contacts = null;
    private static String url = "http://pnrapi.appspot.com/4051234567";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Creating JSON Parser instance
        JSONObject jon=getJSONFromUrl(url);

        try {
            // Storing each json item in variable
            String id = jon.getString("status");
            Toast.makeText(getApplicationContext(), id, Toast.LENGTH_LONG).show();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //function to get JSON Object
    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

3 Answers 3

3

There are a number of problems in your code although not necessarily all would be directly related to your NullPointerException...

  1. In your getJSONFromUrl method you are using HttpPost when it doesn't seem like you're actually posting anything. Use HttpGet instead.

  2. When reading a JSON string from a response, use the getContentLength() method of HttpEntity to create a byte array such as (example)...

    byte[] buffer = new byte[contentLength] and simply read the InputStream as...

    inStream.read(buffer). You will need to do error checking along the way of course. In your case you're attempting to read a string line by line and appending "n" to each line. Firstly you don't need to read a JSON string in this way and if you're actually intending to append a newline character (at any time in any Java code), it should be "\n".

  3. To convert your byte array to a usable string for JSON parsing you then simply do the following...

    String jsonString = new String(buffer, "UTF-8")

  4. Never specify iso-8859-1 encoding for anything if you can really avoid it.

  5. When you create your Toast in your Activity onCreate(...) method, you use getApplicationContext(). Don't use the application context unless you're really sure of when and where you should use it. In the main body of an Activity's code you can simply use this for the Context when creating a Toast.

  6. As others have mentioned, make sure you check for a null return everywhere they can possibly happen. If an exception occurs in a method and the return is null make sure whatever code called that method checks for null.

Sign up to request clarification or add additional context in comments.

Comments

1

use get instead of getString as:

try {
    JSONObject jsona=new JSONObject("{'status': 'INVALID', 'data': 'No results'}");
    String id = (String)jsona.get("status");
    Toast.makeText(DfgdgdfgdfActivity.this, id, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

EDIT:

use

while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

instead of

while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }

1 Comment

Did you spot the line sb.append(line + "n")? Also the OP is using a stream reader with iso-8859-1 encoding. The code is broken in at least 3 or 4 different places that I can see.
1

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();
}

3 Comments

Error parsing data org.json.JSONException: A JSONObject text must begin with '{'. This is what i get. But the object that is returned indeed starts with a '{'. pnrapi.appspot.com/4051234567 try the link.
Did you spot the line sb.append(line + "n")? Also the OP is using a stream reader with iso-8859-1 encoding. The code is broken in at least 3 or 4 different places that I can see.
"{'status': 'TIMEOUT', 'data': 'Request Timed Out'} which is not valid JSON" - How is that NOT valid JSON? It is as equally valid as the expanded / indented JSON you show in the code block where you say "It should be"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.