- public class DatabaseHelper extends SQLiteOpenHelper {
- private final String packageName = "应用的包名";
- private String DB_PATH = "/data/data/" + packageName + "/databases/";
- private SQLiteDatabase myDataBase;
- private final Context myContext;
- private static final String DB_NAME = "soft.db";
- private static String CITY = "city_name";
- public static final String CITY_ID = "city_id";
- public static final String CITY_NAME = "city_name";
- public DatabaseHelper(Context context) {
- super(context, DB_NAME, null, 1);
- this.myContext = context;
- }
- /**
- * 创建空数据库,并且通过复制资源文件夹的数据库覆盖
- * */
- public void createDataBase() throws IOException {
- boolean dbExist = checkDataBase();
- if (dbExist) {// 存在,什么也不干
- } else {
- // 进行数据库的复制
- this.getReadableDatabase();
- try {
- copyDataBase();
- } catch (IOException e) {
- throw new Error("Error copying database");
- }
- }
- }
- /**
- * 查询操作
- *
- * @return
- */
- public Cursor getAllCity() {
- String col[] = new String[] { CITY_ID, CITY_NAME };
- // return db.rawQuery("select * from tb_diary",null);
- return myDataBase.query(CITY, col, null, null, null, null, null);
- }
- /**
- * 启动应用的时候去检查数据库是否存在,如果不存在,则需要调用copy数据库的方法
- *
- * @return 存在返回 true , 不存在返回false
- */
- boolean checkDataBase() {
- SQLiteDatabase checkDB = null;
- try {
- String myPath = DB_PATH + DB_NAME;
- checkDB = SQLiteDatabase.openDatabase(myPath, null,
- SQLiteDatabase.OPEN_READONLY);
- } catch (SQLiteException e) {
- // 如果数据库不存在
- // throw new Error("Database does't exist yet.");
- return false;
- }
- if (checkDB != null) {
- checkDB.close();
- }
- return checkDB != null ? true : false;
- }
- /**
- *
- * 复制数据库的方法
- *
- * @throws IOException
- *
- * */
- void copyDataBase() throws IOException {
- // 通过资源文件访问数据库文件,以输入流的形式
- InputStream myInput = myContext.getAssets().open(DB_NAME);// 访问assets下的资源
- // InputStream
- // input=myContext.getResources().openRawResource(R.id.xx);//访问res下的资源
- // 数据库的 输出地址
- String outFileName = DB_PATH + DB_NAME;
- OutputStream myOutput = new FileOutputStream(outFileName);
- byte[] buffer = new byte[1024];
- int length;
- while ((length = myInput.read(buffer)) > 0) {
- myOutput.write(buffer, 0, length);
- Log.i("data", "copying.....");
- }
- myOutput.flush();
- myOutput.close();
- myInput.close();
- }
- /**
- * 关闭数据库的方法
- */
- @Override
- public synchronized void close() {
- if (myDataBase != null)
- myDataBase.close();
- super.close();
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- }
- /**
- * 打开数据库的方法
- *
- * @throws SQLException
- */
- public void openDataBase() throws SQLException {
- // Open the database
- String myPath = DB_PATH + DB_NAME;
- myDataBase = SQLiteDatabase.openDatabase(myPath, null,
- SQLiteDatabase.OPEN_READONLY);
- }
- }