如何用示例解釋 Android Shared Preferences?


使用 Shared Preferences,我們可以以鍵值對的形式儲存或檢索值。Shared Preferences 提供了五種不同的方法,如下所示:

  • Edit() - 用於編輯 Shared Preferences 的值。

  • commit() - 用於將 Shared Preferences 的值提交到 xml 檔案中。

  • apply() - 用於將編輯器中的更改提交回 Shared Preferences。

  • remove(String key) - 用於使用鍵從 Shared Preferences 中刪除鍵值對。

  • Put() - 用於將鍵值對放入 Shared Preferences xml 檔案中。

Shared Preferences 的示例語法如下所示:

final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);

在上述語法中,我們建立了一個名為 USER.xml 的 Shared Preferences 檔案,並且它是私有模式,這意味著其他應用程式無法訪問此 Shared Preferences。

以下示例演示瞭如何在 Android 中使用 Shared Preferences。

步驟 1 - 在 Android Studio 中建立一個新專案,轉到 File ⇒ New Project 並填寫所有必要資訊以建立新專案。

步驟 2 - 將以下程式碼新增到 res/layout/activity_main.xml 中。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
   xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical"
   tools:context = ".MainActivity"
   tools:layout_editor_absoluteY = "81dp">
   <EditText android:id = "@+id/name"
      android:layout_width = "match_parent"
      android:layout_height = "60dp"
      android:layout_marginTop = "8dp"
      android:autofillHints = ""
      android:hint = "NAME" app:layout_constraintTop_toTopOf = "parent"
      tools:layout_editor_absoluteX = "0dp" />
   <EditText android:id = "@+id/address" android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:layout_marginTop = "84dp"
      android:hint = "Phone Number"
      android:importantForAutofill = "no"
      android:inputType = ""
      app:layout_constraintTop_toTopOf = "@+id/name"
      tools:layout_editor_absoluteX = "16dp"
      tools:targetApi = "o" />
   <Button
      android:id = "@+id/button"
      android:layout_width = "108dp"
      android:layout_height = "wrap_content"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "120dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:gravity = "center_horizontal"
      android:text = "Save"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintHorizontal_bias = "0.503"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toTopOf = "@+id/address" />
   <Button
      android:id = "@+id/read"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "88dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:gravity = "center_horizontal"
      android:text = "read"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toBottomOf = "@+id/button" />
   <TextView
      android:id = "@+id/result"
      android:layout_width = "wrap_content"
      android:layout_height = "0dp"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "184dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:text = "result"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toBottomOf = "@+id/button" />
</android.support.constraint.ConstraintLayout>

在上面的 xml 中,它包含兩個用於姓名和地址的 EditText,當用戶點選“儲存”按鈕時,它將把值儲存到 Shared Preferences 中,當用戶點選“讀取”按鈕時,它將從 Shared Preferences 中讀取值。

步驟 3 - 將以下程式碼新增到 src/MainActivity.java

package com.example.andy.myapplication;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);
      final EditText name = findViewById(R.id.name);
      final EditText address = findViewById(R.id.address);
      final TextView result = findViewById(R.id.result);
      Button save = findViewById(R.id.button);
      Button read = findViewById(R.id.read);
      read.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            result.setText("Name is "+sharedPreferences.getString("Name","No name")+" Address "+ sharedPreferences.getString("Address","No Address"));
        }
      });
      save.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if(name.getText().toString().isEmpty() && address.getText().toString().isEmpty()) {
               Toast.makeText(MainActivity.this,"Plz Enter all the data",Toast.LENGTH_LONG).show();
            } else {
               String nameData = name.getText().toString().trim();
               String addressData = address.getText().toString().trim();
               SharedPreferences.Editor editor = sharedPreferences.edit();
               editor.putString("Name",nameData);
               editor.putString("Address",addressData);
               editor.commit();
            }
         }
      });
   }
}

步驟 4 - 無需更改 manifest.xml 讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟專案中的一個 Activity 檔案,然後點選工具欄中的執行圖示 播放圖示 。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

在上面的示例中,我們添加了姓名和地址,並點選了“儲存”按鈕。

在上面的示例中,我們點選了“讀取”按鈕。它將文字附加到 TextView 中。

更新於: 2020-06-27

326 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告