user4257999
user4257999

Reputation:

How to simplify sharedpreferences in android?

Is there a way to simplify the following code, so that there only needs to be used 1 settings/editor?

SharedPreferences settings = getSharedPreferences("gebruikersnaam", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("gebruikersnaam", givenUsername);
editor.apply();
SharedPreferences settings2 = getSharedPreferences("wachtwoord", 0);
SharedPreferences.Editor editor2 = settings2.edit();
editor2.putString("wachtwoord", givenPassword);
editor2.apply();
SharedPreferences settings3 = getSharedPreferences("url", 0);
SharedPreferences.Editor editor3 = settings3.edit();
editor3.putString("url", givenURL);
editor3.apply(); 

Upvotes: 1

Views: 86

Answers (2)

kostek
kostek

Reputation: 801

Checkout this great library.

https://github.com/mg6maciej/hrisey

https://github.com/mg6maciej/hrisey/wiki/Preferences

It can save you a lot of boilerplate code, not only for shared preferences.

It's Android specific version of Lombok.

https://projectlombok.org/

Upvotes: 1

mattfred
mattfred

Reputation: 2759

Why don't you just save all of your strings in one sharedPreference

SharedPreferences settings = getSharedPreferences("myApp", 0);
settings.edit().putString("gebruikersnaam", givenUsername).apply();
settings.edit().putString("wachtwoord", givenPassword).apply();
settings.edit().putString("url", givenURL).apply();

Upvotes: 4

Related Questions