Search code examples
androidandroid-activityparcelableserializable

Send list of objects which contain other custom objects from one activity to another


This is my class whose list I want to send to another activity.

public class PostComments {

    public User from;

    public String message;

    public String createdTime;

    public String like_count;

    public Boolean user_likes;
}

This is User class whose object is used in PostComments class.

public class User extends BaseEntity{
    public String photoUrl;
}

And this is BaseEntity Class

public class BaseEntity {
    public String Id;

    public String Name;
}

How can I send this object from one activity to another?

PostComments[] myData = ClickedPost.comments.data;
Intent PostCommentsActivity = new Intent(getActivity() , PostCommentsActivity.class);
getActivity().startActivity(PostCommentsActivity);

Above is the code to open PostCommentsActivity and I want to send myData object to the PostCommentsActivity.

I have searched alot about this problem but every question and tutorial explain that only for a class which contains simple string, int or boolean variables.


Solution

  • Let's try:

    ArrayList<PostComments> comments = new ArrayList<MainActivity.PostComments>();
    comments.add(...) //Add your list data here
    Intent intent = new Intent(getActivity() , PostCommentsActivity.class);
    intent.putExtra("list_comments", comments);
    getActivity().startActivity(intent);
    

    And edit your PostComments Class to:

    public class PostComments implements Serializable {
    
            public String message;
    
            public String createdTime;
    
            public String like_count;
    
            public Boolean user_likes;
        }
    

    In PostCommentsActivity, get bundle to get list comments.