简体   繁体   English

Recyclerview from parcelable arraylist

[英]Recyclerview from parcelable arraylist

I have an arraylist of custom objects nested inside another arraylist like this:我有一个 arraylist 自定义对象嵌套在另一个 arraylist 中,如下所示:

public class Person implements Parcelable {
private String Name;
private float Age;
private String Email;
ArrayList<Hobbies> Hobbies;


public Person(String name, float age, String email, ArrayList<Hobbies> hobbies) {
    this.Name = name;
    Age = age;
    this.Email = email;
    this.Hobbies = hobbies;
}

I pass this arraylist from MainActivity to another activity using 'putParcelableArrayListExtra()'我使用“putParcelableArrayListExtra()”将这个 arraylist 从 MainActivity 传递到另一个活动

intent.putParcelableArrayListExtra(HOBBIES_ARRAY, Person.get(position).getHobbies());

I use this to retrieve it我用它来检索它

hobbiesArray = new Arraylist<>();
hobbiesArray = getIntent().getParcelableArrayListExtra(MainActivity.HOBBIES_ARRAY);

I then add this list to recyclerview然后我将此列表添加到 recyclerview

hobbiesRecycler = findViewById(R.id.HobbyRecycler);
mLayoutManager = new LinearLayoutManager(this);
adapter = new HobbiesAdapter(hobbiesArray);
hobbiesRecycler.setLayoutManager(mLayoutManager);
hobbiesRecycler.setAdapter(adapter);
adapter.notifyDataSetChanged();

This is the error i'm getting: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference at com.example.ReminderApp.hobbiesAdapter.getItemCount(hobbiesAdapter.java:55) This is the error i'm getting: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference at com.example.ReminderApp.hobbiesAdapter.getItemCount(hobbiesAdapter.java:55)

Edit: I'm also adding items to the arraylist from the second activity编辑:我还在第二个活动中向 arraylist 添加项目

Are Hobbies Parcelable too?爱好也可以打包吗? From the code you have shown, The class Person is parcelable So that can be sent.从您显示的代码中,class 人是可包裹的,因此可以发送。

You can use http://www.parcelabler.com/ to ensure all the methods required are set.您可以使用http://www.parcelabler.com/确保设置了所有需要的方法。

Try sending Person and then retrieving the Hobbies from the Person class.尝试发送 Person,然后从 Person class 中检索爱好。

Add null check to your getItemsCount function in Adapter.将 null 检查添加到适配器中的 getItemsCount function。

 .... getItemsCount(){
     returm yourList != null ? yourList.size() : 0;
}

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

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