Martin Erlic
Martin Erlic

Reputation: 5667

How can I pass List<String> as an Intent extra?

I have a List that I want to convert into a String[] so that I can pass it as an extra with an intent.

List<String> votedBy = parseObject.getList("votedBy");

The intent logic:

Intent intent = new Intent(CommentActivity.this, UsersListActivity.class);
intent.putExtra(BundleConstants.KEY_LIST_TYPE, getString(R.string.voters));
intent.putExtra(BundleConstants.KEY_VOTERS_LIST, votedBy);
startActivity(intent);

My first thought was to convert the contents of the List to a String[], but that list is retrieved from a database and its size is not known apriori. One suggestion I had was to cast the votedBy List as Parcelable. I can't run the code at the moment so I'm not sure if that will work. What should I do here?

Upvotes: 1

Views: 1993

Answers (3)

SamCle88
SamCle88

Reputation: 275

I think you should try with

List<String> list = ..;
String[] array = list.toArray(new String[0]);

as suggested in this question.
As you can see, the size of the list is never a problem for the conversion, you never need to know it.

Upvotes: 1

MJim
MJim

Reputation: 39

As far as I know, a List cannot be passed as an Intent extra.

I would suggest to pass the original String as was retrieved from the database, then parse it directly at the new activity (UserListActivity).

Upvotes: 1

santosh kumar
santosh kumar

Reputation: 2972

This is used to send using intent from one activity.

            Intent intent = getIntent();
            intent.putStringArrayListExtra("votedBy",new ArrayList<>(votedBy));

To receive this can be used;

ArrayList<String> votedByList= getIntent().getStringArrayListExtra("votedBy");

Upvotes: 9

Related Questions