When using ActiveAndroid you may face the problem that the database Model class already declears an id
field as primary key and you actually need that id
field for your own purposes. The following will describe how to change the primary key identifier of ActiveAndroid so you can use your own id
definition.
Let's face an example by declaring a class like Item
to interact with an API. The Item
class requires an id
field as the main identifier.
public class Item {
private long id;
private String name;
}
Now you don't want to create an extra model for the ActiveAndroid database mapping and just use the existing class as your database model. You have to annotate the class and its properties with required annotations.
@Table(name = "Items")
public class Item extends Model {
@Column(name = "id")
private long id;
@Column(name = "name")
private String name;
}
Now your database mapping is done, but will run into errors during runtime since ActiveAndroid will collide and override your id
value with its own id
field.
Solution
Solving this problem is quite simple: define the column name for ActiveAndroid's default primary key. You can do this by setting the id field in the table annotation:
@Table(name = "Items", id = "_id")
public class Item extends Model {
@Column(name = "id")
private long id;
@Column(name = "name")
private String name;
}
ActiveAndroid will use your defined identifier "_id"
as the primary key column name and you can use your property "id"
without hassle.
Enjoy coding!