Я начинаю изучать Realm DB на Android Studio и создаю приложение для управления хранилищем. Я начинаю с создания базы данных. java класса:
public class Database {
private List<Product> database = new ArrayList<Product>();
public Database() {
addAllProducts();
}
private void addAllProducts(){
database.add( new Product( "Sock", "s1", "Jacquard-knit socks in a soft cotton blend with elastication at top.", 4.99, "clothes", 1.99) );
database.add( new Product( "Shirt", "s2", "Regular Fit – a classic fit with good room for movement and a gently shaped waist.", 39.99, "clothes" ) );
database.add( new Product( "Shoe", "s3", "Chelsea boots with elastic panels at sides and a loop at back.", 59.99, "clothes" ) );
database.add( new Product( "Hat", "s4", "Hat in crocheted paper straw.", 19.99, "clothes" ) );
database.add( new Product( "Hoodie", "s5", "Long-sleeved sweatshirt in soft fabric with a lined drawstring hood, kangaroo pocket.", 24.99, "clothes" ) );
database.add( new Product( "Sweatshirt", "s6", "Soft sweatshirt with a slightly looser fit.", 14.99, "clothes" ) );
database.add( new Product( "Jacket", "s7", "Soft sweatshirt with a slightly looser fit.", 79.99, "clothes" ) );
database.add( new Product( "Coat", "s8", "Straight-cut, double-breasted coat in felted wool-blend fabric.", 129.99, "clothes" ) );
database.add( new Product( "Cardigan", "s9", "Fine-knit cardigan in cotton with a shawl collar, buttons at front.", 49.99, "clothes" ) );
database.add( new Product( "Blazer", "s10", "Single-breasted blazer in woven stretch fabric with narrow, notched lapels.", 79.99, "clothes" ) );
database.add( new Product( "Shorts", "s11", "5-pocket shorts in washed denim with heavily distressed details.", 34.99, "clothes" ) );
database.add( new Product( "Banana", "s12", "Bananas are a healthy source of fiber, potassium, vitamin B6, vitamin C, and various antioxidants.", 999.99, "food" ) );
database.add( new Product("Lemon","s13","The lemon fruit is an ellipsoid berry surrounded by a green rind, which ripens to yellow, protecting soft yellow segmented pulp.", 599.99,"food")); database.add( new Product("Apple","s14","An apple is a sweet, edible fruit produced by an apple tree.", 699.99,"food"));
database.add( new Product("Watermelon","s15","Watermelon is a plant species in the family Cucurbitaceae, a vine-like flowering plant originating in West Africa.", 799.99,"food"));
database.add( new Product("Tuna","s16","A tuna is a saltwater fish that belongs to the tribe Thunnini, a subgrouping of the Scombridae (mackerel) family.", 199.99,"food"));
database.add( new Product("Noodle","s17","Noodles are a type of food made from unleavened dough which is rolled flat and cut, stretched or extruded, into long strips or strings.", 299.99,"food"));
database.add( new Product("Rice","s18","Rice is the seed of the grass species Oryza sativa (Asian rice) or Oryza glaberrima (African rice). ", 399.99,"food"));
}
public Product getProduct(int i){
Product result = null;
if ( i < database.size() )
result = database.get(i);
return result;
}
public Product findProduct( String searchName){
Product result = null;
for( int i = 0; i < database.size(); i++ ){
if( searchName.equalsIgnoreCase( database.get(i).getName() ) )
result = database.get(i);
}
return result;
}
public List<Product> getDatabase() {
return database;
}
public int getSize(){
return database.size();
}
}
и уровня приложения RealmInitializer. java, который инициализирует Realm при запуске приложения:
public class RealmInitializer extends Application {
private Realm realm;
public static Database database;
private List<Product> productList;
@Override
public void onCreate(){
super.onCreate();
database = new Database();
Realm.init(this);
realm = Realm.getDefaultInstance();
createRealmDatabase();
}
private void createRealmDatabase(){
productList = database.getDatabase();
addtoRealm(productList);
}
private void addtoRealm(List list){
realm.beginTransaction();
realm.insertOrUpdate(list);
realm.commitTransaction();
}
}
Моя проблема заключается в том, что я хочу, чтобы база данных в default.realm , найденная в устройстве, отражала только количество продукта. У меня есть List<Product>
, на котором я выполняю insertOrUpdate()
. Я пытался закомментировать другие продукты, чтобы в списке продуктов был только один элемент, но файл default.realm не изменился соответствующим образом или при попытке заменить продукты в моем List<Product>
с чем-то еще, он просто добавил бы это к уже существующим данным. Где я go ошибся?