user983965
user983965

Reputation: 1121

Array List Null Pointer Exception - Android

I am trying to create an application which retrieves the users favourite book quote however I am stuck on how to display this information back to the user. I created an ArrayList which will store all the information. However when displaying this information, I keep getting the error:

java.lang.NullPointerException

when it tries to execute the code

temp[i] = new HashMap<String,String>();

This class is shown below:

public class FavouriteQuotesActivity extends ListActivity {

    static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();

    private void getFavorites() {
        DataBaseHelper myDbHelper = new DataBaseHelper(this);

        String favorites [] = myDbHelper.getFavourites();

        if(list.size() > 0)
        {
            list.removeAll(list);
        }

        for(int i = 0;i < favorites.length; i++)
        {
            String quotes = favorites[i];
            String[] quoteArray = quotes.split(":");
            HashMap<String,String> temp[] = null; 

            temp[i] = new HashMap<String,String>();
            temp[i].put("Author",(quoteArray[2]));
            temp[i].put("Quote",(quoteArray[4]));
            list.add(temp[i]);

        }


    }

Any help would be greatly appreciated.

Upvotes: 0

Views: 1973

Answers (3)

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

temp doesn't point to an array. You are setting it to null.

You declared the variable temp as an array (by writing HashMap temp[]).

Without being it an actual array, you can't set any elements.

Upvotes: 3

Tudor
Tudor

Reputation: 62439

You are declaring and using temp wrong. You don't need an array of HashMap, just a single HashMap, since list is an ArrayList<HashMap>:

HashMap<String,String> temp = new HashMap<String,String>();
temp.put("Author",(quoteArray[2]));
temp.put("Quote",(quoteArray[4]));
list.add(temp);

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500215

Look at this code:

HashMap<String,String> temp[] = null; 
temp[i] = new HashMap<String,String>();

You've just assigned a null value to the temp variable (which would more typically have a declaration of HashMap<String, String>[] temp) - so of course you'll get a NullPointerException when you then try to access temp[i] on the very next statement.

It's not clear why you're using an array at all in that code - why aren't you just using:

HashMap<String, String> map = new HashMap<String, String>();
map.put("Author", quoteArray[2]);
map.put("Quote", quoteArray[4]);
list.add(map);

Additionally it's unclear why you're using a map at all here, given that it will always have the same two keys. Why not create a Quote class with name and author properties? Also, using a static variable here seems like a bad idea - why doesn't getFavorites create a new list on each invocation, and return it at the end of the method?

Upvotes: 6

Related Questions