当我启动Android应用程序时,我登录Realm Object Server并从Realm Server Object下载(同步)数据。 好。 现在我得到片段显示人员名单。
这里代码:
public class PersonsFragment extends Fragment {
private ListView notEmptytsListView;
private Realm realm;
private RealmResults<Person> personsRealmResults;
private PersonsAdapter personsAdapter; // RealmBaseAdapter<Organization>
private RealmChangeListener realmChangeListener;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.persons_fragment, container, false);
init(rootView);
return rootView;
}
private void init(View view) {
realm = Realm.getDefaultInstance();
notEmptytsListView = (ListView) view.findViewById(R.id.notEmptytsListView);
personsRealmResults = realm.where(Person.class).findAllSorted(Person.NAME);
personsAdapter = new PersonsAdapter(personsRealmResults);
notEmptytsListView.setAdapter(personsAdapter);
// NOT CALL WHEN DATA ON REALM OBJECT SERVER WAS CHANGED
realmChangeListener = new RealmChangeListener() {
@Override
public void onChange(Object object) {
personsAdapter.notifyDataSetChanged();
}
};
personsRealmResults.addChangeListener(realmChangeListener);
}
@Override
public void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
}
如果我继续使用Fragm并在Realm Object Server(远程Realm)上更改数据,则本地数据不会同步。不调用onChanged()方法。
我如何解决这个问题?
答案 0 :(得分:0)
public class MyFragment extends Fragment {
RealmResults<Person> personsRealmResults; // <--
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.persons_fragment, container, false);
notEmptytsListView = (ListView) view.findViewById(R.id.notEmptytsListView);
realm = Realm.getDefaultInstance();
personsRealmResults = realm.where(Person.class).findAllSorted(Person.NAME);
personsAdapter = new PersonsAdapter(personsRealmResults);
notEmptytsListView.setAdapter(personsAdapter);
realmChangeListener = new RealmChangeListener() {
@Override
public void onChange(Object object) {
// call when data on Realm Object Server was changed
}
};
personsRealmResults.addChangeListener(realmChangeListener);
return rootView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
}
虽然PersonsAdapter
是RealmBaseAdapter
可能会更容易。 (见docs)