My code below shows this warning:
Null pointer access: The variable civs can only be null at this
location
public static List<String> getCivs(String game) {
List<String> civs = null;
System.err.printf("game: %s\n", game);
SQLiteDatabase db = godSimDBOpenHelper.getReadableDatabase();
String where = GAME_COLUMN + "= ?";
Cursor cursor = db.query(GAMES_TABLE, new String[] {CIV_COLUMN}, where, new String[] {game}, null, null, null);
while (cursor.moveToNext()) {
System.err.println("now here");
System.err.println(cursor.getString(0));
civs.add(cursor.getString(0)); //warning appears for this line
}
return civs;
}
Sure enough, when I run this, it crashes. I don’t understand why this has to be null, by definition. I realize that I am initializing the variable to null (I only do this because Eclipse gives me another error if I don’t), but I am adding values to the list inside of the while loop. Doesn’t that mean that it is no longer null?
I’m sorry if I am being dense, but I just can’t see what it wrong here. Maybe in the way that I am initializing the varialble. Just not sure.
Thanks!
The reason its failing is that the variable
civsisnullat the time you try and run the add method on it. So in effect, you are trying to reference a class instance which does not exist(all you done is created a variable which is capable of pointing to a class instance of a class implementing the List interface).So, to make this work, you must make this variable (which currently points at nothing) point at something meaningful. In this case, it means you must create a new instance of a class implementing the list interface and set your variable to point to that instance.
try the following
Just a little tip, this is pretty preliminary stuff, you will safe you’re self a lot of frustration if you invest a bit of time and read though the core java trails at oracle.
http://docs.oracle.com/javase/tutorial/