我使用RealmString替代List<字符串>在Realm Android中。 但是我遇到了RealmChangeListener的问题。我在下面的例子中使用了许多模型中的RealmString,如Dog,Cat,Chicken。 但当任何人改变数据时,所有这些都会改变。
Ex:当我拯救狗时 - >狗变化和猫变化。
我可以通过使用RealmDogString,RealmCatString,RealmChickenString解决这个问题,但它复制了我的代码。有没有更好的解决方案?
这是我的示例代码:
public class RealmTestActivity extends AppCompatActivity {
private Context context;
private Realm realm;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_realm_test);
Stetho.initialize(
Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build()).build());
context = this;
RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(realmConfig);
realm = Realm.getDefaultInstance();
final RealmResults<Dog> puppies = realm.where(Dog.class).lessThan("age", 2).findAll();
puppies.addChangeListener(new RealmChangeListener<RealmResults<Dog>>() {
@Override
public void onChange(RealmResults<Dog> results) {
System.out.println("XXX Dog ::" + puppies.size());
Toast.makeText(context, "Dog Change", Toast.LENGTH_SHORT).show();
puppies.size();
}});
final RealmResults<Cat> puppiesCat = realm.where(Cat.class).lessThan("age", 2).findAll();
puppiesCat.addChangeListener(new RealmChangeListener<RealmResults<Cat>>() {
@Override
public void onChange(RealmResults<Cat> results) {
System.out.println("XXX Cat ::" + puppiesCat.size());
Toast.makeText(context, "Cat Change", Toast.LENGTH_SHORT).show();
}
});
}
public void saveDog(View view) {
Dog dog = new Dog();
dog.setName("Bella");
dog.setAge(1);
RealmList<RealmString> realmStrings = new RealmList<RealmString>();
RealmString realmString = new RealmString();
realmString.setValue("link_Bella.png");
realmStrings.add(realmString);
dog.setImage(realmStrings);
realm.beginTransaction();
realm.copyToRealm(dog);
realm.commitTransaction();
}
public void saveCat(View view) {
Cat cat = new Cat();
cat.setName("Oliver");
cat.setAge(1);
RealmList<RealmString> realmStrings_2 = new RealmList<RealmString>();
RealmString realmString_2 = new RealmString();
realmString_2.setValue("link_Oliver.png");
realmStrings_2.add(realmString_2);
cat.setImage(realmStrings_2);
realm.beginTransaction();
realm.copyToRealm(cat);
realm.commitTransaction();
}
}