In this tutorial, we explain how to use Shared Preferences in Android Studio to save, edit, and delete data in an XML file. This data can be accessed from any activity in your app or even other activities.
Quick Overview of Shared Preferences in Android Studio
Shared Preferences allow you to save data in an XML file that can be accessed from any activity in your application.
Creating a Shared Preferences Variable
First, create a variable of type SharedPreferences
:
javaCopiar códigoSharedPreferences preferences = getSharedPreferences("file_name", Context.MODE_PRIVATE);
file_name
: The ID or name of the file. If it exists, its data will be accessed; if not, the file will be created.Mode
: Specifies access permissions for the file. Common options include:MODE_PRIVATE
: Accessible only within the app.MODE_APPEND
: Appends new values to existing ones.MODE_WORLD_READABLE
: Allows other apps to read the file.MODE_WORLD_WRITABLE
: Allows other apps to write to the file.
Adding Data
To add values, use an Editor
object:
javaCopiar códigoSharedPreferences.Editor editor = preferences.edit();
editor.putString("id", "value");
editor.commit();
- Commands for adding data:
putString(ID, VALUE)
putInt(ID, VALUE)
putFloat(ID, VALUE)
putBoolean(ID, VALUE)
Use the same ID
or key to retrieve or edit the value later.
Saving Data:
commit()
: Saves data synchronously but may block the main thread.apply()
: Saves data asynchronously and is recommended for the main thread.
For official documentation, visit SharedPreferences.Editor.
Reading Data
To retrieve data, use the following:
javaCopiar códigoString value = preferences.getString("id", "Default");
- Commands for retrieving data:
getString(ID, DEFAULT)
getInt(ID, DEFAULT)
getFloat(ID, DEFAULT)
getBoolean(ID, DEFAULT)
If the ID
doesn’t exist, the default value is returned.
Checking Data Existence
To check if data exists:
javaCopiar códigoboolean containsData = preferences.contains("id");
Removing Data
To remove specific data:
javaCopiar códigoSharedPreferences.Editor editor = preferences.edit();
editor.remove("id");
editor.commit();
- Use
remove(ID)
to specify the key to be deleted.
Clearing All Data
To clear all Shared Preferences data:
javaCopiar códigoSharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
To clear the content but keep the file structure:
javaCopiar códigoSharedPreferences.Editor editor = preferences.edit();
editor.clear().commit();
For more Android tutorials, visit our blog for related topics.
Algunos temas que te pueden interesar: