Android共享首选项

2022-11-06  本文已影响0人  蜗牛是不是牛

什么是共享首选项?

它是数据持久性的概念之一,就像数据库一样,SharedPreference也用于存储数据,但不是存储大数据。

SharedPreferences适用于不同的情况,比如我们想存储用户的设置。例如;用户已选择暗主题,因此当用户下次打开应用程序时,它应该向他们显示暗主题。

其他情况是,我们希望在应用程序的不同活动中使用该数据块。

在共享首选项中写入数据

// Storing data into SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref",MODE_PRIVATE);

// Creating an Editor object to edit(write to the file)
SharedPreferences.Editor myEdit = sharedPreferences.edit();

// Storing the key and its value as the data fetched from edittext
myEdit.putString("name", name.getText().toString());
myEdit.putInt("age", Integer.parseInt(age.getText().toString()));

// Once the changes have been made,
// we need to commit to apply those changes made,
// otherwise, it will throw an error
myEdit.commit();

为了创建SharedPreference,使用了“getSharedReferences()”方法。此方法包含2个参数、SharedPreference的名称和要设置的模式。

共有3种模式:

模式_PUBLIC:使用此模式时,文件是公共的,可以被其他应用程序使用。

模式-私有:你的文件在这里处于私有模式,其他应用无法访问。

MODE_APPEND:当您想从共享首选项读取数据时使用它。

SharedPreferences.Editor myEdit = sharedPreferences.edit();

// Storing the key and its value as the data fetched from edittext
myEdit.putString("name", name.getText().toString());
myEdit.putInt("age", Integer.parseInt(age.getText().toString()));

因为我们要将数据添加到SP中,所以必须创建编辑器。您可以将数据放入编辑器,如上图所示。

输入所有数据后,必须提交SP。为了保存数据。

从共享首选项读取数据

// Retrieving the value using its keys the file name
// must be same in both saving and retrieving the data
SharedPreferences sh = getSharedPreferences("MySharedPref", MODE_APPEND);

// The value will be default as empty string because for
// the very first time when the app is opened, there is nothing to show
String s1 = sh.getString("name", "");
int a = sh.getInt("age", 0);

同样,在这里创建共享首选项。但是用了附加模式。因为我们想读取数据。

使用sh.getString、sh.getInt各自的方法来获取值。

这些方法中的第一个参数是我们在创建这些数据时提供的“键”,其他参数是默认值。如果SP无法检索具有该ID的数据,它将返回默认值。

上一篇下一篇

猜你喜欢

热点阅读