当我使用parcelable接口读/写布尔值时,会发生Nullobject Reference,为什么?

时间:2016-10-13 04:24:12

标签: java android

我正在尝试创建一个Parcelable对象,以便传递给我开始编写实现Parcelable的Userclass的活动。

Userare的一个属性是布尔值,所以我通过引用answer来做到这一点。即,How to read/write a boolean when implementing the Parcelable interface?

但是出现了错误,我得到了一个空引用错误。它说:

  

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean java.lang.Boolean.booleanValue()'。

代码如下。

public class User implements Parcelable{
    private String userName;
    private String passWord;
    private Boolean oldUser;

    public String getUserName() {
        return userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public Boolean getOldUser() {
        return oldUser;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public void setOldUser(Boolean oldUser) {
        this.oldUser = oldUser;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        User user = new User();
        parcel.writeString(user.userName);
        parcel.writeString(user.passWord);
        //seems a good way by using the official api.
        //parcel.writeBooleanArray(new boolean[]{user.oldUser});
        //null pointer,why?
        parcel.writeByte((byte) (user.oldUser ? 1 : 0));
    }

    public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
        public User createFromParcel(Parcel in) {
            User user = new User();
            //boolean[] myBooleanArr = new boolean[1];
            user.userName = in.readString();
            user.passWord = in.readString();
            //more codes needed to use the below api.
            //in.readBooleanArray(myBooleanArr);
            //user.oldUser = myBooleanArr[0];

            //method we define using readInt.
            user.oldUser = (in.readInt() != 0);
            return user;
        }

        public User[] newArray(int size) {

            return new User[size];
        }
    };
}

记录消息:

log messages

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.thon.scos, PID: 2838
              java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
                  at es.source.code.model.User$override.writeToParcel(User.java:52)
                  at es.source.code.model.User$override.access$dispatch(User.java)
                  at es.source.code.model.User.writeToParcel(User.java:0)
                  at android.os.Parcel.writeParcelable(Parcel.java:1416)
                  at android.os.Parcel.writeValue(Parcel.java:1322)
                  at android.os.Parcel.writeArrayMapInternal(Parcel.java:665)
                  at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1330)
                  at android.os.Bundle.writeToParcel(Bundle.java:1079)
                  at android.os.Parcel.writeBundle(Parcel.java:690)
                  at android.content.Intent.writeToParcel(Intent.java:7793)
                  at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2639)
                  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1507)
                  at android.app.Activity.startActivityForResult(Activity.java:3917)
                  at android.app.Activity.startActivityForResult(Activity.java:3877)
                  at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:861)
                  at android.app.Activity.startActivity(Activity.java:4200)
                  at android.app.Activity.startActivity(Activity.java:4168)
                  at es.source.code.activity.LoginOrRegister$1.onClick(LoginOrRegister.java:46)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
老实说,我是android和java的新人。我试过编辑

parcel.writeByte((byte) (user.oldUser ? 1 : 0));

parcel.writeByte((byte) (oldUser ? 1 : 0));

太棒了,它确实有效,所有错误都消失了。

解决方案是否正确?我只是想不通。 处理这个问题的最佳方法是什么?感谢。

2 个答案:

答案 0 :(得分:7)

编写宗地时,不应创建新的User对象。您正在对当前对象实例进行操作。

我猜你可以在createFromParcel()方法中执行对象创建和读取包裹的所有逻辑,但我已经更经常地看到下面的模式,将parcel传递给对象的构造函数并在那里处理它。确保以相同的顺序读取和写入包裹的字段。

public class User implements Parcelable {

    private String userName;
    private String passWord;
    private boolean oldUser;

    public User(Parcel in) {
        userName = in.readString();
        passWord = in.readString();
        oldUser = in.readInt() == 1;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(userName);
        dest.writeString(passWord);
        dest.writeInt(oldUser ? 1 : 0);
    }

    public String getUserName() {
        return userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public boolean getOldUser() {
        return oldUser;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public void setOldUser(boolean oldUser) {
        this.oldUser = oldUser;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        public User[] newArray(int size) {
            return new User[size];
        }
    };    

}

答案 1 :(得分:2)

对于真正的布尔(不是布尔)我会选择:

@Override
    public void writeToParcel(Parcel out, int flags) {
        if (open_now == null) {
            out.writeInt(-1);
        } else {
            out.writeInt(open_now ? 1 : 0);    
        }

private MyClass(Parcel in) {
    switch (in.readInt()) {
        case 0:
            open_now = false;
            break;
        case 1:
            open_now = true;
            break;
        default:
            open_now = null;
            break;
    }

这将帮助您保持&#34; null&#34;价值正确。