package com.sets.speedtest.db;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import com.sets.speedtest.R;
import com.sets.speedtest.constant.C;
import com.sets.speedtest.manager.SharedPreferencesManager;
/**
* DB工具类
*
* @author : lipan
* @create_time : 2014年4月19日 下午4:36:28
* @desc :
* @update_time :
* @update_desc :
*
*/
public class DBOpenHelper extends SQLiteOpenHelper
{
private static final String DB_NAME_APPENDIX = ".db"; //
public static final String BASE_DB_NAME = "init.db"; // 基础数据
public static final String PACKAGE_NAME = "com.sets.speedtest";// 包名
public static final String BASE_DB_PATH = "/data"
+ Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME + "/files/"; // 存放数据库的位置
private Context context;
// 测速结果日志表
public static final String CREATE_RESULT_LOG = "CREATE TABLE address_info (id integer NOT NULL PRIMARY KEY AUTOINCREMENT, address_id integer NOT NULL, city text, college text, address text, seat_number integer, signal_strength integer, download integer, recommend_num integer, test_time integer )";
/**
* 系统数据库
*
* @param context
*/
public DBOpenHelper(Context contextP)
{
super(contextP, C.SQLITE_DB_NAME + DB_NAME_APPENDIX, null, C.SQLITE_DB_VERSION);
this.context = contextP;
}
@Override
public void onCreate(SQLiteDatabase db)
{
// 测速结果日志表
db.execSQL(CREATE_RESULT_LOG);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
/**
* 得到本地数据库对象
*
* @return
*/
public SQLiteDatabase openBaseDatabase()
{
try
{
// db文件位置
String dbLocation = BASE_DB_PATH + BASE_DB_NAME;
// 判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
// 或者当前基础数据版本不等于上一次的版本
// if (!(new File(dbLocation).exists()) || C.SQLITE_BASE_DB_VERSION!=SharedPreferencesManager.getInstance().getUserInfo().baseDbVersion)
// {
// 打开静态数据库文件的输入流
InputStream is = context.getResources().openRawResource(R.raw.init);
// 通过Context类来打开目标数据库文件的输出流,这样可以避免将路径写死。
FileOutputStream os = context.openFileOutput(BASE_DB_NAME, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int count = 0;
// 将静态数据库文件拷贝到目的地
while ((count = is.read(buffer)) > 0)
{
os.write(buffer, 0, count);
}
is.close();
os.close();
// 记录当前基础数据版本
SharedPreferencesManager.getInstance().setBaseDbVersion(C.SQLITE_BASE_DB_VERSION);
// }
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbLocation, null);
return db;
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}