SQLiteLocationDB.java
package info.kamogashira.sharemapwidget.lib;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class SQLiteLocationDB {
private Context context;
private SQLiteDatabase db;
private static int DB_MODE = Context.MODE_PRIVATE;
private final static String DB_NAME = "location.db";
private final static String DB_TABLE = "location_table";
private final static int DB_VERSION = 1; TODO
private SharedPreferences pref;
private int defValue = 1;
public SQLiteLocationDB(Context context) {
this.context = context;
pref = context.getSharedPreferences(DB_NAME, Context.MODE_PRIVATE);
int ver = pref.getInt("VER", defValue);
if (ver != DB_VERSION) {
try {
db = context.openOrCreateDatabase(DB_NAME, DB_MODE, null);
String sql = "drop table " + DB_TABLE + ";";
db.execSQL(sql);
Log.v("SQLiteLocationDb", "DB is updated , table droped");
} catch (Exception e) {
Log.e("SQLiteLocationDB", "Drop table:" + e);
}
}else{
Log.v("SQLiteLocationDB","DB is not updated");
}
SharedPreferences.Editor editor = pref.edit();
editor.putInt("VER", DB_VERSION);
editor.commit();
}
public boolean openDB() {
boolean resultFLG = false;
db = null;
try {
db = context.openOrCreateDatabase(DB_NAME, DB_MODE, null);
String sql = "create table if not exists " + DB_TABLE + " ("
+ "id integer primary key autoincrement, "
+ "lineNum text ," + "posX integer ," + "posY integer ,"
+ "datetime text" + ");";
Log.d("createTable", sql);
db.execSQL(sql);
resultFLG = true;
} catch (Exception e) {
db = null;
Log.e("opencreate", "" + e);
}
return resultFLG;
}
public boolean closeLocationDB() {
db.close();
return true;
}
public void insertLocation(int posX, int posY) {
try {
Date date = Calendar.getInstance().getTime();
String lineNum = _Util.getLineNumber(context);
String sql = "insert into " + DB_TABLE
+ " (lineNum , posX , posY , datetime) values (" + "'"
+ lineNum + "'," + posX + "," + posY + " ,'"
+ MyDateFormat.date2string(date) + "');";
Log.v("SQL", sql);
db.execSQL(sql);
} catch (Exception e) {
Log.e("InsertSQL", "" + e);
}
}
public int getCount() {
int count = 0;
Cursor resultSet;
String sql = "select count(*) from " + DB_TABLE;
resultSet = db.rawQuery(sql, null);
resultSet.moveToFirst();
count = resultSet.getInt(0);
return count;
}
private static class MyDateFormat {
private static final String DATE_PATTERN = "yyyy/MM/dd HH:mm:ss.SSS";
private static SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
public static String date2string(Date date) {
return sdf.format(date);
}
public static Date string2date(String str) {
try {
return sdf.parse(str);
} catch (Exception e) {
return null;
}
}
}
}