0

I added a new column to sqflite database. After that, I can't use my application when update application. I should uninstall and re-install. How to handle this kind of situation?

class HelperDatabase1 {
  static final HelperDatabase1 _instance = HelperDatabase1.internal();

  factory HelperDatabase1() => _instance;
  static Database _db;

  Future<Database> get db1 async {
    if (_db != null) return _db;
    _db = await initDb();
    return _db;
  }

  HelperDatabase1.internal();

  initDb() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "HelperDatabase.db");
    var theDb = await openDatabase(path, version: 2, onCreate: _onCreate);
    return theDb;
  }

  void _onCreate(Database db, int version) async {
await db.execute("CREATE TABLE GetUserPreferenceTable(id INTEGER PRIMARY KEY AUTOINCREMENT, data INTEGER)");
}

in my main.dart

var helper;

void main() async {
  // debugPaintSizeEnabled=false;
  helper =
  await HelperDatabase1(); 

1 Answers1

0

Without seeing your specific error, it is likely that you need to increment your database's version number in the openDatabase() method to notify of a schema change.

For example, if you are using code similar to the following to create your database, you would increment the version from 1 to 2:

createDatabase() async {
  String databasesPath = await getDatabasesPath();
  String dbPath = join(databasesPath, 'my.db');

  var database = await openDatabase(dbPath, version: 2, onCreate: populateDb);
  return database;
}
Josh Sullivan
  • 360
  • 3
  • 10
  • 1
    I tried. Nothing is happening. I added a new id to my table with primary key and auto increment. But not working –  May 21 '19 at 17:51
  • Override the onUpgrade() method - https://pub.dev/documentation/sqflite/latest/sqlite_api/OpenDatabaseOptions/onUpgrade.html – Josh Sullivan May 21 '19 at 21:20
  • See this question - https://stackoverflow.com/questions/8291673/how-to-add-new-column-to-android-sqlite-database – Josh Sullivan May 21 '19 at 21:20