简体   繁体   中英

NullpointerException while using RealM

I am using the RealM Library to store my values in the database. The problem is that since RealM does not support AutoIncrement i am trying to implement it by my own.

This is my modal class:

public class User extends RealmObject{

    @PrimaryKey
    private int id;
    private String name;
    private  int rollno;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getRollno() {
        return rollno;
    }

    public void setRollno(int rollno) {
        this.rollno = rollno;
    }


    public int getid() {
        return id;
    }

    public void setid(int id) {
        this.id = id;
    }

}

I my main class i have a function named insertValues in which i am inserting the data in the database.

 public void insertValues(Realm realm,String name,int rollNo)
    {

        realm.beginTransaction();

        int nextId = (int)(realm.where(User.class).maximumInt("id") + 1); // this line gives me nullpointer error. Please help

        User user = realm.createObject(User.class);
        user.setName(name);
        user.setRollno(rollNo);
        realm.commitTransaction();
    }

My Logcat:

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at io.realm.RealmQuery.maximumInt(RealmQuery.java:1421)
at realmsample.bd.com.realmsample.MainActivity.insertValues(MainActivity.java:105)
at realmsample.bd.com.realmsample.MainActivity$1.onClick(MainActivity.java:53)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
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)

See here , It's fairly similar as your issue, So as suggested,

If max related function is called on an empty results query or query's results are all null values, maximumInt will throw an exception.

So use RealmQuery.max() instead.

The problem lies in your code while fetching max value of "id" field. When you add first object in the database, maximumInt("id") will be NULL .

So you need to keep an if condition to prevent NPE.

int nextId = 1;
if (realm.where(User.class).findAll().size() > 0) {
    nextId  = (int)(realm.where(User.class).maximumInt("id") + 1)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM