Bart Simons

Bart Simons


Thoughts, stories and ideas.

Bart Simons
Author

Share


Tags


Twitter


Android - Save and load data using SharedPreferences

Want to store data inside your Android app? No problem! The Android SDK and Java has got you covered. One of the many options to save and load data is to use Sh…

Bart SimonsBart Simons

Want to store data inside your Android app? No problem! The Android SDK and Java has got you covered. One of the many options to save and load data is to use SharedPreferences. It's also good to know that it is one of the easiest (and in my opinion most integrated) methods to implement! Please mind that SharedPreferences are probably not suitable for intensive, repetitive and/or low-latency I/O usage (SQL storage might be better for those tasks).

How do I use it?

Simple! I have made two working code samples for you.

Saving stuff
SharedPreferences sharedPref = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();

editor.putString("username", "randomusername4238");
editor.putString("passwordhash", "somerandompasswordhash");

editor.apply();
Loading stuff
SharedPreferences sharedPref = getSharedPreferences("preferences", Context.MODE_PRIVATE);

String saved_username = sharedPref.getString("username", "");
String saved_passwordhash = sharedPref.getString("passwordhash", "");

That should get the job done! As you can see, this method of saving data is great for saving and loading important data for your app. Enjoy!

Bart Simons
Author

Bart Simons

Comments