「android」の編集履歴(バックアップ)一覧に戻る

android - (2012/11/25 (日) 16:41:50) のソース

*androidに関してのメモ

**SQLite

セーブデータのように次にアプリを起動した時もデータを引き出したい時は、
SQLiteOpenHelperのコンストラクタの第2引数にファイル名を渡す。
ここでありがちな名前にすると、他のアプリとかぶる場合があるので
自分のアプリ固有の名前にして、他のHelper内でも同じ名前を指定することで
↓の例だとmyapp_database.db内にMyTblで作ったテーブルが作成され、
他のクラスのコンストラクタでも同じように指定すれば、複数テーブルを登録できる。

 class MyTbl extends SQLiteOpenHelper {
    private static final int version = 1;
    public MyTbl(Context context) {
         super(context, "myapp_database.db", null, version);
    }
 }

[[参考URL>>http://ichitcltk.hustle.ne.jp/gudon/modules/pico_rd/index.php?content_id=74]]

SELECT文を使う時は
 String name = "名前";
 // ここから読み込み
 SQLiteDatabase db = &bold(){getReadableDatabase}();
 
 // 重複データがあるか確認
 Cursor c = db.query(TABLE, new String[] { Column.NAME.toString() },
 	Column.NAME.toString() + " = ?", 
        new String[] { name }, null, null, null);
 int count = c.getCount();

UPDATE文とかINSERT文を使う場合は、
 // ここから書き込み
 try {
     SQLiteDatabase db = &bold(){getWritableDatabase}();
     db.beginTransaction();
     // 既にデータがあるので、書き換える
     ContentValues content = new ContentValues();
     content.put(Column.PASSWORD.toString(), password);
     int numUpdate = db.update(TABLE, content, Column.NAME.toString() + " = ?", 
                     new String[]{ name });
     // ここでdb.insert()なども
     db.setTransactionSuccessful();
 } finally {
     db.endTransaction();
 }