I have a class which extends ListActivity within I have all methods for managing database items: insertItems(), getItems(), showItems(), etc. Everything works great when I populate this list view with items from the database. What I want to do, is to populate in the same way an another ListView from another activity but when I am trying to pass the cursor to that activity I get NullPointer Exception. I try to put what is most representative.
public class FOO extends ListActivity{
//...
public static DBAdapter items;
@override
public void onCreate(){
//...
items = new DBAdapter(this);
//...
}
public static Cursor getAllItems() {
// TODO Auto-generated method stub
db = items.getReadableDatabase();
return db.query(DBConstants.TABLE_NAME, FROM, null, null, null, null, null);
}
then, in the second activity I have:
public class BAR extends ListActivity{
//.....
public FOO foo = new FOO();
Cursor cursor;
//...
public static DBAdapter items;
@override
public void onCreate(){
//...
items = new DBAdapter(this);
foo.insertItems(//arguments);
this.cursor = foo.getAllItems();
this.startManagingCursor(this.cursor);
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.item_list, cursor, FROM, TO);
setListAdapter(adapter);
}
What I get first is this error, where MainActivity = BAR
E/AndroidRuntime(22923): java.lang.RuntimeException: Unable to start activity ComponentInfo{your.pack.databasae/your.pack.databasae.MainActivity}: java.lang.NullPointerException
public FOO foo = new FOO();You should never be creating activities like this, its up to the framework to construct activities as needed. That said if you need to do it this way, make sure
itemsanddbare created in the constructor for FOO (typical code would have it get created inonCreate()which would lead to a NPE here). Nothing in BAR ever calls FOO’s onCreate soitemsand presumablydbare both null.Alternatively, try to refactor your code such that the database management code is available in a separate class accessible from both ListActivity classes.