开发者

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 a ListArray (or two, one for each row. Not sure if that would be better or worse) and I just don't understand how to do it. I've tried various database manager classes that I've found but none of them do what I need and it seems that I should be able to do this simple task without the extra features I've seen in other database managers. Is there any simple way to JUST query some data from an existing SQLite database and get it into a ListArray so that I can work with it? I realize I need to copy the database from assets into the Android database path and I can handle that part. I also need to be able to modify one of the columns per row. I don't need to create databases or tables or rows. I implore someone to help me with this as I consider any code I've written (copied from the internet) to be completely useless.


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 :

private static class DatabaseHelper extends SQLiteOpenHelper{

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

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

    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜