未找到默认的RealmConfiguration。调用setDefaultConfiguration()

时间:2016-05-31 10:26:48

标签: java android realm

我正在尝试通过创建简单的测试应用程序来学习如何使用Realm,但我总是得到这个错误。我正在使用Realm 1.0.0。 logcat中的错误:

java.lang.NullPointerException: No default RealmConfiguration was found. 
Call     setDefaultConfiguration()

这是Mainactivity中的代码。

public class MainActivity extends AppCompatActivity {
EditText name;
EditText age;
TextView result;
Realm myRealm;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    name= (EditText) findViewById(R.id.editText);
    age=(EditText)findViewById(R.id.editText2);
    result= (TextView) findViewById(R.id.textView);
    myRealm= Realm.getDefaultInstance();

}
public void store(){
myRealm.beginTransaction();
    User user=myRealm.createObject(User.class);
    user.setName(name.getText().toString());
    user.setAge(Integer.parseInt(age.getText().toString()));
    myRealm.commitTransaction();
}

public void load(View view) {
    RealmResults<User>results=myRealm.where(User.class).findAll();
    StringBuffer stingBuffer=new StringBuffer();
    for(User user:results){
        stingBuffer.append(user.getName()+" - "+user.getAge()+"\n");
    }
    result.setText(stingBuffer.toString());
}

1 个答案:

答案 0 :(得分:2)

添加 您MyApplication文件中的RealmCOnfiguration

//在您的应用程序中设置领域

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
}