Question

I have a trouble with accessing database. I have a database on my sdcard, not from my assets. How to configure that? Can i use this code?

private void copyDataBase() throws IOException {
InputStream myInput = context.getExternalFilesDir(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}

i have some error when try this code

Was it helpful?

Solution

SQLite will always create a database in your application context only. It will create a folder called databases and saves all your databases in that folder only. So you have to copy the database from sdcard to your application databases only

private void copyDataBaseFromSdCard() 
{
    try
    {
        String DB_PATH = "data/data/" + getPackageName() + "/databases/";
        String DB_NAME = "testcopy.db";

        String yourDbFileNamePresentInSDCard = "/mnt/sdcard/test.db";
        File file = new File(yourDbFileNamePresentInSDCard);
        // Open your local db as the input stream
        InputStream myInput = new FileInputStream(file);

        // Path to created empty db
        String outFileName = DB_PATH + DB_NAME;

        // Opened assets database structure
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }
    catch(Exception e)
    {

    }
}

    private SQLiteDatabase getDB()
{
     String DB_NAME = "testcopy.db";
    return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top