Hesam Hesam - 1 year ago 185
Android Question

Realm findFirst() method returns null

I searched and found FindFirst returns null question but no one answered it. As I'm thinking I am doing something wrong, let me explain my problem with more details.

I'm working on an app the asks user to sign in first the lets user to use the app.

My User class looks like this:

public class User extends RealmObject {

String id;
String firstName;
String lastName;
String avatar;
int sessions;
int invites;
String nextSessionTime;
String nextSessionTitle;
String lastLogin;
String token;

public String toString() {
return new GsonBuilder().create().toJson(this, User.class);

// other setters and getters

I store User's object in Realm db after successful login in SigninActivity class:

public void onSignInResponse(final GeneralResponse response) {

if (response == null) {
Timber.e("response is null");

if (response.isSuccess()) {
// Store user's info including Token
realm.executeTransaction(new Realm.Transaction() {
public void execute(Realm realm) {

// Goto main screen

} else {
String errorMessage = response.getErrorMessages();

Once login successful, app directs user to MainVideoActivity. I want to find user in realm by following code however I'm getting

protected void onCreate(Bundle savedInstanceState) {


// Create the Realm instance
realm = Realm.getDefaultInstance();
User user = realm.where(User.class).findFirst();
// RealmResults<User> user = realm.where(User.class).findAll();

in both approaches.
enter image description here

However, I can see my none
user in db.
enter image description here

I'm using
classpath "io.realm:realm-gradle-plugin:2.0.2"

Any idea would be appreciated. Thanks.

Answer Source

There are two things here:

  1. The null values in the debug window. That is a known limitation when using Realm with debugger. Since Realm generated a Proxy class to access values, inspecting the RealmObject's field in the debugger won't go through the proxy class. See more details here

  2. The fields with null values are not printed in the toString() method. Realm annotation processor will generate a toString() method if there is no toString() method defined in the RealmObject. I think the problem here is the a User.toString() ignores null values. Try to remove the toString() method in the User class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download