samedi 13 juin 2015

Android Database Access Pattern

Is this the appropriate way to do database access in an Android app? Should I be opening and closing database connections like this, or should I have one SQLiteDatabase object that I continually run queries against? Is my method for get specific column data from the cursor appropriate?

public List<Object> getObjects() {
    SQLiteDatabase db = SQLiteDatabase.openDatabase(this.path, null, SQLiteDatabase.OPEN_READONLY);

    List<Object> ret = new ArrayList<Object>();

    Cursor cursor = db.rawQuery("select * from objects", null);

    while(cursor.moveToNext())
    {
        Object obj = new Object();

        obj.setId(cursor.getInt(cursor.getColumnIndex("ID")));
        obj.setTitle(cursor.getString(cursor.getColumnIndex("Title")));

        ret.add(obj);
    }

    db.close();

    return ret;
}

Aucun commentaire:

Enregistrer un commentaire