我想连接数据库中的数据并在列表视图中显示
但我在对象Realm中有错误并停止了我的应用程序
如何解决问题??
protected void onResume() {
super.onResume();
Realm realm = Realm.getInstance(getApplicationContext());
realm.beginTransaction();
List<Car> cars = realm.allObjects(Car.class);
String[] names = new String[cars.size()];
for (int i = 0; i < names.length; i++) {
names[i] = cars.get(i).getName();
}
ListView listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
}
}
答案 0 :(得分:-1)
除了你没有指定logcat之外,Realm可能会告诉你,你已经打开了一个事务并且崩溃了。
您只需要将事务写入附加到领域的RealmObject
。您还需要关闭打开的每个领域实例。您还必须注意,您无法从封闭的领域中读取。
例如,这有效:
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.
}
}