android - restore sqlite database from internal storge to appication - android

I am trying to restore a database from the phone storage in order to use it in my application.
I successfully did a backup for my database to the internal storage but when I am trying to restore it the following io.exception pops up
java.io.IOException: open failed: ENOENT (No such file or directory)
How can I solve this problem?
However, I tried the follosing existing solutions but they didn't work
Android - java.io.FileNotFoundException,
is it possible backup and RESTORE a database file in android? non root devices,
Restoring SQLite DB file
private void restoreDatabase(Context context) {
String packagename = getPackageName();
File sdcard = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
try {
if (sdcard.canWrite()) {
String currentDBPath = "//data/"+getPackageName() +"/databases/" + DATABASE_NAME;
String backupDBPath = DATABASE_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sdcard, backupDBPath);
currentDB.createNewFile();
if (currentDB.exists()) {
FileChannel src = new FileInputStream(backupDB).getChannel();
FileChannel dst = new FileOutputStream(currentDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Database Restored successfully", Toast.LENGTH_SHORT).show();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
Please don't mark this question as duplicate

after exporting your database you can use this function to import the database, I had it testet and it works fine :
private void importDB() {
String appDataPath = getApplicationContext().getApplicationInfo().dataDir;
File dbFolder = new File(appDataPath + "/databases");//Make sure the /databases folder exists
dbFolder.mkdir();//This can be called multiple times.
//EDITED
File dbFilePath = new File(appDataPath + "/databases/"+"yourDataBaseName");
try {
//EDITED
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "YourBackupFolder","yourDataBaseFileName);
FileInputStream inputStream = new FileInputStream(file); //use your database name
OutputStream outputStream = new FileOutputStream(dbFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer))>0)
{
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e){
//handle
e.printStackTrace();
}
}

Related

unable to see sqlite file on the SD card

my problem is the following:
I have correctly moved the SQlite database on the local SD, but the file is not visible both from the device and the PC via USB connection.
The app does not raise any error.
Here is the method that performs the copy:
private void exportDB(){
DBHelper db = DBHelper.getInstance(this);
String DBName = db.getDBName();
File dbPath = this.getDatabasePath(DBName);
String DBPath = dbPath.getAbsolutePath();
//Toast.makeText(this, "DB Path : " + DBPath , Toast.LENGTH_LONG).show();
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = DBPath;
String backupDBPath = "Download/"+DBName;
File currentDB = new File(currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
} catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}
for transferting DB, I think it may achievable in rooted device.

duplicate default Database into temp Database

I would like to create a temporary database, this is the code:
String PATH = "/data/data/" + appContext.getPackageName() + "/databases/";
List<File> files = getListFiles(new File(PATH));
//File dbFile = appContext.getDatabasePath(PreferenceConstants.TEMP_DB_DATABASE_STORE);
File dbFile = new File(PATH, PreferenceConstants.TEMP_DB_DATABASE_STORE);
FileInputStream is;
if (!dbFile.exists()) {
try {
dbFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}else
dbFile.delete();
try {
is = new FileInputStream(appContext.getDatabasePath(PreferenceConstants.DB_DATABASE_STORE));
FileUtils.copyInputStreamToFile(is, dbFile);
} catch (IOException e) {
e.printStackTrace();
}
but no file are created into database folder, why?
after copy I would like to open another database , copy the tables and append the table in the temp database created.
EDIT
very simple method:
DatabaseHelper dbIng = new DatabaseHelper(appContextDialog, "temp_database.db");
dbIng.closeDB();
This is what I use for importing and exporting databases:
Dont forget about the permissions.
public void exportDatabase(){
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
String currentDBPath = "//data//MY.PACKAGE.NAME//databases//MY_DATABASE_NAME";
String backupDBPath = "MY_DATABASE_FILE.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(c, c.getResources().getString(R.string.exporterenToast), Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(c, c.getResources().getString(R.string.portError), Toast.LENGTH_SHORT).show();
Log.d("Main", e.toString());
}
}
public void importDatabase(){
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
String currentDBPath = "//data//" + "MY.PACKAGE.NAME" + "//databases//" + "MY_DATABASE_NAME";
String backupDBPath = "MY_DATABASE_FILE.db";
File backupDB = new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(c, c.getResources().getString(R.string.importerenToast), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(c, c.getResources().getString(R.string.portError), Toast.LENGTH_SHORT).show();
}
}

prevent storing a video file twice in internal storage in android

how to prevent storing same file selected in galary twice in internal storage in android .I tried with below code it copies same video many times in a folder in the internal storage .
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
new SaveVideoInFolder().execute(uri);
try {
InputStream is = getContentResolver().openInputStream(uri);
File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File app_directory = new File(storage, "video_choosing");
if (!app_directory.exists())
app_directory.mkdirs();
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String filename = String.format("VID_%s.mp4", timestamp);
file = new File(app_directory, filename);
Toast.makeText(MainActivity.this,file.toString(),Toast.LENGTH_SHORT).show();
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int read;
while ((read = is.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
output.close();
} catch (FileNotFoundException e) {
Log.e("TAG", "File Not Found", e);
} catch (IOException e) {
Log.e("TAG", "IOException", e);
}
}
// Create the storage directory if it does not exist
if (!file.exists()) {
if (!file.mkdirs()) {
/* Log.e(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");*/
return null;
}
only you have check that your file is exist bt if condition and make directory if it is not..
File file = new File(app_directory, filename);
if(file.exists()){
...
}
else {
...
}

export of sqlite database in assets folder

I have a sqlite database in my assets folder. I want to export that file. So I do this:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//
File direct = new File(Environment.getExternalStorageDirectory()
+ "/Exam Creator");
if (!direct.exists())
{
if (direct.mkdir())
{
// directory is created;
}
}
exportDB();
// importDB();
}
private void exportDB()
{
// TODO Auto-generated method stub
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite())
{
dbopenhelper.copyDataBase();
String currentDBPath = dbopenhelper.DB_PATH
+ dbopenhelper.DATABASE_NAME;
String backupDBPath = "/BackupFolder/Prayers.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(),
backupDB.toString() + "SUCCESS", Toast.LENGTH_LONG)
.show();
}
} catch (Exception e)
{
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
}
to get the path of my currentDB, I first copy the database in my project using this method in my DBOpenHelper and by calling it in export method as you can see above.
public static void copyDataBase()
{
try
{
InputStream input = context.getAssets().open(DATABASE_NAME);
FileOutputStream output = new FileOutputStream(DB_PATH
+ DATABASE_NAME);
byte[] data = new byte[1024];
int buffer;
while ((buffer = input.read(data)) != -1)
{
output.write(data, 0, buffer);
}
output.flush();
output.close();
input.close();
} catch (IOException ex)
{
Log.e(LOGTAG, "Error in copying database...");
}
}
but when I run it, I get Filenotfound exception. I debuged it and saw that after this line:
FileChannel src = new FileInputStream(currentDB).getChannel();
it goes to catch block. Does anyone know what is wrong?
Thanks in advance

Trying to Copy SQLite DB from data to SD card

I am using the following code that was posted somewhere on Stack Overflow and modified for my purposes:
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+ "com.exercise.AndroidSQLite" +"//databases//"+"MY_DATABASE";
String backupDBPath = "/temp/MY_DATABASE";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
So the error I get when I try to access it is:
java.io.FileNotFoundException: /data/data/com.exercise.AndroidSQLite/databases/MY_DATABASE: open failed: EACCES (Permission Denied)
I am trying to copy this file without rooting my tablet. The write external storage directory permission is set in the application; I just can't get around this error. Would appreciate help on resolving this issue, it's driving me mad
I am backing up my database in my android application and it works fine. You can only access the database file if you are the owner of it, meaning your application created it.
I think your path is wrong, I have this in my app:
private static final String DATABASE_NAME = "my.db.name";
public File getBackupDatabaseFile() {
File dir = new File(getStorageBaseDirectory().getAbsolutePath() + "/backup");
if (!dir.exists()) {
dir.mkdirs();
}
return new File(dir, DATABASE_NAME);
}
public final boolean backupDatabase() {
File from = mContext.getDatabasePath(DATABASE_NAME);
File to = this.getBackupDatabaseFile();
try {
FileUtils.copyFile(from, to);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Error backuping up database: " + e.getMessage(), e);
}
return false;
}
And FileUtils.copyFIle is this:
public static void copyFile(File src, File dst) throws IOException {
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dst);
FileChannel fromChannel = null, toChannel = null;
try {
fromChannel = in.getChannel();
toChannel = out.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
if (fromChannel != null)
fromChannel.close();
if (toChannel != null)
toChannel.close();
}
}
You are using "MY_DATABASE" literally when you probably actually want to use it as a variable...
Remove the quotes from around it and see if that doesn't solve your problem.

Categories

Resources