简体   繁体   中英

Recyclerview from parcelable arraylist

I have an arraylist of custom objects nested inside another arraylist like this:

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()'

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

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)

Edit: I'm also adding items to the arraylist from the second activity

Are Hobbies Parcelable too? From the code you have shown, The class Person is parcelable So that can be sent.

You can use http://www.parcelabler.com/ to ensure all the methods required are set.

Try sending Person and then retrieving the Hobbies from the Person class.

Add null check to your getItemsCount function in Adapter.

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

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