I have a situation where i prompt user whether to backup their messages or no with the google backup service. I am successfully backing up the current realm database onto the SD card from where the backup to google service will happen.
But yet i though about the scenario where i want to actually restore the database from SD card to the current Realm Instance,meaning replace the current realm file with the one which is available on the SD Card.
In the older versions i saw that Realm gave a way to specify a custom path from which realm would read the database file,but in this new one i see none of it.
Any help please?
CREATE BACKUP FILE
public void backup() {
try {
// create a backup file
File exportRealmFile;
exportRealmFile = new File(EXPORT_REALM_PATH, EXPORT_REALM_FILE_NAME);
// if backup file already exists, delete it
exportRealmFile.delete();
// copy current realm to backup file
realm.writeCopyTo(exportRealmFile);
} catch (IOException e) {
e.printStackTrace();
}
realm.close();
}
RESTORE
private String copyBundledRealmFile(String oldFilePath, String outFileName) {
try {
File file = new File(activity.getApplicationContext().getFilesDir(), outFileName);
FileOutputStream outputStream = new FileOutputStream(file);
FileInputStream inputStream = new FileInputStream(new File(oldFilePath));
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, bytesRead);
}
outputStream.close();
return file.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Hope this help.
Credit to link
Related
In my project I am have LoginFragment(which accepts user name and password) PinFrgment which Accepts a PIN and Confirms that PIN and saves it in Realm.
When the user confirms the PIN I am creating a realmconfiguration and getting the realm instance as shown below.
protected void initRealm(Context context, byte[] key) {
try {
Realm.init(context);
RealmConfiguration config = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().encryptionKey(key).build();
Realm.setDefaultConfiguration(config);
realmInstance = Realm.getDefaultInstance();
DoPayApplication.getInstance().setRealmException(false);
} catch (RealmFileException realmFileException) {
DoPayApplication.getInstance().setRealmException(true);
Log.d(TAG, realmFileException.toString());
}catch (Exception ex){
Log.i(TAG, ex.toString());
DoPayApplication.getInstance().setRealmException(true);
}
}
On logout and forgot PIN I am calling the following method to close/reset realm.
public static void closeRealm(Context context) {
try{
if (realmInstance != null && !realmInstance.isClosed()) {
realmInstance.close();
RealmConfiguration config = realmInstance.getConfiguration();
realmInstance.deleteRealm(config);
}
}catch (Exception e){
Log.d(TAG, e.getMessage());
}
}
As long as I am in the app, on logout I am able to closeRealm as realmInstance is not null.
If the app is closed and user comes back to it. On forgot PIn when I call closeRealm 'realmInstance' is null and I cannot get the realmconfiguration to delete.
As the PIN is forgotten and the encryptionkey can not be generated. Is there a way to delete/recreate the real file without the Key.
Any advice would be very helpful.
Thanks
R
You can just delete .realm file with native tools:
// realm file default name is default.ream
File file = new File(context.getFilesDir(), "realmFileName.realm");
file.delete();
In that way you can copy db dump from assets or raw resources, also without realm configurations:
//Load dump from assets folder
InputStream inputStream = application.getAssets().open("my_factory_data_db.realm");
// realm file default name is default.ream
File file = new File(context.getFilesDir(), "realmFileName.realm");
FileOutputStream outputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, bytesRead);
}
ApiPreferenceHelper.setVersionApi(application, BuildConfig.BUILD_TIMESTAMP);
inputStream.close();
outputStream.close();
You can lear more about realm db file here How to find my realm file?
I've written an app that has several hard-coded settings such as fontSize or targetDirectory. I would like to be able to change those type of settings on an infrequent basis.
SharedPreferences seems to be one way to go about it but I want to share this application and settings, and my phone is not rooted.
My application is a personal tool, and does not have a UI. It opens, does it's job, and then closes. I could create the equivalent of a Windows .ini file and read/write to it, but that seems clunky. Having the SharePreferences file located on the sdcard where I can reach it, instead of device memory, where I can't, seems like that would work.
I do not want to backup these preferences, just be able to edit them, or copy them to a new device.
By default SharedPreferences files are stored in internal storage. You can make a backup of it to SD card programmatically.
File ff = new File("/data/data/"
+ MainActivity.this.getPackageName()
+ "/shared_prefs/pref file name.xml");
copyFile(ff.getPath().toString(), "your sdcard path/save file name.xml");
private void copyFile(String filepath, String storefilepath) {
try {
File f1 = new File(filepath);
File f2 = new File(storefilepath);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
You may replace it back when first start and backup it when application closed.
References: here
I wrote an app which logged data and saved it via SQL into a .db File. I had a method copying it from internal memory to SD card.
Now i wrote a second app, which needs to work with this particular .db file. As i think, that apps can't get access to package files from other apps
(in this case
/data/data/app1_package/databases/my_database.db
)
i need somehow to work with my DB on the SD Card. How do i do that?
Can i use this path in my SQLiteHelper class? Should i copy it from SD to my package, is that even possible (access rights etc.)?
I'm a beginner in databases, some help would be nice.
You can open any readable file path as a database:
File dbFile = new File( Environment.getExternalStorageDirectory(), "myfile.db" );
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile,null,null);
Note: check if sd-card is mounted before using this code.
yes place the DB file in your assets folder and get it this way :
DB_PATH="/data/data/app1_package/databases/my_database.db"
in your create :
is = getAssets().open("Meaniningss.db");
write(is);
the method :
public void write(InputStream is) {
try {
OutputStream out = new FileOutputStream(new File(DB_PATH));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
is.close();
out.flush();
out.close();
System.err.println(out + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
I made an application in which I save few information in my SQLite database.
As we know that SQLite database resides in the internal memory of the device and its created while app installation and deleted when we remove the respective application.
I am releasing a new version of the application, so when I delete my older version to install the newer version I lost the complete information which I had saved in the older version.
My query is can i retrieve the data from the older version from its SQLite database somehow so that, it can be used and maintained in the newer version.
Please suggest me so that my users must not lost their old data.
If the user updates the application then the database will remain intact. Uninstalling the old version and re-installing the new version will cause the database to be deleted.
See my comment, I really don't think you need to worry about it.
However, if you want to back up and restore your database, the following methods will send it to the SD Card and then read it back in (overwriting what was previously there in each case):
public void backup() {
try {
File sdcard = Environment.getExternalStorageDirectory();
File outputFile = new File(sdcard,
"yourDB.bak");
if (!outputFile.exists())
outputFile.createNewFile();
File data = Environment.getDataDirectory();
File inputFile = new File(data,
"data/your.package.name/databases/yourDB.sqlite");
InputStream input = new FileInputStream(inputFile);
OutputStream output = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("Copying Failed");
}
}
public void restore() {
try {
File sdcard = Environment.getExternalStorageDirectory();
File inputFile = new File(sdcard,
"yourDB.bak");
File data = Environment.getDataDirectory();
File outputFile = new File(data,
"data/your.package.name/databases/yourDB.sqlite");
if (!outputFile.exists())
outputFile.createNewFile();
InputStream input = new FileInputStream(inputFile);
OutputStream output = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("Copying Failed");
}
}
I have an SQLite database in my application. When I go to check if the database is created or not in File Explorer, there is no any database file within the data folder. It didn't even show up using the adb shell command. Does this mean that the database hasn't been created yet? Any suggestions on how to solve this?
If you are using an actual device, you will not be able to see or access it from outside unless you root your phone.
If you are using the emulator, the DDMS view will let you navigate to it and pull it from there.
Or, you could have an issue with creating your DB. Without seeing your code we cannot tell.
EDIT
If you want to get the file off of a real device, you'll need to implement a method to copy it from your data directory to someplace where you do have access (such as your SD card). This would do the trick:
public void backup() {
try {
File sdcard = Environment.getExternalStorageDirectory();
File outputFile = new File(sdcard,
"YourDB.bak");
if (!outputFile.exists())
outputFile.createNewFile();
File data = Environment.getDataDirectory();
File inputFile = new File(data, "data/your.package.name/databases/yourDB");
InputStream input = new FileInputStream(inputFile);
OutputStream output = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("Copying Failed");
}
}