anko icon indicating copy to clipboard operation
anko copied to clipboard

How to create sqlite database in external storage (SDCARD)?

Open holic-cl opened this issue 6 years ago • 1 comments

Hi, i wanna know how to create sqlite database in sdcard, could it be done making something like this?:

class MyDatabaseOpenHelper(ctx: Context) : ManagedSQLiteOpenHelper(
    ctx, Environment.getExternalStorageDirectory() + File.separator + FILE_DIR + File.separator + DATABASE_NAME, null, 1) {
    companion object {
        private var instance: MyDatabaseOpenHelper? = null

        @Synchronized
        fun getInstance(ctx: Context): MyDatabaseOpenHelper {
            if (instance == null) {
                instance = MyDatabaseOpenHelper(ctx.getApplicationContext())
            }
            return instance!!
        }
    }

    override fun onCreate(db: SQLiteDatabase) {
        // Here you create tables
        db.createTable("Customer", true, 
                    "id" to INTEGER + PRIMARY_KEY + UNIQUE,
                    "name" to TEXT,
                    "photo" to BLOB)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        // Here you can upgrade tables, as usual
        db.dropTable("User", true)
    }
}

regards

holic-cl avatar Oct 10 '18 03:10 holic-cl

I think it should work, unless the user refuses to grant your app WRITE_EXTERNAL_STORAGE permission.

iceboundrock avatar Dec 18 '18 16:12 iceboundrock