我有类别类:
@Entity(tableName = "Categories",indices = {@Index(value = {"id"},
unique = true)})
public class Category implements Serializable {
public Category(String name,int icon,int color)
{
_name= name;
_icon = icon;
_color = color;
}
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "name")
public String _name;
@ColumnInfo(name = "icon")
public int _icon;
@ColumnInfo(name = "color")
public int _color;
public String get_name() {return _name;}
public int getColor() {
return _color;
}
public int getIcon() {
return _icon;
}
}
我想在新创建数据库时创建常量行,而不是每次加载应用程序时创建常量行。 我到现在所做的是:
protected CategorySingletone() {
// Exists only to defeat instantiation.
AppDatabase db = AppDatabase.getAppDatabase(MainActivity.get().getApplicationContext());
if (db.categoryDao().countCategories()==0) {
_categoryList = new ArrayList<>();
_categoryList.add(new Category("Cars", R.drawable.couch, 3));
_categoryList.add(new Category("Tech", R.drawable.phone, 3));
_categoryList.add(new Category("Home", R.drawable.book_1, 3));
_categoryList.add(new Category("Leisure", R.drawable.book_1, 3));
_categoryList.add(new Category("Motors", R.drawable.book_4, 3));
_categoryList.add(new Category("Fashion", R.drawable.book_5, 3));
for (Iterator<Category> i = _categoryList.iterator(); i.hasNext();) {
Category item = i.next();
db.categoryDao().insertAll(item);
}
}
我正在检查行是否存在。 有更好的方法吗?
答案 0 :(得分:0)
更有效的方法是使用DatabaseUtils
queryNumEntries
方法。
e.g。
if (DatabaseUtils.queryNumEntries(db,"Categories") == 0) {
.......
}