21

i am developing an application in which i want to read an sqlite database file from the asset folder of the project. i have searched the web but nothing found helpful. please help me. Thanks.

3
  • 5
    Did you really find nothing? Web is a waste man, lets smoke come'on! Commented Dec 31, 2013 at 12:56
  • google.com.au/… Commented Dec 31, 2013 at 12:57
  • 1
    Better to go through this link stackoverflow.com/questions/2605555/… Commented Jun 11, 2014 at 21:36

2 Answers 2

5

Basically you can get an InputStream (from the AssetManager open function) for a file name and write it to an OutputStream.

InputStream inputStream = getAssets().open(fileName);

If you create your database using openOrCreateDatabase you might want to put the database in the databases folder...

    String fileName = "MySQLiteDB.db";
    File file = getDatabasePath(fileName );
    if (!file.exists()) {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }

        InputStream inputStream = getAssets().open(DATABASE_NAME);
        OutputStream outputStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024 * 8];
        int numOfBytesToRead;
        while((numOfBytesToRead = inputStream.read(buffer)) > 0)
        outputStream.write(buffer, 0, numOfBytesToRead);
        inputStream.close();
        outputStream.close();
    }

    db = SQLiteDatabase.openOrCreateDatabase(file, null);
Sign up to request clarification or add additional context in comments.

Comments

1

In Kotlin you can write :

val fileName = "your_file_name.db"
val file = getDatabasePath(fileName)

val data = SQLiteDatabase.openOrCreateDatabase(file, null)

then you can use rawQuery to read any table from the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.