我有位置课。
package com.example.phamf.javamvvmapp.Model;
import ...
@Entity (tableName = "location")
public class Location {
@PrimaryKey(autoGenerate = true)
private int id;
private float x;
private float y;
private String name;
public Location(int id, float x, float y, String name) {
this.id = id;
this.x = x;
this.y = y;
this.name = name;
}
public Location () {
}
}
我想添加一个名为type的新字段,它的类型是INTEGER,所以我修改上面的Location.java文件
package com.example.phamf.javamvvmapp.Model;
import ...
@Entity (tableName = "location")
public class Location {
@PrimaryKey(autoGenerate = true)
private int id;
private int type;
private float x;
private float y;
private String name;
public Location(int id, float x, float y, String name, int type) {
this.id = id;
this.x = x;
this.y = y;
this.name = name;
this.type = type;
}
public Location () {
}
}
@Database(entities = {Location.class}, version = 2)
public abstract class LocationRoomDatabase extends RoomDatabase {
private static LocationRoomDatabase DATABASE;
public static LocationRoomDatabase getDatabase (final Context context) {
Migration migration = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE location ADD type INTEGER");
}
};
if (DATABASE == null) {
DATABASE = Room.databaseBuilder(context, LocationRoomDatabase.class, "database")
.addMigrations(migration).build();
}
return DATABASE;
}
public abstract LocationDAO locationDAO();
}
问题是当我运行上面的代码时,我得到一个错误
//...
Caused by: java.lang.IllegalStateException:
Migration didn't properly handle location(com.example.phamf.javamvvmapp.Model.Location).
Expected:
TableInfo{..., type=Column{name='type', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, foreignKeys=[], indices=[]}
Found:
TableInfo{..., type=Column{name='type', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
//...
Migration migration = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE location ADD type INTEGER not null");
}
};
我以为它会运行得很好,但后来我出错了
Caused by: android.database.sqlite.SQLiteException: Cannot add a NOT NULL column with default value NULL (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE location ADD type INTEGER not null
private int type = 0;
任何解决这个问题的方法,请帮助我。非常感谢。