Tutorials  /  Security

Saving User Settings in Android: Insights into Shared Preferences

Ccentron Redaktion · September 2024 ·4 min read ·Security, Tutorial

Discover in our latest blog post how to efficiently save and restore user settings in Android applications using Shared Preferences. From initialization to retrieving saved data - we guide you through the process and show you how easy it is to manage data in the form of key-value pairs.

Overview of Android Shared Preferences

Shared Preferences allows activities and applications to store settings in the form of key-value pairs similar to a map, which persist even when the user closes the application. Android stores the Shared Preferences settings as an XML file in the shared_prefs folder under the DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory(). SharedPreferences are application-specific, meaning the data will be lost if any of the following actions are taken:

  • When uninstalling the application
  • When deleting application data (via settings)

As the name suggests, the main purpose is to store user-specific configuration details, such as user preferences to keep the user logged in to the application. To access the settings, we have three APIs to choose from:

  • getPreferences(): used within your activity to retrieve activity-specific settings
  • getSharedPreferences(): used within your activity (or other application contexts) to retrieve application-wide settings
  • getDefaultSharedPreferences(): used on the PreferenceManager to retrieve the shared preferences that work in line with the entire Android preference framework

In this tutorial, we will be using getSharedPreferences(). The method is defined as follows: getSharedPreferences(String PREFS_NAME, int mode) PREFS_NAME is the name of the file. Mode is the operating mode. The following operating modes are applicable:

  • MODE_PRIVATE: the default mode in which the created file is accessible only by the calling application
  • MODE_WORLD_READABLE: Creating world-readable files is very dangerous and can cause security holes in applications
  • MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous and can cause security holes in applications
  • MODE_MULTI_PROCESS: This method checks for changes to the settings even if the shared preference instance has already been loaded
  • MODE_APPEND: This appends new settings to the existing ones
  • MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When set, enables write-ahead logging by default
SEC

Matching infrastructure at centron

Hardening does not stop at the server: cloud firewalls filter traffic before it reaches the VM – centrally managed, no per-rule surcharge. Explore cloud firewalls →

Initialization

We need an editor to edit and save changes in the Shared Preferences. The following code can be used to obtain the Shared Preferences:

Code
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();

Saving Data

editor.commit() is used to save changes in the Shared Preferences. An example of saving data:

Code
editor.putBoolean("key_name", true); // Saving Boolean - true/false
editor.putString("key_name", "String value"); // Saving String
editor.putInt("key_name", 123); // Saving Integer
editor.putFloat("key_name", 3.14f); // Saving Float
editor.putLong("key_name", 123456789L); // Saving Long

editor.commit(); // Confirming changes

Retrieving Data

Data can be retrieved from the saved settings using getString() as follows:

Code
pref.getString("key_name", null); // Retrieving String
pref.getInt("key_name", -1); // Retrieving Integer
pref.getFloat("key_name", -1.0f); // Retrieving Float
pref.getLong("key_name", -1L); // Retrieving Long
pref.getBoolean("key_name", false); // Retrieving Boolean

Deleting Data

remove("key_name") is used to delete a specific value. clear() is used to remove all data.

Code
editor.remove("name"); // will delete the key "name"
editor.remove("email"); // will delete the key "email"

editor.commit(); // Confirming changes
editor.clear();
editor.commit(); // Confirming changes

Project Structure

The project structure includes the activity (MainActivity.java) and the layout (activity_main.xml). The MainActivity.java file is used to save and retrieve data, while the activity_main.xml layout contains two EditText views to save and display names and emails. With this knowledge, you can save and restore user settings and other data in your Android application. Happy coding!

That's it for this tutorial. Thank you for reading!

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Security
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren