📜  Android 中的共享首选项示例

📅  最后修改于: 2022-05-13 01:54:58.444000             🧑  作者: Mango

Android 中的共享首选项示例

Android为其用户提供的最有趣的数据存储选项之一是Shared PreferencesShared Preferences是一种可以将少量原始数据作为键/值对存储和检索到设备存储文件中的一种方式,例如 String、int、float、Boolean,它们在应用程序内的 XML 文件中构成您的首选项在设备存储上。 Shared Preferences可以被认为是一个字典或一个键/值对。例如,您可能有一个键是“用户名”,而对于值,您可以存储用户的用户名。然后你可以通过它的键(这里是用户名)来检索它。您可以拥有一个简单的共享首选项 API,您可以使用它来存储首选项并在需要时将其拉回。 Shared Preferences 类提供用于读取、写入和管理此数据的 API。下面给出了一个示例 GIF,以了解我们将在本文中做什么。请注意,我们将使用Java语言来实现这个项目。

Android 中的共享首选项示例

共享偏好适用于不同的情况。例如,当需要保存用户的设置或存储可用于应用程序内不同活动的数据时。如您所知,onPause() 总是会在您的 Activity 被置于后台或被销毁之前被调用,因此为了持久保存数据,最好将其保存在 onPause() 中,可以在 onCreate() 中恢复活动。使用共享首选项存储的数据在应用程序范围内保持私有。但是,共享首选项不同于该活动的实例状态。

Shared Preferences 与 Saved Instance State 有何不同?

Shared Preferences

Saved Instance State

Persist Data across user sessions, even if the app is killed and restarted, or the device is rebootedPreserves state data across activity instances in the same user session.
Data that should be remembered across sessions, such as the user’s preferred settings or their game score.Data that should not be remembered across sessions, such as the currently selected tab or current state of activity.
A common use is to store user preferencesA common use is to recreate the state after the device has been rotated

如何创建共享首选项?

我们需要做的第一件事是为每个应用程序创建一个共享首选项文件。因此,使用您的应用程序的包名称命名它 - 独特且易于与应用程序关联。如果要获取值,请调用getSharedPreferences()方法。 Shared Preferences 提供了存储数据的模式(私有模式和公共模式)。这是为了向后兼容 - 仅使用MODE_PRIVATE是安全的。

共享首选项的嵌套类

  1. SharedPreferences.Editor :用于在 SP 文件中写入(编辑)数据的接口。编辑完成后,必须commit()apply()对文件所做的更改。
  2. SharedPreferences.OnSharedPreferenceChangeListener() :在更改、添加或删除共享首选项时调用。即使将首选项设置为其现有值,也可能会调用它。此回调将在您的主线程上运行。

以下是共享首选项的方法

  1. contains(String key) :此方法用于检查首选项是否包含首选项。
  2. edit() :此方法用于为这些首选项创建一个新的编辑器,通过它您可以修改首选项中的数据并将这些更改原子地提交回 SharedPreferences 对象。
  3. getAll() :此方法用于从首选项中检索所有值。
  4. getBoolean(String key, boolean defValue) :此方法用于从首选项中检索布尔值。
  5. getFloat(String key, float defValue) :此方法用于从首选项中检索浮点值。
  6. getInt(String key, int defValue) :此方法用于从首选项中检索 int 值。
  7. getLong(String key, long defValue) :此方法用于从首选项中检索长值。
  8. getString(String key, String defValue) :此方法用于从首选项中检索字符串值。
  9. getStringSet(String key, Set defValues) :此方法用于从首选项中检索一组字符串值。
  10. registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener) :此方法用于注册要在首选项发生更改时调用的回调。
  11. unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener) :此方法用于取消注册先前的回调。

以下是有关如何在共享首选项中写入数据的示例字节代码:

Java
// 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();


Java
// 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);
 
// We can then use the data
name.setText(s1);
age.setText(String.valueOf(a));


XML


 
    
 
    
    
 
    
    
 


Java
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
 
public class MainActivity extends AppCompatActivity {
 
    private EditText name, age;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = findViewById(R.id.edit1);
        age = findViewById(R.id.edit2);
    }
 
    // Fetch the stored data in onResume()
    // Because this is what will be called
    // when the app opens again
    @Override
    protected void onResume() {
        super.onResume();
 
        // Fetching the stored data
        // from the SharedPreference
        SharedPreferences sh = getSharedPreferences("MySharedPref", MODE_PRIVATE);
 
        String s1 = sh.getString("name", "");
        int a = sh.getInt("age", 0);
 
        // Setting the fetched data
        // in the EditTexts
        name.setText(s1);
        age.setText(String.valueOf(a));
    }
 
    // Store the data in the SharedPreference
    // in the onPause() method
    // When the user closes the application
    // onPause() will be called
    // and data will be stored
    @Override
    protected void onPause() {
        super.onPause();
 
        // Creating a shared pref object
        // with a file name "MySharedPref"
        // in private mode
        SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref", MODE_PRIVATE);
        SharedPreferences.Editor myEdit = sharedPreferences.edit();
 
        // write all the data entered by the user in SharedPreference and apply
        myEdit.putString("name", name.getText().toString());
        myEdit.putInt("age", Integer.parseInt(age.getText().toString()));
        myEdit.apply();
    }
}


以下是有关如何在共享首选项中读取数据的示例字节代码:

Java

// 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);
 
// We can then use the data
name.setText(s1);
age.setText(String.valueOf(a));

演示在 Android 中使用共享首选项的示例

下面是共享首选项的小演示。在这个特定的演示中,有两个 EditText,它们保存并保留之前在其中输入的数据。这种类型的功能可以在带有表单的应用程序中看到。使用共享首选项,用户不必一次又一次地填写详细信息。在activity_main.xml文件中调用以下代码来实现 UI:

XML



 
    
 
    
    
 
    
    
 

输出界面:

使用 MainActivity。 Java文件处理两个EditText来保存用户在SharedPreferences里面输入的数据。下面是MainActivity 的代码。 Java文件。代码中添加了注释以更详细地理解代码。

Java

import androidx.appcompat.app.AppCompatActivity;
 
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
 
public class MainActivity extends AppCompatActivity {
 
    private EditText name, age;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = findViewById(R.id.edit1);
        age = findViewById(R.id.edit2);
    }
 
    // Fetch the stored data in onResume()
    // Because this is what will be called
    // when the app opens again
    @Override
    protected void onResume() {
        super.onResume();
 
        // Fetching the stored data
        // from the SharedPreference
        SharedPreferences sh = getSharedPreferences("MySharedPref", MODE_PRIVATE);
 
        String s1 = sh.getString("name", "");
        int a = sh.getInt("age", 0);
 
        // Setting the fetched data
        // in the EditTexts
        name.setText(s1);
        age.setText(String.valueOf(a));
    }
 
    // Store the data in the SharedPreference
    // in the onPause() method
    // When the user closes the application
    // onPause() will be called
    // and data will be stored
    @Override
    protected void onPause() {
        super.onPause();
 
        // Creating a shared pref object
        // with a file name "MySharedPref"
        // in private mode
        SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref", MODE_PRIVATE);
        SharedPreferences.Editor myEdit = sharedPreferences.edit();
 
        // write all the data entered by the user in SharedPreference and apply
        myEdit.putString("name", name.getText().toString());
        myEdit.putInt("age", Integer.parseInt(age.getText().toString()));
        myEdit.apply();
    }
}

输出:

参考:共享偏好 |安卓