private void addAction() {
String what = mInputWhat.getText().toString();
long now = System.currentTimeMillis();
Realm.init(getContext());
RealmConfiguration configuration = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(configuration);
Realm realm = Realm.getDefaultInstance();
Drop drop = new Drop(what, now, 0, false);
realm.beginTransaction();
realm.copyToRealm(drop);
realm.commitTransaction();
realm.close();
}
}
每当我不创建contexet时,应用程序就会崩溃 但是当我使用Realm.init(getContext())创建上下文时,“添加它”按钮不起作用enter image description here
答案 0 :(得分:1)
您必须在从Application扩展的类中初始化Realm。请参见下面的代码:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder()
.name("appName.realm")
.schemaVersion(1)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(config);
}
}
之后,您可以在任何地方调用Realm类
别忘了将此行添加到清单应用程序标记
android:name="com.example.MyApplication"