android - 我可以使用 android.preference 包执行数据库特定操作吗?

标签 android database preference

我需要一个数据库,可以在其中存储数据并在需要时获取数据。 这可以通过 android.preference 包实现吗? 我不想使用 sqlite 数据库

问候

最佳答案

根据Shared Preferences | Android Developer Tutorial (Part 13)作者:Sai Geetha M N,

Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.

Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.

  1. 共享首选项:共享首选项可供应用程序外的所有组件( Activity 、服务等)使用。

  2. Activity 处理的首选项:这些首选项只能在 Activity 中使用,不能由应用程序的其他组件使用。

共享偏好设置:

共享首选项是在 Context 类的 getSharedPreferences 方法的帮助下进行管理的。首选项存储在默认文件 (1) 中,或者您可以指定用于引用首选项的文件名 (2)。

(1) 以下是指定文件名时获取实例的方式

public static final String PREF_FILE_NAME = "PrefFile";
   SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

MODE_PRIVATE 是首选项的操作模式。这是默认模式,意味着创建的文件将仅由调用应用程序访问。支持的其他两种模式是 MODE_WORLD_READABLEMODE_WORLD_WRITEABLE。在MODE_WORLD_READABLE中,其他应用程序可以读取创建的文件,但不能修改它。如果是 MODE_WORLD_WRITEABLE,其他应用程序也对所创建的文件具有写入权限。

(2) 推荐的方式是按默认方式使用,不指定文件名

SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context);

最后,一旦您拥有了首选项实例,您就可以通过以下方式从首选项中检索存储的值:

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

要在首选项文件中存储值,必须使用SharedPreference.Editor对象。 EditorSharedPreference 类的嵌套接口(interface)。

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

编辑器还支持 remove()clear() 等方法从文件中删除首选项值。

Activity 偏好:

共享首选项可供其他应用程序组件使用。但是,如果您不需要与其他组件共享首选项并希望拥有 Activity 私有(private)首选项。您可以借助 Activity 的 getPreferences() 方法来完成此操作。 getPreference 方法使用 getSharedPreferences() 方法,并将 Activity 类的名称作为首选项文件名。

以下是获取偏好设置的代码

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);

存储值的代码也与共享首选项的情况相同。

SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

您还可以使用其他方法,例如将 Activity 状态存储在数据库中。注意 Android 还包含一个名为 android.preference 的包。该包定义了用于实现应用程序首选项 UI 的类。

要查看更多示例,请查看 Android 的 Data Storage在开发者网站上发布。

关于android - 我可以使用 android.preference 包执行数据库特定操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3317812/

相关文章:

sql - 从配置表中检索值以用于查询

mysql - 如何使用 Java 在不同线程或不同进程上运行不同的 sql 查询

android - findViewById 在 PreferenceFragment 的 onViewCreated 中失败,Android

android - BluetoothAdapter.getDefaultAdapter();返回空

android - 向 RadioGroup 和 Radiobutton 添加过渡动画

MySQL:在数据库中查找活跃客户的查询

android - 如何在自定义 ArrayList 中保存 FCM 通知?

java - LocationUpdatesForegroundService 应用程序进程在关闭应用程序后仍在运行

java - 如何将数据从firebase数据库传递到短信?

python - Spyder-IDE 如何打开参数检查