SQLiteに関しての質問です。
外部ソフトでデータベースファイルを作成し,そのファイルをSQLiteのDatabaseOpenHelperにコピーする手法を取っています。
PCで作ったSQLiteのDBファイルをAndroidで使う。を参考にさせて頂きました(参考というよりかコピペさせて頂きました)。
かたまりごとにどのような処理を行なっているのか,教えていただけたら幸いです。
public
1 private static final String DB_FILE_NAME = "MainProject.db"; 2 private static final String DB_NAME = "sample.db"; 3 private static final int DB_VERSION = 7; 4 private Context context; 5 private File dbPath; 6 private boolean databaseExists = true; 7 8 public DatabaseOpenHelper(Context context) { 9 super(context, DB_NAME, null, DB_VERSION); 10 this.context = context; 11 this.dbPath = context.getDatabasePath(DB_NAME); 12 } 13 @Override 14 public void onCreate(SQLiteDatabase db) { 15 super.onOpen(db); 16 databaseExists = false; 17 } 18 @Override 19 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 20 String databasePath = this.dbPath.getAbsolutePath(); 21 File file = new File(databasePath); 22 if (file.exists()) { 23 file.delete(); 24 } 25 databaseExists = false; 26 } 27 @Override 28 public SQLiteDatabase getReadableDatabase() { 29 SQLiteDatabase database = super.getReadableDatabase(); 30 if (!databaseExists) { 31 try { 32 database.close(); 33 database = copyDatabaseFromAssets(); 34 databaseExists = true; 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } 38 } 39 return database; 40 } 41 private SQLiteDatabase copyDatabaseFromAssets() throws IOException { 42 InputStream inputStream = this.context.getAssets().open(DB_FILE_NAME); 43 OutputStream outputStream = new FileOutputStream(dbPath); 44 45 byte[] buffer = new byte[1024]; 46 int size; 47 while ((size = inputStream.read(buffer)) > 0) { 48 outputStream.write(buffer, 0, size); 49 } 50 outputStream.flush(); 51 outputStream.close(); 52 inputStream.close(); 53 54 return super.getReadableDatabase(); 55 } 56}
あなたの回答
tips
プレビュー