tekartik / sqflite

SQLite flutter plugin
BSD 2-Clause "Simplified" License
2.86k stars 521 forks source link

Accessing Sqflite in Android specific code #334

Open xilibro opened 4 years ago

xilibro commented 4 years ago

Is it possible access Sqflite in Android specific code?

`

public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper instance;
public static final String DATABASE_NAME = "app.db"; 
private static final int DATABASE_VERSION = 1;
public static synchronized DatabaseHelper getInstance(Context context) {
    if (instance == null) {
        instance = new DatabaseHelper(context.getApplicationContext());
    }
    return instance;
}

`

Can i also use these code to access sqflite's database created in Flutter code, as write data to database in android specific code, and read data in flutter code somewhere

alextekartik commented 4 years ago

In theory, you should be able to have multiple connections to the same database, so it should be possible to have one connection on the flutter side and one connection on the native side. I have not tried it yet though and having multiple connections always expose a risk of being locked and to have to handle new errors.

xilibro commented 4 years ago

Thanks for your reply, i will have a try.

medyas commented 4 years ago

if any is trying to access Sqflite from native Android, you can access it using:


class DatabaseHelper(context: Context) {
    private val dbPath = PathUtils.getDataDirectory(context) + "/" + DATABASE_NAME
    private var sqliteDatabase: SQLiteDatabase

    init {
        sqliteDatabase = SQLiteDatabase.openDatabase(dbPath, null,
                SQLiteDatabase.CREATE_IF_NECESSARY)
    }

    //TODO: add you method to CRUD the database

    fun close() {
        sqliteDatabase.close()
    }

    companion object {
        @Synchronized
        fun getInstance(context: Context): DatabaseHelper {
            if (instance == null) instance = DatabaseHelper(context)
            return instance as DatabaseHelper
        }

        var instance: DatabaseHelper? = null
        private const val TABLE_NAME = "table_name"
        private const val DATABASE_NAME = "database_name_used_in_flutter_sqflite.db"
    }
}