export of sqlite database in assets folder - android

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

Related

android - restore sqlite database from internal storge to appication

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();
}
}

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();
}
}

copy .db file on sdcard in android

this code does not copy .db file on sdcard while my phone is rooted
try {
String comando = "cp -r /data/data/com.whatsapp/databases/msgstore.db /storage/sdcard0/tmp";
Process suProcess = Runtime.getRuntime().exec("su");
System.out.println(">>>>"
+ Environment.getExternalStorageDirectory());
DataOutputStream os = new DataOutputStream(
suProcess.getOutputStream());
os.writeBytes(comando + "\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
try {
int suProcessRetval = suProcess.waitFor();
if (255 != suProcessRetval) {
//
System.out.println(">>>>> done >>>>");
} else {
//
System.out.println(">>>>> not done >>>>");
}
} catch (Exception ex) {
Log.e("ERROR-->", ex.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
Copy database from /data/data folder to sdcard :
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//com.example.usarmy//databases//usarmy_db.sqlite";
String backupDBPath = "backdatabase.sqlite";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
System.out.println("error in data base copy:"+e);
}

android copy file it not work?

I try to copy a file from other package "/data/data/targetPackage" to "/data/data/myPackate"
but it is not working. I have request supermission
p = Runtime.getRuntime().exec("su");
// Attempt to write a file to a root-only
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("chmod 777 /data/data/targetPackage/databases"+"\n");
// Close the terminal
os.writeBytes("exit\n");
os.flush();
try
{
p.waitFor();
if (p.exitValue() != 255)
{
// TODO Code to run on success
toastMessage("root");
//accsessDB();
}
else
{
// TODO Code to run on unsuccessful
toastMessage("not root");
}
}
catch (InterruptedException e)
{
// TODO Code to run in interrupted exception
toastMessage("not root");
}
and this code copy
File f=new File("/data/data/targetPackage/databases/targetFile");
InputStream input = new FileInputStream(f);
new File("/data/data/myPackate/databases").mkdir();
File f2=new File("/data/data/myPackate/databases/targetFile");
OutputStream output = new FileOutputStream(f2,true);
byte[] buf= new byte[1024];
toastMessage(Integer.toString(input.read(buf)));
int len;
while((len=input.read(buf))>0)
{
output.write(buf, 0,len);
}
output.close();
input.close();
please help me
Try this it'll work..
private void copyFile()
{
try{
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
} else {
File file = new File(Environment.getExternalStorageDirectory()
+File.separator
+"App"
+File.separator
+"app"
+File.separator
+"images"
+File.separator
); //file name
file.mkdirs();
File source= new File(filePath);
File destination= new File(file,nameimage);
newloc=Environment.getExternalStorageDirectory()+"/"+"App"+"/"+"app"+"/"+"images"+"/";
newimgloc=Environment.getExternalStorageDirectory()+"/"+"App"+"/"+"app"+"/"+"images"+"/"+nameimage;
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
File dir = Environment.getExternalStorageDirectory();
if(dir.exists()){
toname=generatePin();
File from = new File(newloc,nameimage);
File to = new File(newloc,toname+".jpg");
if(from.exists())
from.renameTo(to);
filePath=newloc+toname+".jpg";
nameimage=toname+".jpg";
filedel();
}
}
}
}catch (Exception e) {
System.out.println(e);
Toast.makeText(getApplicationContext(), "Catch",Toast.LENGTH_SHORT).show();
}
}

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