Skip to content Skip to sidebar Skip to footer

Android: Json Parse: Null Object Reference When Attempting To Parse Json Into A Listview

This app is supposed to parse some JSON data (hard coded for now) from the Google Books API, and pass an ArrayList of Books to the adapter that will display it on a ListView. The p

Solution 1:

The issue is that one of the arguments in BookAdapter adapter = new BookAdapter(this, bookList); is null for some reason. Try passing bookList as an argument to updateDisplay and checking whether it's not null.

publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener {

ProgressBar pBar;
List<MyTask> tasks;

ArrayList<Book> bookList;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pBar = (ProgressBar) findViewById(R.id.progressBar);
    pBar.setVisibility(View.INVISIBLE);

    Button sButton = (Button) findViewById(R.id.s_button);
    sButton.setOnClickListener(this);

    tasks = newArrayList<>();

}

@OverridepublicvoidonClick(View v) {
    switch (v.getId()) {
        case R.id.s_button: {
            if (isOnline()) {
                newMyTask().execute("https://www.googleapis.com/books/v1/volumes?q=millionare"); //https://www.googleapis.com/books/v1/volumes?q=soft+skills

            } else {
                Toast.makeText(this, "Connection failed", Toast.LENGTH_LONG).show();
            }
            break;
        }
    }
}

protectedbooleanisOnline() {

    ConnectivityManager connectManager = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo netInfo = connectManager.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        returntrue;
    } else {
        returnfalse;
    }
}

privateclassMyTaskextendsAsyncTask<String, Void, String> {

    @OverrideprotectedvoidonPreExecute() {
        super.onPreExecute();
    }

    @OverrideprotectedStringdoInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.try {
            returnHttpManager.getData(urls[0]);
        } catch (IOException e) {
            return"Unable to retrieve web page. URL may be invalid.";
        }
    }

    @OverrideprotectedvoidonPostExecute(String result) {
        ArrayList<Book> bookList = BookJSONParser.parseFeed(result);
        updateDisplay(bookList);
    }

}

protectedvoidupdateDisplay(ArrayList<Book> bookList) {
    if (bookList != null){
        BookAdapter adapter = newBookAdapter(this, bookList);

        ListView listView = (ListView) findViewById(R.id.list);

        listView.setAdapter(adapter);
     }
}
}

Solution 2:

It would appear you are getting a JSONParseException... therefore causing a NullPointerExpcetion for the List into the Adapter

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

That is your error, here is how you get it

publicstaticArrayList<Book> parseFeed(String content) {

    try {
        JSONArray jsonArray = newJSONArray(content); // <-- Throws an errorArrayList<Book> bookList = newArrayList<>();

        // Stuff...return bookList;
    } catch (JSONException e) {
        e.printStackTrace();
        returnnull; // <----- Null is returned
    }

And you use that null value here

@OverrideprotectedvoidonPostExecute(String result) {
        bookList = BookJSONParser.parseFeed(result);
        updateDisplay();
    }

Followed by

protectedvoidupdateDisplay() {

    BookAdapteradapter=newBookAdapter(this, bookList); // <-- Null hereListViewlistView= (ListView) findViewById(R.id.list);

    listView.setAdapter(adapter);
}

So, the way to fix that NullPointerExpception is to always return an ArrayList

ArrayList<Book> bookList = newArrayList<>();
try {
    JSONArray jsonArray = newJSONArray(content);

    // Stuff...
} catch (JSONException e) {
    e.printStackTrace();
}

return bookList;

Solution 3:

to get json string from url you should do it like that

String content = new MyTask()
         .execute("https://www.googleapis.com/books/v1/volumes?q=millionare")
         .get();
//pass the content to BookJSONParser class
booklist = new BookJSONParser().parseFeed(content);
updateDisplay();

what you get from the url you provided is NOT jsonArray it's a jsonobject so I think this code will work "assuming that you did everything else correctly"

JSONObject o = newJSONObject(content);
JSONArray jsonArray = o.getJSONArray("items");

the you can do the for loop

Post a Comment for "Android: Json Parse: Null Object Reference When Attempting To Parse Json Into A Listview"