How to read data from the assets folder sqlite database file with .sqlite extension in my Android application?

Solution 1

Try this code:

public class DataBaseHelper extends SQLiteOpenHelper {
    private Context mycontext;

    //private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
    private static String DB_NAME = "(datbasename).sqlite";//the extension may be .sqlite or .db
    public SQLiteDatabase myDataBase;
    /*private String DB_PATH = "/data/data/"
                        + mycontext.getApplicationContext().getPackageName()
                        + "/databases/";*/

    public DataBaseHelper(Context context) throws IOException {
        boolean dbexist = checkdatabase();
        if (dbexist) {
            //System.out.println("Database exists");
        } else {
            System.out.println("Database doesn't exist");

    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if(dbexist) {
            //System.out.println(" Database exists.");
        } else {
            try {
            } catch(IOException e) {
                throw new Error("Error copying database");

    private boolean checkdatabase() {
        //SQLiteDatabase checkdb = null;
        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);
            //checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
            checkdb = dbfile.exists();
        } catch(SQLiteException e) {
            System.out.println("Database doesn't exist");
        return checkdb;

    private void copydatabase() throws IOException {
        //Open your local db as the input stream
        InputStream myinput = mycontext.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
        OutputStream myoutput = new FileOutputStream("/data/data/(packagename)/databases   /(datbasename).sqlite");

        // transfer byte to inputfile to outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length =>0) {

        //Close the streams

    public void opendatabase() throws SQLException {
        //Open the database
        String mypath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);

    public synchronized void close() {
        if(myDataBase != null) {


Solution 2

Place old database (old.db) in your asset folder. Type this inside onCreate() of your activity:

public void onCreate(Bundle savedInstanceState) {

//=======Code For copying Existing Database file to system folder for use====//
    // Copying Existing Database into system folder
        try {

            String destPath = "/data/data/" + getPackageName()
                    + "/databases/data.db";

            File f = new File(destPath);
            Log.v(TAG,"File Not Exist");
            InputStream in = getAssets().open("old.db");
            OutputStream out = new FileOutputStream(destPath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = > 0) {
                out.write(buffer, 0, length);

        } catch (FileNotFoundException e) {
        } catch (IOException e) {

        DBManager dbManager =  new DBManager(this);
        Log.v(TAG,"Database is there with version: "+dbManager.getReadableDatabase().getVersion());
        String sql = "select * from prizes";

        SQLiteDatabase db = dbManager.getReadableDatabase();
        Cursor cursor = db.rawQuery(sql, null);
        Log.v(TAG,"Query Result:"+cursor);




Now you have to make a DBManager Class which subclasses SQLiteOpenHelper . Insert the abstract method and constructor. Don't forget to type correct database name inside super() of dbHelper.

public class DBManager extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String TAG = "DATABASES";

public DBManager(Context context) {
    super(context, "data.db", null, DATABASE_VERSION);


public void onCreate(SQLiteDatabase db) {
    Log.v(TAG,"On create Called:"+db.getPath());

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

Now you can access database by instantiating DBManager.

SQLiteDatabase db = dbManager.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);

Don't forget to close database or u will get a SQLiteDatabaseNotClosed Exception.


Solution 3

Its important that in the tutorial, when you call the file, make sure you pass the application context getApplicationContext() such that you have access to the correct assets, otherwise you might get a FileNotFound Exception.

Solution 4

You will want to try android sqlite asset helper. It made opening a pre-existing db a piece of cake for me.

I literally had it working in about a half hour after spending 3 hours trying to do it all manually. Funny thing is, I thought I was doing the same thing the library did for me, but something was missing!

Solution 5

You need to convert your .sqlite database to .db inorder to fit to Android.

On your app's first launch after installation

SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.COPY_TO_SYSTEM);

On subsequent launches

SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.READ_FROM_DEVICE);

Simply fire SQL queries

database.sqlInject("INSERT INTO food VALUES('Banana','Vitamin A');");

Get results on Array in CSV, JSON, XML

ArrayList<String> rows=new ArrayList<String>();
rows=database.sqlEjectCSV("SELECT * FROM food;");
for (int i=0;i<rows.size();i++)
    //Do stuffs with each row

You need to include my library for this. Documentations here:

Solution 6

If you are planning to create a new SQLite database then over ride and implement the onCreate() Method as shown in the tutorial.

But if you are using a SQLite database that is created by another external source and you are going to pull it down, then leave the onCreate() method empty.

Solution 7

You can only read database from asset folder as the resources folders are read-only. If you need to do more operation like create, update, delete you can do a tricks. Copy the database from assets folder to storage and then you can do anything you want.

Here is a quick example of Working with Android Pre Built Database.

There is a easy to use library too for accessing database from assets folder. You can check Android SQLiteAssetHelper ( Good luck!