Issue
I have a question. I edited my Room entity from this:
@Entity(tableName = "users")
public class User {
public User(String username, String email, String password){
this.username = username;
this.email = email;
this.password = password;
}
public User() {}
@PrimaryKey
@ColumnInfo(name = "Username")
private String username;
@ColumnInfo(name = "Email")
private String email;
@ColumnInfo(name = "Password")
private String password;
//getters setters
To this form:
@Entity(tableName = "users")
public class User {
public User(String username, String email, String password){
this.username = username;
this.email = email;
this.password = password;
}
public User() {}
//changes here, move userId to int instead of username
@NonNull
@PrimaryKey(autoGenerate = true)
private int id;
@NonNull
@ColumnInfo(name = "Username")
private String username;
@ColumnInfo(name = "Email")
private String email;
@ColumnInfo(name = "Password")
private String password;
//getters setters.
And this is how looks my RoomDatabase
class:
@Database(entities = {User.class}, version = 1)
public abstract class ApplicationDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
My question is when I edit an entity if the database in my android device change? What if I had data in my database? If I need to drop the database on my device first? What about my constructor for user, it will work now?
Thanks for any advice
Solution
When you edit your entities you need to change the version of your database, in that case, change the annotation to @Database(entities = {User.class}, version = 2)
It is up to you to decide whether you want to drop old data of your database or you want to migrate the old version to the newer one (I would recommend it if you have a user base and you don't want them to lose their saved data in the database otherwise I would recommend you to drop the information in the old database because it is the easier solution).
In case you want to read further about migrating your room database I have added a link:
https://developer.android.com/training/data-storage/room/migrating-db-versions
Answered By - Gal
Answer Checked By - Cary Denson (JavaFixing Admin)