Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

Hello I keep getting NPE when I try to get an object from my jsonString. I tried alot of things even changed my json a coople of times but it's just not working. The HTTPResponse works fine and when I log "myObject" it gives the right object. But when I try to get the object in it it gives me a NPE. I tested the json and it is valid. I also tried to retrieve an array instead of an object but it also gives an NPE. Can someone tell me how to fix this.

I made a simple jsontester activity to test my json:

public class JSONTester extends Activity {

private DefaultHttpClient createHttpClient() {
    HttpParams my_httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(my_httpParams, 3000);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ThreadSafeClientConnManager multiThreadedConnectionManager = new ThreadSafeClientConnManager(my_httpParams, registry);
    DefaultHttpClient httpclient = new DefaultHttpClient(multiThreadedConnectionManager, my_httpParams);
    return httpclient;
}

MikeyJSON mJSON;

Button mBtnGo;
TextView mTxt1;
TextView mTxt2;
TextView mTxt3;
TextView mTxt4;
ProgressDialog mProgressDialog;
private String lang;        
private int length;     // 0 - 6 (length 7 to length 12)
private int wordPos;        // 0 - array length

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

    mTxt1 = (TextView) findViewById(R.id.txt1);
    mTxt1 = (TextView) findViewById(R.id.txt1);
    mTxt1 = (TextView) findViewById(R.id.txt1);
    mTxt1 = (TextView) findViewById(R.id.txt1);
    mBtnGo = (Button) findViewById(R.id.btnGo);

}

public boolean isNumeric(String str) {

    for(int i=0;i<str.length();i++) {

        if(Character.isDigit(str.charAt(i))) {
            return true;
        }
    }
    return false;
}

public void testJSON(View view) {
    if(view==mBtnGo) {

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("loading");
        mProgressDialog.show();
        new DownloadNewWords().execute();
    }

}
private class DownloadNewWords extends AsyncTask<Void, Void, Void> {

    int mStatusCode = 0;
    String mResultString;
    Exception mConnectionException;

    @Override
    protected Void doInBackground(Void... args) {

            String fetchUrl = "http://www.mikeywebs.nl/json/jsonexample.html";
            DefaultHttpClient httpclient = createHttpClient();
        HttpGet httpget = new HttpGet(fetchUrl);

        try {
            HttpResponse response = httpclient.execute(httpget);
            StatusLine statusLine = response.getStatusLine();
            mStatusCode  = statusLine.getStatusCode();
                if (mStatusCode == 200){
                mResultString = EntityUtils.toString(response.getEntity());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            mConnectionException = e;
        } catch (IOException e) {
            e.printStackTrace();
            mConnectionException = e;
        }
        return null;            
    }

        @Override
    protected void onPostExecute(Void arg) {
        mProgressDialog.dismiss();
        if (mStatusCode  == 200){
            mJSON = new MikeyJSON(mResultString);   
            lang = "English";   //Integer.parseInt(langu);
            length = 7;  //Integer.parseInt(wordl);
            wordPos = 0;
            String getWord = mJSON.getResult(lang, length, wordPos);
            mTxt4.setText(getWord);

        }
        else {
            Toast.makeText(JSONTester.this, "Gegevens konden niet worden opgehaald. Controleer uw internetverbinding en probeer het opnieuw (" +mConnectionException.toString() + ")" , Toast.LENGTH_LONG).show();
            mJSON = null;
        }
    }
}

}

And the jsonclass I use is:

public class MikeyJSON {

private JSONObject myObject;
private JSONArray jsonArray;

int i;


public MikeyJSON(String jsonString) {
    Log.i("JSON", "jsonString: " + jsonString);
    try {
        JSONObject myObject = new JSONObject(jsonString);
        Log.i("JSON", "myObject_Object: " + myObject.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public String getResult(String lang, int length, int wordPos) {
    String word = "0";  
    //0 is Nederlands 1 is English
    int la = 0;
    if(lang.equals("English")) { 
        la = 1;
    }
    //make String length
    String le = "length" + Integer.toString(length);
    Log.i("PARSE", "get_length: " + le);

    //the json
    try {
        jsonArray = myObject.getJSONArray("galgjejson");
        Log.i("JSON", "jsonArray: " + jsonArray.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return word;        
}
}

Here is the json:

{ "galgjejson" : [
                { "Nederlands" :  [
                                        { "length7" : [ 
                                                            { "word" : "android" }, 
                                                            { "word" : "camping" },
                                                            { "word" : "koekjes" }
                                                        ]
                                        }
                                ]   
                },
                { "English" : [
                                        { "length7" : [ 
                                                            { "word" : "android" }, 
                                                            { "word" : "camping" },
                                                            { "word" : "koekjes" }
                                                        ]
                                        }
                                ]
                }               
            ]                                               
}

and here is the log:

03-18 14:06:23.178: I/JSON(6719): myObject_Object: {"Nederlands":[{"length7":
[{"word":"android"},{"word":"camping"},{"word":"koekjes"}]}]}
03-18 14:06:23.178: I/PARSE(6719): get_length: length7
03-18 14:06:23.178: D/AndroidRuntime(6719): Shutting down VM
03-18 14:06:23.178: W/dalvikvm(6719): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
03-18 14:06:23.207: E/AndroidRuntime(6719): FATAL EXCEPTION: main
03-18 14:06:23.207: E/AndroidRuntime(6719): java.lang.NullPointerException
03-18 14:06:23.207: E/AndroidRuntime(6719):     at me.mikey.my.games.galgjex.MikeyJSON.<init>(MikeyJSON.java:38)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at me.mikey.my.games.galgjex.JSONTester$DownloadNewWords.onPostExecute(JSONTester.java:128)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at me.mikey.my.games.galgjex.JSONTester$DownloadNewWords.onPostExecute(JSONTester.java:1)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.AsyncTask.finish(AsyncTask.java:631)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.Looper.loop(Looper.java:137)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.app.ActivityThread.main(ActivityThread.java:4745)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at java.lang.reflect.Method.invoke(Method.java:511)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at dalvik.system.NativeStart.main(Native Method)

oh and line 38 is:

jsonArray = myObject.getJSONArray("galgjejson");
share|improve this question
3  
Dude. If we didn't give you the right answer, change the old question, or edit it to update. Don't repost the exact thing, because otherwise, someone who didn't see the outcome of the first will close this as a duplicate. At the very least, if you do want to open a new question, mark one of our posts as the answer in the old thread –  Matt Taylor Mar 18 '13 at 14:34
add comment

marked as duplicate by Kev Mar 20 '13 at 2:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

up vote 1 down vote accepted

myObject is most likely null since you have it in your class and then privately within mikeyJSON. You should probably try:

private JSONObject myObject;
private JSONArray jsonArray;

int i;


public MikeyJSON(String jsonString) {
Log.i("JSON", "jsonString: " + jsonString);
try {
    myObject = new JSONObject(jsonString);
    Log.i("JSON", "myObject_Object: " + myObject.toString());
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}

Looking at that JSON I am pretty sure you can create the JSONArray using the string in your constructor instead of a JSONObject.

Edited example.

private JSONArray jsonArray;

int i;

public MikeyJSON(String jsonString) {
try {
    jsonArray = new JSONArray(jsonString);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}
share|improve this answer
 
Good spot on variable scope! –  Matt Taylor Mar 18 '13 at 14:40
add comment

As the first line of your Logcat shows:

03-18 14:06:23.178: I/JSON(6719): myObject_Object: {"Nederlands":[{"length7": [{"word":"android"},{"word":"camping"},{"word":"koekjes"}]}]}

At this point, you already have the JSONArray marked as "galgjejson", so you need to instead change line 38 to:

jsonArray = myObject.getJSONArray("Nederlands");

Which will get you the next JSONArray for processing

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.