Skip to content

Instantly share code, notes, and snippets.

@dynoChris
Last active November 24, 2020 08:07
Show Gist options
  • Save dynoChris/d4319cb81c55c3554dfa35c40b7d9384 to your computer and use it in GitHub Desktop.
Save dynoChris/d4319cb81c55c3554dfa35c40b7d9384 to your computer and use it in GitHub Desktop.
putStringSet() Issue in Shared Preferences SOLVED
//What the problem?
//If you will put the String Set to Shared Preferences with a putStringSet() method it will be put,
//but for second iteration and more it is work uncorrectly. Let's see
public class MainActivity extends AppCompatActivity {
private Button mFirstButton, mSecondButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
mFirstButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveFirst(this);
}
});
mSecondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveSecond(this);
}
});
}
private void initViews() {
mFirstButton = findViewById(R.id.first_btn);
mSecondButton = findViewById(R.id.second_btn);
}
private void saveFirst(Context context) {
Set<String> stringSet = new LinkedHashSet<>();
stringSet.add("hello1");
stringSet.add("hello2");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("set1", stringSet);
editor.apply();
}
private void saveSecond(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Set<String> stringSet = sharedPreferences.getStringSet("set1", new LinkedHashSet<>());
stringSet.add("hello3");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("set1", stringSet);
editor.apply();
}
}
<!--Shared Prefences after clicking to First then Second button-->
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<set name="set1">
<string>hello1</string>
<string>hello2</string>
</set>
</map>
//As you can see, <string>hello3</string> record is absent. So, what to do?
//SOLUTION:
//replace saveSecond to
private void saveSecond(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Set<String> stringSet = sharedPreferences.getStringSet("set1", new LinkedHashSet<>());
Set<String> newStringSet = new LinkedHashSet<>(stringSet); //crutch. if you don't create a new instance of set it will not work :(
newStringSet.add("hello3");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("set1", newStringSet);
editor.apply();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment