Skip to content

Repository files navigation

ExternalRoomReadDbFromFile

part 5, setelah zip dibuat , buat instanse untuk room

Using Room as your local database.

Code for AppDataBase

@Database(entities = {SampleTable.class}, version = 3)
publicabstractclassAppDatabaseextendsRoomDatabase {
privatestaticfinalStringTAG = "AppDatabase";
publicstaticStringdbName = "ExternalBase64Md5ToZip.db";
publicabstractSampleTableDaosampleTableDao();
publicstaticAppDatabasegetInstance(Contextcontext) {
Filefolder = newFile(Environment.getExternalStorageDirectory().toString()+"FolderOnExternal"+"/db"+dbName);
returnRoom.databaseBuilder(context,
AppDatabase.class, dbName)
.createFromFile(folder)
.allowMainThreadQueries()
.build();
}
publicvoidcopyFile(AppDatabaseappDatabase) {
appDatabase.close();
try {
FilelocalDir = newFile(Environment.getExternalStorageDirectory().toString()+"FolderOnExternal"+"/db");
Filesd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
StringcurrentDBPath = appDatabase.getOpenHelper().getWritableDatabase().getPath();
StringbackupDBPath = AppDatabase.dbName;
FilecurrentDB = newFile(currentDBPath);
FilebackupDB = newFile(localDir, backupDBPath);
Log.d(TAG, "path local "+localDir.toString());
Log.d(TAG, "path sumber "+currentDB.toString());
Log.d(TAG, "path tujuan "+backupDB.toString());
if (currentDB.exists()) {
FileChannelsrc = newFileInputStream(currentDB).getChannel();
FileChanneldst = newFileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
} else {
Log.d(TAG, "path Cannon write");
}
} catch (Exceptione) {
e.printStackTrace();
Log.d(TAG, "path "+e.getMessage());
}
}
}

Important

Every new transaction process Insert, Update, Delete or ON APP DESTROY you should use copyFile to close Database and backup Database Room from root to eksternal. Here is the example.

AppDatabaseappDatabase = AppDatabase.getInstance(getApplicationContext());
appDatabase.sampleTableDao().insertAll(newSampleTable(0, "data baru"));
appDatabase.copyFile(appDatabase);

Copyright 2020 M. Fadli Zein

About

part 5, setelah zip dibuat , buat instanse untuk room

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages