写入数据库时​​Realm空指针

时间:2015-07-16 13:37:42

标签: nullpointerexception realm

空指针应该很容易修复,但我无法理解为什么我在这里得到NullPointerException

public static void updateUserCity(String city, Context context) {
    Realm realm = Realm.getInstance(context);
    realm.beginTransaction();
    RealmQuery<User> query = realm.where(User.class);
    User user = query.findFirst();
    if (user != null) {
        user.setCity(new City(0, city, city)); // here it crashes
    }
    realm.commitTransaction();
}

我的堆栈跟踪:

 java.lang.NullPointerException
        at io.realm.UserRealmProxy.setCity(UserRealmProxy.java:118)
        at com.ratata.adapters.DatabaseAdapter.updateUserCity(DatabaseAdapter.java:38)
        at com.ratata.services.userManagment.UserManager.updateCity(UserManager.java:30)
        at com.ratata.dialogs.MainTabDialog.updateUserData(MainTabDialog.java:92)
        at com.ratata.dialogs.MainTabDialog.updateTab(MainTabDialog.java:84)
        at com.ratata.dialogs.MainTabDialog.access$000(MainTabDialog.java:32)
        at com.ratata.dialogs.MainTabDialog$2.onClick(MainTabDialog.java:50)
        at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:153)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

User不是null,因此我应该setCity这个对象。我用给定的数据创建new City

2 个答案:

答案 0 :(得分:3)

这里的问题是new City(0, city, city)是一个独立的对象。 Realm将生成一个在Realm中使用的代理类。当在这里玩setCity时,你需要传递一个带代理的对象。

你可以试试这个: user.setCity(realm.copyToRealmOrUpdate(new City(0, city, city)));

请参阅文档here

答案 1 :(得分:1)

我设法解决了这个问题。显然,我无法创建新对象并将其保存到Realm,所以我采用了其他方式。

 public static void updateUserCity(String city, Context context) {
    Realm realm = Realm.getInstance(context);
    realm.beginTransaction();
    RealmQuery<User> query = realm.where(User.class);
    User user = query.findFirst();
    City realmCity = user.getCity();
    realmCity.setName(city);
    realmCity.setRepresentativeName(city);
    user.setCity(realmCity);
    realm.commitTransaction();
}