Issue
i created a notepad app which has a sqlite db. the app allows user to backup of his data to google drive. i want to restore this data when ever user clicked on restore button. the problem is i can not access sqlite db to replace it with backup file in google drive.
This problem only happens on android 29+ and if i set targetsdk to 28 my codes works fine. but google play did not let me to upload an app with targetsdk lower than 30 so i had to increase sdk version. here is my code any suggestion would be appreciated:
File data = Environment.getDataDirectory();
String currentDBPath = "/data/" + getPackageName() + "/databases/" + Constants.dataBaseName;
File currentDB = new File(data, currentDBPath);
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Constants.dataBaseName;
File destination = new File(destinationPath);
try {
FileUtils.copyFile(destination, currentDB);
Snackbar.make(findViewById(R.id.activity_backup_restore), getString(R.string.successful_importing_db), Snackbar.LENGTH_LONG).show();
} catch (IOException e) {
Snackbar.make(findViewById(R.id.activity_backup_restore), getString(R.string.error_in_importing_db), Snackbar.LENGTH_LONG).show();
}
Solution
after struggling with targetsdk and different file methods, i saw a video on youtube and get me an idea to use contextWrapper class and i was able to fix the problem. here is the new code i write:
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File currentDB = contextWrapper.getDatabasePath(Constants.dataBaseName);
File destinationDirectory = contextWrapper.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File destination = new File(destinationDirectory, Constants.dataBaseName + ".db");
try {
FileUtils.copyFile(destination, currentDB);
Snackbar.make(findViewById(R.id.activity_backup_restore), getString(R.string.successful_importing_db), Snackbar.LENGTH_LONG).show();
} catch (IOException e) {
Snackbar.make(findViewById(R.id.activity_backup_restore), getString(R.string.error_in_importing_db), Snackbar.LENGTH_LONG).show();
}
Answered By - amir hossein kazemi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.