Eriz
Eriz

Reputation: 972

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 :)

Upvotes: 0

Views: 423

Answers (4)

jacknad
jacknad

Reputation: 13739

You are doing the db.open before the new so it doesn't exist yet, you are trying to open a null db.

Upvotes: 0

wtsang02
wtsang02

Reputation: 18863

        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.

Upvotes: 1

Zoubiock
Zoubiock

Reputation: 1165

Just initialise your databasehelper before opening it: db = new DatabaseHelper(this);

Upvotes: 0

Rajeev
Rajeev

Reputation: 1404

aren't you doing it reverse?

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

Upvotes: 1

Related Questions