写入数据库时​​的领域空指针 [英] Realm null pointer when writing to database

查看:58
本文介绍了写入数据库时​​的领域空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

空指针应该很容易修复,但是我不明白为什么在这里得到NullPointerException.

Null pointers should be easy to fix, but I cannot understand why I get NullPointerException here.

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.

User is not null, so I should setCity for this object. I create new City with given data.

推荐答案

此处的问题是new City(0, city, city)是独立对象. Realm将生成要在Realm内部使用的代理类.在这里使用setCity播放游戏时,您需要通过代理传递对象.

The problem here is new City(0, city, city) is a standalone object. Realm will generate a proxy class to be used inside Realm. And when play with setCity here, you need to pass a object with proxy.

您可以尝试以下操作: user.setCity(realm.copyToRealmOrUpdate(new City(0, city, city)));

You can try this: user.setCity(realm.copyToRealmOrUpdate(new City(0, city, city)));

请参见此处

这篇关于写入数据库时​​的领域空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆