繁体   English   中英

使用Parcelable发送StringArray时发生NullPointerException

[英]NullPointerException while sending StringArray using Parcelable

用parcelable对象发送意图时我遇到了奇怪的问题。 这个对象有一个String数组。 使用此答案如何使用Intents将对象从一个Android Activity发送到另一个? 我首先将我的对象创建为parcelable,然后发送它。 这是我的代码片段:

    public class MyObject implements Parcelable{

    private String _title = null;
    private String[] _genre;
    private int _time = 0;
    private String _disc = null;

    private static final String TAG = "MyObject";

    public MyObject (String title, String[] genre, int time, String disc) {
        _title = title;
        _genre = genre;
        _time = time;
        _disc = disc;
    }



    public MyObject(Parcel source) {
            /*
             * Reconstruct from the Parcel
             */
            Log.v(TAG, "ParcelData(Parcel source): time to put back parcel data");
            _title = source.readString();
            try{
                source.readStringArray(_genre);
            }catch(Exception e){
                Log.e(TAG,e.toString());
            }
        _time = source.readInt();
        _disc = source.readString();
    }

    /*... Getters and setters and other stuff...*/

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        Log.v(TAG, "writeToParcel..."+ flags);
        dest.writeString(_title);
        dest.writeStringArray(_genre);
        dest.writeInt(_time);
        dest.writeString(_disc);
        Log.i(TAG,_genre[0]);
    }

    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>() {
        public MyObject createFromParcel(Parcel in) {
            return new MyObject(in);
        }

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

发送似乎没问题。

Intent displayInfo = new Intent(getApplicationContext(), MovieInfo.class);
                    displayInfo.putExtra(OBJECT, mySQLiteAdapter.getEntry(idSet));
                    startActivity(displayInfo);

但是,当我试图获取此数据时

Intent intent = getIntent();
        myParcel = (MyObject) intent.getParcelableExtra(FBM2Activity.OBJECT);

我从readStringArray得到NullPointerException 有谁知道我哪里有错误?

使用_genre = source.createStringArray()

这背后的原因是readStringArray(String[] val)期望val是一个String[] ,它已经使用正确数量的数组元素创建。 你这样做的方式,当你调用source.readStringArray(_genre)时, _genrenull

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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