Back up content from a DB in /data/data/package/databases/db.dbname in sdcard?

2

My application creates a db, what I want to do is a backup of what it contains then I do the following code:

  File CarFile = new File("sdcard/xxxx");
    if (!CarFile.exists()) {
        try {
            CarFile.mkdir();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    File f=new File("/data/data/x.x.x/databases/xxx.db");
    FileInputStream fis=null;
    FileOutputStream fos=null;

    try
    {
        fis=new FileInputStream(f);
        fos=new FileOutputStream("sdcard/xxxx/xxx.sql");
        while(true)
        {
            int i=fis.read();
            if(i!=-1)
            {fos.write(i);}
            else
            {break;}
        }
        fos.flush();
        Toast.makeText(this, "OK", Toast.LENGTH_LONG).show();
    }
    catch(Exception e)
    {
        e.printStackTrace();
        Toast.makeText(this, "ERROR", Toast.LENGTH_LONG).show();
    }
    finally
    {
        try
        {
            fos.close();
            fis.close();
        }
        catch(IOException ioe)
        {}
    }

but the code I get is not readable in a text editor and no sqlite manager.

    
asked by Jorge Luis Pilo Torres 11.10.2016 в 02:17
source

1 answer

2

The solution is simple, you are opening the file safely with a plain text editor, the * .db files are not plain text. I suggest you use the firefox addon "SQlite Manager" and open it.

link

Do not forget this permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></u‌​ses-permission>

Improving the code a bit would be:

try {
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();

    if (sd.canWrite()) {
        File db = new File(data, "//data//x.x.x//databases//xxx.db");
        File backup = new File(sd, "xxx.db");

        if (db.exists()) {
            FileChannel src = new FileInputStream(db).getChannel();
            FileChannel dst = new FileOutputStream(backup).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            Toast.makeText(this, "OK", Toast.LENGTH_LONG).show();
        }
    }
} catch (Exception e) {
    e.printStackTrace();
    Toast.makeText(this, "ERROR", Toast.LENGTH_LONG).show();
}
    
answered by 14.10.2016 в 02:27