Ngo Van
Ngo Van

Reputation: 887

Android: Get json from URL - nullPointerException

I try to load Json from URL. By not using AsyncTask class on previous version, It worked well.
However call getJSONFromUrl(currentURL) directly from main Thread (someone told me) is not accepted in 3.2 or higher Android versons.
So, I tried by the following code.
this is my code:

private static String urlTruyenMoiNhat = "myUrl";
private static String currentURL = urlTruyenMoiNhat;
private static JSONObject jSonGetFromCurrentURL = null;

//some stuff....
currentURL = urlTruyenMoiNhat;
GetJsonAsync getJson = new GetJsonAsync();
getJson.execute();
RetreiveListStory(jSonGetFromCurrentURL);

This is my GetJsonAsync class:

private class GetJsonAsync extends AsyncTask <String, Void, String> {

    @Override
    protected void onPreExecute() {
        // Do stuff before the operation
    }

    protected String doInBackground(String... params){
        JSONParser jParser = new JSONParser();
        jSonGetFromCurrentURL = jParser.getJSONFromUrl(currentURL);
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // Do stuff after the operation
    }
}

I don't know why it through exception:

11-28 13:30:44.084: E/AndroidRuntime(828): FATAL EXCEPTION: main
11-28 13:30:44.084: E/AndroidRuntime(828): java.lang.RuntimeException: Unable to start activity ComponentInfo{vn.truyencuoihay/vn.truyencuoihay.MainActivity}: java.lang.NullPointerException  

Please help me overcome this problem.
Thanks!

Upvotes: 0

Views: 233

Answers (2)

gbl
gbl

Reputation: 188

why are u returning null at this line- jSonGetFromCurrentURL = jParser.getJSONFromUrl(currentURL); return null;

return jSonGetFromCurrentURL.instead of null.

Upvotes: 0

Shankari vatsalkumar
Shankari vatsalkumar

Reputation: 698

What actually happens in AsyncTask is when u call execute.. it starts a separate thread.. and all your other commands are excuted in Oncreate() without waiting for the result (in your case jSonGetFromCurrentURL)form AsyncTask .. so u get null pointer exception..

write this line in onPostExecute();

RetreiveListStory(jSonGetFromCurrentURL);

FYI AsyncTask

actually means

AsyncTask <String input, Void progress, String result> 

Upvotes: 1

Related Questions