Java/Androidのローカルストレージに対するcreate/read/update処理をまとめる

スマホのアプリを作る場合はほとんどCloudにデータを置くのが一般的だが、
Androidのローカルストレージにデータを置きたい場合があると思う。

そのための処理をJavaで実装したので、備忘のためにまとめておく。

ローカルストレージにアクセスするためのヘルパー

[java]
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
static final String DB_NAME = “testdb”; // DB名
static final int DB_VERSION = 1; // DBのVersion
static final String DB_TABLE = “testtable”;

public MySQLiteOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(“create table if not exists ” + DB_TABLE +
“(id integer primary key, somenumer integer)”);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(“drop table if exists ” + DB_TABLE);
onCreate(db);
}
}
[/java]

create/update処理

[java]

MySQLiteOpenHelper mydb = new MySQLiteOpenHelper(this);
db = mydb.getWritableDatabase();

public void writeDB(Integer id, Integer somenumber){
ContentValues values = new ContentValues();
values.put(“id”,id);
values.put(“somenumber”, somenumber);

int colNum = db.update(MySQLiteOpenHelper.DB_TABLE, values, “id = ” + id, null);
// updateされなかったら。
if (colNum == 0){
db.insert(MySQLiteOpenHelper.DB_TABLE, “”, values);
}

}
[/java]

Read処理

[java]
public class Completedb {
public Integer id;
public Integer somenumber = 0;
}

public Completedb readDB(Integer id) throws Exception {
Completedb cdb = new Completedb();
Cursor c = db.query(MySQLiteOpenHelper.DB_TABLE, new String[]{“id”, “somenumber”},
“id=” + id, null, null, null, null);
if (c.getCount() == 0){
cdb.somenumber = -1;
c.close();
return cdb;
}
c.moveToFirst();
cdb.id = c.getInt(0);
cdb.somenumber = c.getInt(1);
c.close();

return cdb;
}
[/java]

Deleteはいまつくっているアプリでは使わないからまた使うタイミングにまとめようと思う。


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *