Save preferences with SharedPreferences
Updated in AndroidSharedPreferences is a simple way to store preference data in Android. SharedPreferences class provides an easy API to store and retrieve preferences from persistent storage, that is all the stored preferences are available even after the application or the device restarts. The nice thing about using SharedPreferences is that all of the work is handled by the SharedPreferences class itself, so using it requires minimal effort from the developer. Though on the downside, SharedPreferences supports only common data types (booleans, ints, floats, longs, strings and string sets.) which makes it ideal for storing preferences but won’t help you with more comples data types.
Basics
SharedPreferences class breaks down to two parts, the main class SharedPreferences and SharedPreferences.Editor. The main class handles preference reading and the Editor the writing.
To access a store preferences, you first need to get a SharedPreference instance. The simplest way is to use Context.getSharedPreferences. method which requires a name and the opening mode as parameters. The name just implies the file name that is used when the preferences are store to the device and the mode tells who can access the preferences file. More info about the available modes is available from the Context.getSharedPreferences Javadoc.
Once you have the SharedPreference instance you can read preference values by calling the appropriate method and giving a key for the preference. Writing the preferences is achieved by first calling edit() which returns an Editor instance and then putting the changes with the available putXXX() methods. One thing to note here is that the changes are not saved until commit them.
Committing changes can be done by two different ways. In the usual case calling Editor.apply() (API level 9 onwards) is enough. This schedules a write in a background thread. But in some cases you might need to immediately write the changes which can be done with Editor.commit() call. But do note that commit() call is synchronous so it needs to be executed from a background thread!
The example below show how you can read and write SharedPreferences.
Example
package com.tanelikorri.android.sharedpreferences;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class SharedPreferencesActivity extends AppCompatActivity {
private static final String KEY = "key";
private SharedPreferences preferences;
private EditText textField;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_preferences);
preferences = getSharedPreferences("preferences", Context.MODE_PRIVATE);
textField = findViewById(R.id.editText);
}
public void onWriteClick(View view) {
final Editor editor = preferences.edit();
editor.putString(KEY, textField.getText().toString());
switch (view.getId()) {
case R.id.write_button_async:
// Write asynchronously
editor.apply();
break;
case R.id.write_button_sync:
AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
@Override
public void run() {
// This call is synchronous and needs to be
// called from a background thread
editor.commit();
}
});
break;
}
Toast.makeText(this, R.string.write_message, Toast.LENGTH_LONG).show();
}
public void onReadClick(View view) {
String text = "Saved value is " + preferences.getString(KEY, null);
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
}
Screenshots
Source code
Source code for the whole example project is available here