M0rty
M0rty

Reputation: 1085

Opening a database from external storage Android

I was previously storing a sqlite database in my apps assets folder but have now moved the database to external storage.

My previous copyDatabase() method looked like this.

private void copyDataBase() throws IOException {
        InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
        OutputStream myOutput = new FileOutputStream(DB_PATH);
        byte[] buffer = new byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
        while (true) {
            int length = myInput.read(buffer);
            if (length > 0) {
                myOutput.write(buffer, 0, length);
            } else {
                myOutput.flush();
                myOutput.close();
                myInput.close();
                return;
            }
        }
    }

The issue is I'm unsure how to create an InputStream for opening the database from external storage. I can't seem to find the external storage equivalent to myContext.getAssets().open(DATABASE_NAME);

The current database path:

DB_PATH = Environment.getExternalStorageDirectory().getPath().toString()+"/SoulInfoDatabase/BB2SoulDatabase.db";

Upvotes: 0

Views: 2478

Answers (1)

Md. Shahadat Sarker
Md. Shahadat Sarker

Reputation: 849

Step 1: Give storage permission in your App Manifesto file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step 2: Copy database to your custom SD card Path

private void copyDataBase() throws IOException {
    // Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DB_NAME);

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

    // Open the empty db as the output stream
    new File(outFileName).createNewFile();
    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();
}

Step 3: Then Open your database:

try {
        db = SQLiteDatabase.openDatabase(DB_PATH + "/" + DB_NAME, null,
                SQLiteDatabase.OPEN_READWRITE
                        | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

WHERE

String filePath =  Environment.getExternalStorageDirectory().getAbsolutePath() + "/SoulInfoDatabase";
File file = new File(filePath);
if(!file.exists()){
    file.mkdirs();
}

DB_PATH = filePath; DB_NAME = "BB2SoulDatabase.sqlite";

Upvotes: 1

Related Questions