除了您没有指定 logcat 之外,Realm 可能会告诉您您已将事务打开并崩溃。
您只需要将事务写入附加到领域的RealmObjects。您还需要关闭您打开的每个领域实例。您还必须注意,您无法从封闭领域进行读取。
例如,这是有效的:
Realm realm = null;
try {
Cat cat = new Cat(); //public class Cat extends RealmObject {
cat.setName("Meowmeow"); //cat is not yet attached to a realm, therefore you can modify it
realm = Realm.getInstance(context); //open instance of default realm
realm.beginTransaction();
realm.copyToRealmOrUpdate(cat); //cat is now attached to the realm,
//and cannot be written outside the transaction.
realm.commitTransaction();
} catch(Exception e) {
if(realm != null) {
try { //newer versions of Realm like 0.84.0+ have `realm.isInTransaction()`
realm.cancelTransaction();
} catch(IllegalStateException e) {
//realm not in transaction
}
}
throw e;
} finally {
if(realm != null) {
realm.close(); //every open realm must be closed
}
}
如果您使用的是较新版本的 Realm,您也可以在后台线程上执行此操作,而无需手动打开和关闭。
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
// begin and end transaction calls are done for you
Dog dog = realm.where(Dog.class).equals("age", 1).findFirst();
d.setAge(3);
}
}, new Realm.Transaction.Callback() {
@Override
public void onSuccess() {
// Original RealmResults<T> objects and Realm objects
// are automatically updated
// ON THREADS THAT HAVE A LOOPER ASSOCIATED WITH THEM (main thread)
//the realm is written and data is updated, do whatever you want
}
});
对于显示您的数据,这有效(0.83.0+):
public class HelloWorldActivity extends AppCompatActivity {
protected Realm realm;
ListView listView;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
realm = Realm.getInstance(this);
setContentView(R.layout.activity_hello_world);
this.listView = (ListView)findViewById(R.id.list_view);
listView.setAdapter(new CarAdapter(this, realm.where(Car.class).findAll(), true);
}
@Override
public void onDestroy() {
realm.close();
}
}
你需要一个适配器来为你的... listView...
public class CarAdapter extends RealmBaseAdapter<Car> {
public RealmModelAdapter(Context context, RealmResults<Car> realmResults, boolean automaticUpdate) {
super(context, realmResults, automaticUpdate);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO
//implement viewholder pattern here:
//http://developer.android.com/training/improving-layouts/smooth-scrolling.html#ViewHolder
//Listview is obsolete so I won't bother,
//use RecyclerView when you get the chance.
}
}