Null Pointer Exception While Retrieving Json Object
Solution 1:
There are a number of problems in your code although not necessarily all would be directly related to your NullPointerException...
- In your - getJSONFromUrlmethod you are using- HttpPostwhen it doesn't seem like you're actually posting anything. Use- HttpGetinstead.
- When reading a JSON string from a response, use the - getContentLength()method of- HttpEntityto create a byte array such as (example)...- byte[] buffer = new byte[contentLength]and simply read the- InputStreamas...- 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".
- 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")
- Never specify - iso-8859-1encoding for anything if you can really avoid it.
- When you create your - Toastin 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'scode you can simply use- thisfor the- Contextwhen creating a- Toast.
- As others have mentioned, make sure you check for a - nullreturn everywhere they can possibly happen. If an exception occurs in a method and the return is- nullmake sure whatever code called that method checks for- null.
Solution 2:
use get instead of getString as:
try {
    JSONObject jsona=newJSONObject("{'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");
            }
Solution 3:
Carefully see your code
try {
            jObj = newJSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON Stringreturn 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();
}
Post a Comment for "Null Pointer Exception While Retrieving Json Object"