Skip to content Skip to sidebar Skip to footer

Select Data From Sqlite Into Listarrays

I've been racking my brain on this for days and I just can't wrap my head around using SQLite databases in Android/Java. I'm trying to select two rows from a SQLite database into

Solution 1:

You can create a method like this :

private List<MyItem> getAllItems()
    List<MyItem> itemsList = new ArrayList<MyItem>();
    Cursor cursor = null;
    try {
        //get all rows
        cursor = mDatabase.query(MY_TABLE, null, null, null, null,
                null, null);
        if (cursor.moveToFirst()) {
            do {
                MyItem c = new MyItem();
                c.setId(cursor.getInt(ID_COLUMN));
                c.setName(cursor.getString(NAME_COLUMN));
                itemsList.add(c);
            } while (cursor.moveToNext());
        }
    } catch (SQLiteException e) {
        e.printStackTrace();
    } finally {
        cursor.close();
    }
    return itemsList;
}

This will be inside your class let say MyDatabaseHelper where you will also have to declare a :

privatestaticclassDatabaseHelperextendsSQLiteOpenHelper{

    privatefinalstatic String DATABASE_CREATE="create table " + MY_TABLE + " (id integer primary key, country string);";

    publicDatabaseHelper(Context context,String name, CursorFactory factory, int version){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @OverridepublicvoidonCreate(SQLiteDatabase db){
        db.execSQL(DATABASE_CREATE);
    }

    @OverridepublicvoidonUpgrade(SQLiteDatabase db, int oldVersion, 
                          int newVersion){
        Log.w(TAG, "Upgrading database from version " + oldVersion 
              + " to "
              + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS "+ MY_TABLE);
        onCreate(db);
    }
}    

used to open() and close() the database.

Post a Comment for "Select Data From Sqlite Into Listarrays"