Android Room - auto increment @database version nu

2020-06-04 16:32发布

问题:

During development my Room db schema is very volatile. Every time I do any change to the schema I need to update my version number, like this;

@Database(version = 27,
    entities = {MyClass.class})

public abstract class MyDatabase extends RoomDatabase

I am using fallbackToDestructiveMigration too;

Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, SystemStrings.ROOM_DATABASE_NAME)
                // allow queries on the main thread.
                // Don't do this on a real app! 
                .allowMainThreadQueries()
                .fallbackToDestructiveMigration()
                .build();

Is there any way to avoid updating the version number for each "little" change? As I said, things are quite volatile right now.

回答1:

Deleteing the database would result in it being initialised/built each time the App is run.

You could do this using :-

context.getApplicationContext().deleteDatabase(SystemStrings.ROOM_DATABASE_NAME); //<<<< ADDED before building Database.
//Your existing code follows 
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, SystemStrings.ROOM_DATABASE_NAME)
                // allow queries on the main thread.
                // Don't do this on a real app! 
                .allowMainThreadQueries()
                .fallbackToDestructiveMigration()
                .build();

Of course you would not have this in the real app