Home >Java >javaTutorial >How to Access SharedPreferences from an Android PreferenceActivity?

How to Access SharedPreferences from an Android PreferenceActivity?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 11:55:18152browse

How to Access SharedPreferences from an Android PreferenceActivity?

How to Access SharedPreferences from a PreferenceActivity?

When utilizing a PreferenceActivity to manage application settings, it's common to inflate settings from an XML file. However, accessing the name of the SharedPreference file used by the PreferenceActivity from another Activity can be challenging.

Solution:

To obtain the SharedPreferences instance from a PreferenceActivity:

import android.preference.PreferenceManager;

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

Use the retrieved SharedPreferences object to access the stored values using methods like:

prefs.getBoolean("keystring", true);

Understanding SharedPreferences and Activity Preferences:

Android provides two types of preferences: SharedPreferences and Activity Preferences.

SharedPreferences:

  • Can be used by all application components (activities, services, etc.)
  • Can be named (specific file name) or unnamed (default file)
  • Recommended for preferences that need to be shared across the application

Activity Preferences:

  • Used only within a specific activity
  • Not accessible by other application components
  • Useful for preferences specific to an activity

Storing and Retrieving Preferences:

SharedPreferences can be stored and retrieved using the following methods:

Store:

SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", value);
editor.commit();

Retrieve:

int storedInt = preferences.getInt("storedInt", 0);

Other Resources:

  • Android Developer Tutorial on Shared Preferences: https://developer.android.com/training/basics/data-storage/shared-preferences
  • Android Data Storage: https://developer.android.com/guide/topics/data/data-storage

The above is the detailed content of How to Access SharedPreferences from an Android PreferenceActivity?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn