In Android, SharedPrefences had always been a favorite to store small data but sometimes big too, in a JSON string format.
But firstly for our newbie friends let’s understand
What is shared preference?
Shared Preferences is how one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage
Where are SharedPreferences stored in Android?
Android stores Shared Preferences settings as an XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.
SharedPreferences Modes:
SharedPreferences have different modes, like-
public abstract SharedPreferences getSharedPreferences (String name, int mode)
This method takes two arguments, the first being the name of the SharedPreference(SP) file and the other is the context mode that we want to store our file in.
MODE_PUBLIC will make the file public which could be accessible by other applications on the device
MODE_PRIVATE keeps the files private and secures the user’s data.
MODE_APPEND is used while reading the data from the SP file.
Nested classes of Shared Preferences
- SharedPreferences.Editor: Interface used to write(edit) data in the SP file. Once editing has been done, one must commit() or apply() the changes made to the file.
- SharedPreferences.OnSharedPreferenceChangeListener(): Called when a shared preference is changed, added, or removed. This may be called even if a preference is set to its existing value. This callback will be run on your main thread.
Following are the methods of Shared Preferences
- contains(String key): This method is used to check whether the preferences contain a preference.
- edit(): This method is used to create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.
- getAll(): This method is used to retrieve all values from the preferences.
- getBoolean(String key, boolean devalue): This method is used to retrieve a boolean value from the preferences.
- get float(String key, float devalue): This method is used to retrieve a float value from the preferences.
- getInt(String key, int defValue): This method is used to retrieve an int value from the preferences.
- getLong(String key, long defValue): This method is used to retrieve a long value from the preferences.
- getString(String key, String defValue): This method is used to retrieve a String value from the preferences.
- getStringSet(String key, Set defValues): This method is used to retrieve a set of String values from the preferences.
- registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to registers a callback to be invoked when a change happens to a preference.
- unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to unregisters a previous callback.
In the simplest possible words If you wanna store anything using shared preferences the code is
firstly In MainActivity.kt create your ArrayList variable as global:
class MainActivity : AppCompatActivity() { private var values = ArrayList<String>() ... //the rest of your code
}val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
val editor = sharedPreferences.edit()
val gson = Gson()
val json = gson.toJson(values)
editor.putString("task list", json)
editor.apply()
and if you wanna fetch your data in shared preference the code is
val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
val gson = Gson()
val json = sharedPreferences.getString("task list", "")
val type = object: TypeToken<ArrayList<String>>() {
}.type
if(json == null)
values = ArrayList()
else
values = gson.fromJson(json, type)
Here’ some more things you can play with it
// parse Preference file
SharedPreferences preferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// get values from Map
preferences.getBoolean("key", defaultValue)
preferences.get..("key", defaultValue)
// you can get all Map but be careful you must not modify the collection returned by this
// method, or alter any of its contents.
Map<String, ?> all = preferences.getAll();
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
//add on Change Listener
preferences.registerOnSharedPreferenceChangeListener(mListener);
//remove on Change Listener
preferences.unregisterOnSharedPreferenceChangeListener(mListener);
// listener example
SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener
= new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
};
Now here a simple example of using it all
XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
>
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextName"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
<Button
android:id="@+id/buttonSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:text="Save" />
</RelativeLayout>
Java file
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String SHARED_PREF_NAME = "mysharedpref";
private static final String KEY_NAME = "keyname";
EditText editText;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editTextName);
textView = findViewById(R.id.textView);
findViewById(R.id.buttonSave).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveName();
displayName();
}
});
}
private void saveName() {
String name = editText.getText().toString();
if (name.isEmpty()) {
editText.setError("Name required");
editText.requestFocus();
return;
}
SharedPreferences sp = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(KEY_NAME, name);
editor.apply();
editText.setText("");
}
private void displayName() {
SharedPreferences sp = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);
String name = sp.getString(KEY_NAME, null);
if (name != null) {
textView.setText("Welcome " + name);
}
}
}
ta-da!! Hope that helped . Keep Coding!!