有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java GetParcelableExtract在NullPointerException中返回

我试图从Mainactivity中打开DetailActivity,使用的意图是将实现Parcelable的类对象作为额外对象。在调用putExtra之前,我确实检查了对象是否具有正确的数据。堆栈指向对readList的调用

主要活动。爪哇

    movieViewAdapter =  new MovieViewAdapter(new ArrayList<Movies>(), new MovieViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Movies movie) {
                Intent intent = new Intent(MainActivity.this,DetailActivity.class);
                intent.putExtra("thisMovie",movie);
                startActivity(intent);
            }
        });

这将打开DetailsActivity。爪哇

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_main);
        ButterKnife.bind(this);
        // Line 52
        Movies movie =  (Movies) getIntent().getParcelableExtra("thisMovie");
        .....
        .....           
    }

我发现以下错误:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at 安卓.os.Parcel.readListInternal(Parcel.java:3177)
at 安卓.os.Parcel.readList(Parcel.java:2178)
at com.example.安卓.popularmoviesstage1.Models.Movies$1.createFromParcel(Movies.java:73)
at com.example.安卓.popularmoviesstage1.Models.Movies$1.createFromParcel(Movies.java:56)
at 安卓.os.Parcel.readParcelable(Parcel.java:2851)
at 安卓.os.Parcel.readValue(Parcel.java:2745)
at 安卓.os.Parcel.readArrayMapInternal(Parcel.java:3114)
at 安卓.os.BaseBundle.initializeFromParcelLocked(BaseBundle.java:273)
at 安卓.os.BaseBundle.unparcel(BaseBundle.java:226)
at 安卓.os.Bundle.getParcelable(Bundle.java:939)
at 安卓.content.Intent.getParcelableExtra(Intent.java:7167)
at com.example.安卓.popularmoviesstage1.Activities.DetailActivity.onCreate(DetailActivity.java:52)

这是我对电影的实现。爪哇

public final static Parcelable.Creator<Movies> CREATOR = new Creator<Movies>() {
        @SuppressWarnings({
                "unchecked"
        })
        public Movies createFromParcel(Parcel in) {
            Movies instance = new Movies();
            ....
            ....
            //Line 73
            in.readList(instance.genreIds, (java.lang.Integer.class.getClassLoader()));
            ....
            ....
            return instance;
        }
        public Movies[] newArray(int size) {
            return (new Movies[size]);
        }
};

共 (1) 个答案

  1. # 1 楼答案

    你应该使用Parcelable的插件来生成POJO。对我来说非常有效。 该插件在Android Studio插件库中可用