Sven Nijs
Sven Nijs

Reputation: 508

Copy database from assets folder to local storage error

When users installs my Android app, a sqlite database is copied from the assets folder to local database folder of device. I use this code to accomplish that:

   private void copyDataBase() throws IOException {

   String DB_PATH = "";
   String DB_NAME = "mydb.db";

    if(android.os.Build.VERSION.SDK_INT >= 17){

        DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
    }
    else
    {
        DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    }

    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(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();

  }

This runs fine on alle devices, except one: Moto 3g devices. This kind of devices always throws an ioexception when copying the database with no further information.

Anyone an idea what the problem is?

Upvotes: 0

Views: 257

Answers (3)

akyirem samuel
akyirem samuel

Reputation: 78

Check out this library. Sqlite Asset helper. It greatly reduces all the hussle you have to go through when you want to ship a local database with your apl

Upvotes: 0

fatboy
fatboy

Reputation: 2137

please try below library

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

it may help.

Upvotes: 0

Vanraj Ghed
Vanraj Ghed

Reputation: 1271

Try This code it's work Perfectly just change your table name and Package name

   public class SqlLiteDataBaseHelper extends SQLiteOpenHelper{
    private static final String TAG = SqlLiteDataBaseHelper.class.getSimpleName();
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_PATH = "/data/data/YOUR PACKAGE NAME/databases/";
    private static final String DATABASE_NAME = "test1.sqlite";
    private static final String TABLE_NAME = "Student";
    private static final String COL_Name = "Name";
    private static final String COL_ROLL_NO ="RollNo";
    private Context context;
    private SQLiteDatabase db;

    public SqlLiteDataBaseHelper(Context context) {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }


    //This method is just retuning total no of recode in your table Getting single contact count
    public int  getDataCount() {

        String userRollNo = null;

        String query = "SELECT * FROM " + TABLE_NAME ;

        Cursor cursor = db.rawQuery(query, null);

        return cursor.getCount();
    }




    public void openDataBase () throws SQLException{
        String path = DATABASE_PATH+DATABASE_NAME;
        db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
    }

    public void CopyDataBaseFromAsset() throws IOException {
        InputStream in  = context.getAssets().open(DATABASE_NAME);
        Log.e("sample", "Starting copying");
        String outputFileName = DATABASE_PATH+DATABASE_NAME;
        File databaseFile = new File( "/data/data/YOUR PACKAGE NAME/databases");
        // check if databases folder exists, if not create one and its subfolders
        if (!databaseFile.exists()){
            databaseFile.mkdir();
        }

        OutputStream out = new FileOutputStream(outputFileName);

        byte[] buffer = new byte[1024];
        int length;


        while ((length = in.read(buffer))>0){
            out.write(buffer,0,length);
        }
        Log.e("sample", "Completed" );
        out.flush();
        out.close();
        in.close();

    }

    public void deleteDb() {
        File file = new File(DATABASE_PATH);
        if(file.exists()) {
            file.delete();
            Log.d(TAG, "Database deleted.");
        }
    }
    public boolean checkDataBase() {
        boolean checkDB = false;
        try {
            File file = new File(DATABASE_PATH);
            checkDB = file.exists();
        } catch(SQLiteException e) {
            Log.d(TAG, e.getMessage());
        }
        return checkDB;
    }
}

To use in your actvity

sqlLiteDataBaseHelper = new SqlLiteDataBaseHelper(this);


        try {

            if(sqlLiteDataBaseHelper.checkDataBase()){

                Log.e(TAG,"Data Base Already Exists");

            }else {

                sqlLiteDataBaseHelper.CopyDataBaseFromAsset();

            }

        }catch (Exception e){
            e.printStackTrace();
        }
        try {

            sqlLiteDataBaseHelper.openDataBase();
             // after open data  base u can read write data base 

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

Upvotes: 1

Related Questions