2

here i want to use my pre-populated SQLite database to my android app. So, when first run it automatically copy the database from assets folder and use it as database on my android app.

I have doing this stuff so far :

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String MyVillageSoftware = "MyVillageSoftware";
public static final String table_Question = "table_question";
private static final String DATABASE_PATH="/Users/ever_ncn/Documents/Project/PsikologiKarakter/app/src/main/assets/";
private static final String DATABASE_NAME="question.db";
//TOL for transaction Coloumn
SQLiteDatabase db;
Context context;
private static final String TAG = DatabaseHelper.class.getSimpleName();



public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    this.context=context;

}

@Override
public void onCreate(SQLiteDatabase db) {

}

public void createDatabase(){
    createDB();
}

public void createDB(){
    boolean dbExist = DBExist();

    if(!dbExist){
        this.getReadableDatabase();
        copyDBFromResource();
    }

}

private boolean DBExist(){
    SQLiteDatabase db = null;
    try{
        String databasePath = DATABASE_PATH+DATABASE_NAME;
        db=SQLiteDatabase.openDatabase(databasePath, null,
                SQLiteDatabase.OPEN_READWRITE);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);
        db.setVersion(1);
    }catch(SQLiteException e){
        Log.e("SqlHelper", "Database nda ada babi");
    }
    if(db != null){
        db.close();
    }return db != null ? true : false;
}

private void copyDBFromResource(){
    InputStream inStream=null;
    OutputStream outStream = null;
    String dbFilePath=DATABASE_PATH+DATABASE_NAME;
    try{
        inStream=context.getAssets().open(DATABASE_NAME);
        outStream=new FileOutputStream(dbFilePath);
        byte[] buffer = new byte[1024];
        int length;
        while((length=inStream.read(buffer))>0){
            outStream.write(buffer, 0 , length);
        }
        outStream.flush();
        outStream.close();
        inStream.close();
    }catch (IOException e){
        throw new Error("Problem cuk");
    }
}

public List<String> getAllCategory() {
    List<String> AllCategoryList = new ArrayList<String>();
    List<String> AllCategIdList = new ArrayList<String>();

    String selectQuery = "SELECT * FROM " + table_Question;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);



    if (cursor.moveToFirst()) {
        do {
            String Id = cursor.getString(0);
            String A = cursor.getString(1);
            String B = cursor.getString(2);
            String C = cursor.getString(3);
            String D = cursor.getString(4);
            String aExplain = cursor.getString(5);
            String bExplain = cursor.getString(6);
            String cExplain = cursor.getString(7);
            String dExplain = cursor.getString(8);

        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return AllCategoryList;
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + table_Question);
    onCreate(db);

}

}

But i got an error message like this :

10-28 07:18:38.988 2425-2425/gook.psikologikarakter E/SQLiteLog﹕ (14) cannot open file at line 30046 of [9491ba7d73] 10-28 07:18:38.988 2425-2425/gook.psikologikarakter E/SQLiteLog﹕ (14) os_unix.c:30046: (2) open(/Users/ever_ncn/Documents/Project/PsikologiKarakter/app/src/main/assets/question.db) - 10-28 07:18:38.989 2425-2425/gook.psikologikarakter E/SQLiteDatabase﹕ Failed to open database '/Users/ever_ncn/Documents/Project/PsikologiKarakter/app/src/main/assets/question.db'. android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method) at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209) at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193) at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463) at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185) at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177) at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806) at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791) at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694) at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669) at gook.psikologikarakter.DatabaseHelper.DBExist(DatabaseHelper.java:65) at gook.psikologikarakter.DatabaseHelper.createDB(DatabaseHelper.java:52) at gook.psikologikarakter.DatabaseHelper.createDatabase(DatabaseHelper.java:48) at gook.psikologikarakter.MainActivity.onCreate(MainActivity.java:59) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

I don't know what really happen, but i think i can't open the database file. But i don't know what to do. Please master help me.

Thanks before.

Main Bareng
  • 31
  • 1
  • 9
  • 1
    You can't use a database from the assets folder. You'll want to copy the database over to /data/data/YOUR_PACKAGE/databases/ on first run time. This will be of help: http://stackoverflow.com/questions/513084/how-to-ship-an-android-application-with-a-database – ChallengeAccepted Oct 28 '15 at 00:37
  • yes sir, i mean that, so my question is how to copy the database from assets folder to data/data/your_package/databases/ when the app start for the first time? – Main Bareng Oct 28 '15 at 01:00
  • That my friend is as simple as just copying any other file you would using java. Here is one specifically for your case: http://stackoverflow.com/a/20592481/1371041 – ChallengeAccepted Oct 28 '15 at 01:04
  • but i got error on this sir : private String DATABASE_PATH= context.getApplicationInfo().dataDir + "/databases/"; i got error "illegal forward reference" – Main Bareng Oct 28 '15 at 01:14
  • @ChallengeAccepted thanks sir, it work very well – Main Bareng Oct 28 '15 at 02:05
  • glad to have solved your issue. As for the "illegal forward reference" did you make sure it was in the constructor? What did you do to solve your error? – ChallengeAccepted Oct 30 '15 at 00:44
  • 1
    i use another pattern code to do that sir. i use this code sir, private void copyDatabase(File dbFile) throws IOException { InputStream is = context.getAssets().open(DATABASE_NAME); OutputStream os = new FileOutputStream(dbFile); byte[] buffer = new byte[1024]; while (is.read(buffer) > 0) { os.write(buffer); } os.flush(); os.close(); is.close(); } – Main Bareng Nov 01 '15 at 03:40

1 Answers1

1
private static final String DATABASE_PATH="/Users/ever_ncn/Documents/Project/PsikologiKarakter/app/src/main/assets/";

This is the path on your local file system, not the path of the file on the device at runtime. Use getResources().getAssets().openFile(...) to get an InputStream to the file.

Jeffrey Blattman
  • 22,176
  • 9
  • 79
  • 134
  • so is the code gonna be like this sir? context.getResources().getAssets().openFile(DATABASE_NAME); but i got an error on openFile(); – Main Bareng Oct 28 '15 at 00:37