1

in a project, I would like to copy the sqlite db from the folder:

/res/raw

to the folder:

/data/data/{package_name}/databases/

like it said in the this link. And it doesn't make the copy on the destination folder. Here is my code: MainActivity.java:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("Components onCreate","setContentView");
        setContentView(R.layout.activity_main);

        MySQLiteHelper n = new MySQLiteHelper(getApplicationContext());

        try {

            Uri url = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.myfile);
            boolean temp = n.importDatabase(url.toString());
            Log.i("Components onCreate",""+temp);

        } catch (IOException e) {
            e.printStackTrace();
        }

MySQLiteHelper.java:

public boolean importDatabase(String dbPath) throws IOException {

        // Close the SQLiteOpenHelper so it will commit the created empty
        // database to internal storage.
        close();
        File newDb = new File(dbPath);
        File oldDb = new File(DB_FILEPATH);
        Log.i("ImportDatabase", "Database " + newDb.exists());
        if (newDb.exists()) {
            FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
            // Access the copied database so SQLiteHelper will cache it and mark
            // it as created.
            getWritableDatabase().close();
            return true;
        }
        return false;
    }

On my logcat i am gettin false all the time. Here it is:

I/ImportDatabase﹕ Database false

I don't know what I am making wrong? Any hints? Thanks.

Community
  • 1
  • 1
KostasC
  • 1,076
  • 6
  • 20
  • 40

2 Answers2

1

put your db file inside assets folder and use this class:

package com.app.util;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Milad.
 */
public class DBHandler extends SQLiteOpenHelper {


    private static String DB_PATH;

    private SQLiteDatabase mDataBase;
    private final Context mContext;


    private static String DB_NAME = "myfile";// Database name
    private static int DB_VERSION = 1;


    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     *
     * @param context
     */
    public DBHandler(Context context) {

        super(context, DB_NAME, null, DB_VERSION);
        if (android.os.Build.VERSION.SDK_INT >= 4.2) {
            DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        } else {
            DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
        }
        this.mContext = context;
    }


    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     */
    public void createDataBase() throws IOException {

        // If database not exists copy it from the assets

        boolean mDataBaseExist = checkDataBase();

        if (!mDataBaseExist) {
            this.getReadableDatabase();
            this.close();
            try {
                // Copy the database from assests
                copyDataBase();
                Log.e("DataBaseHelper", "createDatabase database created");
            } catch (IOException mIOException) {
                throw new Error("Error Copying DataBase");
            }
        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */

    //Check that the database exists here: /data/data/your package/databases/Da Name
    private boolean checkDataBase() {
        File dbFile = new File(DB_PATH + DB_NAME);
        //Log.v("dbFile", dbFile + "   "+ dbFile.exists());
        return dbFile.exists();
    }


    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     */
    private void copyDataBase() throws IOException {


        InputStream mInput = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();

    }

    public void openDataBase() throws SQLException {

        // Open the database
        String myPath = DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

        if (mDataBase != null)
            mDataBase.close();

        super.close();

    }


    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }
}

usage:

// dbHandler class instance
dbHandler = new DBHandler(this);
try {

    dbHandler.createDataBase();
    contentLog.append("Database Created\n");

} catch (IOException ioe) {
    //throw new Error("Unable to create database");
}
Milad Nouri
  • 1,587
  • 1
  • 21
  • 32
  • Thanks very much, with a few modification to adapt to my code, it finally worked. Thanks again! – KostasC Feb 22 '15 at 11:44
0

I found that this one works really nice, as someone else has taken care of all of the leg work

https://github.com/jgilfelt/android-sqlite-asset-helper

As was pointed out

Copying database from the asset folder

Community
  • 1
  • 1
Zeppie
  • 179
  • 6