Muzzammil Hussain
Muzzammil Hussain

Reputation: 298

Implementing a Favorite List in Android using SharedPreferences

I want to create a favorite list using SharedPreferences and I am trying to save some lists in it. There is an option for saving a String Set in SharedPreferences but the set does not keep Duplicate values. I want to store a list of duplicates with SharedPreferences. What should I do?

Also how can I convert an ArrayList<String> to HashSet<String> ?

Thanks for your answers!

Upvotes: 1

Views: 81

Answers (1)

Donald Wu
Donald Wu

Reputation: 718

  1. java convert list to set:

http://mkyong.com/java/how-to-convert-list-to-set-arraylist-to-hastset

List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

Set<String> set = new HashSet<String>(list);
  1. I suggest using intent and bundle to store the list

Activity to Activity

Pass list of objects from one activity to other activity in android

Store data:

// activity a
Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("test", arrayList);
intent.putExtras(bundle);
startActivity(intent);

Retrieve data:

// activity b
Bundle bundle = getIntent().getExtras();
Object test = bundle.getParcelable("test");

Activity to Fragment

Android passing ArrayList<Model> to Fragment from Activity

Store data:

// activity a
Bundle bundle = new Bundle();  
bundle.putParcelableArrayList("test", arraylist);
fragment.setArguments(bundle);

Retrieve data:

// fragment a
Bundle extras = getIntent().getExtras();  
List<String> arraylist = extras.getParcelableArrayList("test");

Upvotes: 1

Related Questions