Populating listview from a different activity with items from a SQLite database

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

Answers


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 items and db are created in the constructor for FOO (typical code would have it get created in onCreate() which would lead to a NPE here). Nothing in BAR ever calls FOO's onCreate so items and presumably db are 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.


Need Your Help

Does ActiveRecord find_all_by_X preserve order? If not, what should be used instead?

ruby-on-rails activerecord

Suppose I have a non-empty array ids of Thing object ids and I want to find the corresponding objects using things = Thing.find_all_by_id(ids). My impression is that things will not necessarily hav...

Ostensible inconsistencies in singleton types

scala types programming-languages type-systems singleton-type

I have a couple of questions about singleton types, but since they're both very closely related, I am posting them under the same thread.