James James - 5 months ago 7
Java Question

What is the best way to pass a set to another activity. Java Android SDK

I have a set which contains a list of strings:

public Set<String> favs = new HashSet<>();


However when I start another activity 'Favorites' I want to pass this list over to my 'Favorties' class, currently I have:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();


if (id == R.id.action_settings) {
return true;
} else if (id == R.id.exit_the_app) {
finish();
return true;
} else if (id == R.id.favorites) {
Intent startfavs = (new Intent(Insulter.this, Favorites.class));
startActivity(startfavs);
return true;
}
return super.onOptionsItemSelected(item);
}


I want to pass this set in 'favorites' and eventually display it in a list view after changing it to a list. What would be the best way of going about doing this?

(Note: My second activity is all set up in the manifold and runs fine)

Answer

In your First Activity called Insulter,add this,

Intent startfavs = (new Intent(Insulter.this, Favorites.class));
String[] objects = new String[set.size()];
set.toArray(objects);
final ArrayList<String> list = new ArrayList<String>(Arrays.asList(objects));
startfavs.putStringArrayListExtra("favs",list);
startActivity(startfavs);

In your second Activity called Favorites,to get the param,

ArrayList<String> favs = getIntent().getStringArrayListExtra("favs");
Comments