Realm null pointer when writing to database

2019-08-09 11:24发布

问题:

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();
}

And my stacktrace :

 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 is not null, so I should setCity for this object. I create new City with given data.

回答1:

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.

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

See doc here



回答2:

I have managed to solve this issue. Aparently I can't create new object and save it to Realm, so I did it the other way.

 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();
}