Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the SQLite path within the Assets Folder

I'm developing an application and I've run into two problems here:

  1. How can I open an SQLite database which is stored in the assets folder? What path do I use to access the assets folder in my application? Here's what I have so far:

    path = "file:///asset_folder/database.dat";
    SQLiteDatabase db = null;
    db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
    
  2. How can I copy a file to the internal memory (/data/data/...) during the installation of my application or during the first run? I want to copy a folder inside the assets folder into the internal memory during the first run.

Any suggestions would be greatly appreciated.

like image 940
user852568 Avatar asked Jan 19 '26 20:01

user852568


1 Answers

I was having the same problem, so I moved the db file to the res/raw folder, and accessed it like so:

InputStream inputStream = getBaseContext().getResources().openRawResource(R.raw.mySQLiteFile);

Then I tried to move the file into the /data/data/com.mydomain.www/databases/ folder, but I would get an exception because the destination path didn't exist, so I did File(destPath).getParentFile().mkdir();

From there, I called a copy db method to transfer the db to the destination.

public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        inputStream.close();
        outputStream.close();
    }

InputStream is the db file, OutputStream is the FileOutputStream(destPath).

like image 138
adamcodes Avatar answered Jan 21 '26 11:01

adamcodes