Search code examples
androiddatabaseandroid-listfragment

NullPointerException while opening database through a fragment


I am trying to populate the ListFragment from one of the columns in my Database. For that i am trying to use

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

        db.open();
        db = new NotesDatabase(getActivity());
        c = db.getAllRows();

    getActivity().startManagingCursor(c);

    String[] fromField = new String[] { NotesDatabase.KEY_TITLE };
    int[] toView = new int[] { R.id.item_title };
    SimpleCursorAdapter myCAdapter = new SimpleCursorAdapter(getActivity(),
            R.layout.list_item, c, fromField, toView, 0);
    setListAdapter(myCAdapter);
}

but i dont know why i am getting a NullPointerException on db.open(); and c = db.getAllRows();

db.open()
    public NotesDatabase open() {
    db = myDBHelper.getWritableDatabase();
    return this;
    }

db.getAllRows();

    public Cursor getAllRows() {
    String where = null;
    Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
            null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
    }

DBHelper

    private static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

or if there is a better a better way to populate the list view of fragment from a database? Thanks in Advance :)


Solution

  •         db.open();
            db = new NotesDatabase(getActivity());
            c = db.getAllRows();
    
    1. Open the database
    2. Create the database
    3. Get all the rows.

    Logically speaking. create it first. then open. then get all the rows. So swithc line 1 and lone 2.

    Another thing is that , I assume your getting NPE at myDBHelper, because you never created that helper.