Realm null pointer when writing to database

Null pointers should be easily fixed, but I cannot understand why I get a 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 stack:

  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 not null , so I have to setCity for this object. I am creating a new City with data.

+1
source share
2 answers

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

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

See doc here

+3
source

I managed to solve this problem. I cannot create a new object and save it in Realm , so I did it in a different 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(); } 
+1
source

Source: https://habr.com/ru/post/1233819/


All Articles