Skip to content

Instantly share code, notes, and snippets.

@sdkfz181tiger
Created November 15, 2014 01:38
Show Gist options
  • Save sdkfz181tiger/84cfd00f4a31fe91411b to your computer and use it in GitHub Desktop.
Save sdkfz181tiger/84cfd00f4a31fe91411b to your computer and use it in GitHub Desktop.
SQLite覚え書き(Android)
package com.ozateck.db;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/*
* [データベース]アクセスオブジェクト
*/
public class SQLiteDAO{
private static final String TAG = "SQLiteDAO";
// main
public static final String TABLE_NAME = "main";
public static final String COL_uid = "uid";
public static final String COL_mName = "mName";
public static final String COL_mLat = "mLat";
public static final String COL_mLon = "mLon";
public static final String COL_mStatus = "mStatus";
/*
* テーブル情報の取得
*/
// 全てのデータを取得
public static ArrayList<HashMap<String, String>>
getAllList(SQLiteDatabase db){
String sql = "SELECT * FROM " + TABLE_NAME;
return getArrayList(db, sql);
}
/*
* DB,SQLからArrayListを取得
*/
private static ArrayList<HashMap<String, String>>
getArrayList(SQLiteDatabase db, String sql){
ArrayList<HashMap<String, String>> list =
new ArrayList<HashMap<String, String>>();
Cursor c = db.rawQuery(sql, null);
int total = c.getCount();
c.moveToFirst();
for(int i=0; i<total; i++){
String[] strs = c.getColumnNames();// key
HashMap<String, String> map = new HashMap<String, String>();
for(int s=0; s<strs.length; s++){
Log.i(TAG, "key:" + strs[s] + "_" + c.getString(s));
map.put(strs[s], c.getString(s));
}
list.add(map);
c.moveToNext();
}
c.close();
return list;
}
// Insert
public static void insert(SQLiteDatabase db){
ContentValues cValues = new ContentValues();
cValues.put(COL_mName, "Yabacho");
cValues.put(COL_mLat, 100.0d);
cValues.put(COL_mLon, 200.0d);
cValues.put(COL_mStatus, "WIFI");
long result = db.insert(TABLE_NAME, null, cValues);
Log.d(TAG, "result:" + result);
}
// Delete
public static void delete(SQLiteDatabase db, int uid){
int result = db.delete(TABLE_NAME, COL_uid + " = ?", new String[]{String.valueOf(uid)});
Log.d(TAG, "result:" + result);
}
// Count
public static int count(SQLiteDatabase db){
Cursor c = db.rawQuery("SELECT count(*) as cnt FROM " + TABLE_NAME, null);
c.moveToFirst();
int count = c.getInt(c.getColumnIndex("cnt"));
c.close();
return count;
}
/*
* データ確認用
*/
// 配列データの確認(List)
public static void checkList(List<HashMap<String, String>> list){
Log.i(TAG, "-checkList-");
for(int s=0; s<list.size(); s++){
Log.d(TAG, "-[" + s + "]-");
HashMap<String, String> map = list.get(s);
Set<String> keySet = map.keySet();
for(Iterator<String> it = keySet.iterator(); it.hasNext();){
String key = it.next();
String value = map.get(key);
Log.d(TAG, "key:" + key + "_value:" + value);
}
}
}
// 配列データの確認(Array)
public static void checkArray(int[] array){
Log.i(TAG, "-checkArray-");
for(int i=0; i<array.length; i++){
Log.d(TAG, "array:" + array[i]);
}
}
}
package com.ozateck.db;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.SQLException;
import android.util.Log;
public class SQLiteOpenHelperLocal extends SQLiteOpenHelper{
private static final String TAG = "SQLiteOpenHelperLocal";
// データベースパスとファイル名
public static String DB_PATH;
public static String DB_NAME;
private Context context;
private SQLiteDatabase db;
public SQLiteOpenHelperLocal(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
// ファイルのパス
DB_PATH = context.getFilesDir().getPath();
DB_NAME = "master.sqlite";
// DBが存在しない場合にシステムパス上にDBを作成
if(isExists()){
Log.d(TAG, "MySQLiteOpenHelper isExists:true");
//updateDB();// テスト時に利用(強制リフレッシュ)
}else{
Log.d(TAG, "MySQLiteOpenHelper isExists:false");
updateDB();// DBを作成
}
}
@Override
public void onCreate(SQLiteDatabase db){
Log.d(TAG, "MySQLiteOpenHelper onCreate");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
Log.d(TAG, "MySQLiteOpenHelper onUpgrade");
}
@Override
public synchronized void close(){
super.close();
Log.d(TAG, "MySQLiteOpenHelper close");
if(db != null)
db.close();
}
// DBファイルの初期化
public void updateDB(){
//アプリのデフォルトシステムパスに作られる
this.getReadableDatabase();
//assetに格納したデータベースをコピーする
copyDatabaseFromAsset();
}
// DBの存在を確認する
public boolean isExists(){
boolean exist = false;
String dbPath = DB_PATH + DB_NAME;
File file = new File(dbPath);
if(file.exists()){
try{
db = SQLiteDatabase.openDatabase(dbPath, null,
SQLiteDatabase.OPEN_READONLY);
if(db != null)
db.close();
exist = true;
}catch(SQLiteException e){
Log.d(TAG, "SQLE:" + e.toString());
exist = false;
}
}else{
exist = false;
}
return exist;
}
// assetに格納したDBをデフォルトのDBパスに作成し、コピーする
private void copyDatabaseFromAsset(){
try{
// DBを格納するディレクトリを自作
File databaseDir = new File(DB_PATH);
if (!databaseDir.exists()) databaseDir.mkdirs();
// asset内のDBにアクセス
InputStream is = context.getAssets().open(DB_NAME);
// デフォルトのDBパスに作成した空のDB
String dbPath = DB_PATH + DB_NAME;
OutputStream os = new FileOutputStream(dbPath);
// コピー
byte[] buffer = new byte[1024];
int size;
while((size = is.read(buffer)) > 0){
os.write(buffer, 0, size);
}
// クローズ
is.close();
os.flush();
os.close();
Log.d(TAG,"DB Copy:success");
}catch(IOException e){
Log.e(TAG, "IOE:" + e.toString());
Log.d(TAG, "DB Copy:failed");
}
}
// DBを開く
public SQLiteDatabase openDataBase(){
try{
String dbPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(
dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}catch(SQLiteException e){
Log.d(TAG, "SQLE:" + e.toString());
}
return db;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment