Android の学習: SharedPreferences を使用してデータを保存する

Android の学習: SharedPreferences を使用してデータを保存する

SharedPreferences は、Android システムによって提供される軽量のデータ ストレージ メソッドであり、主にシステム ログイン用のユーザー名とパスワードなどの単純なデータを保存したり、ウィンドウ ステータスなどの一般的に使用されるシステム構成情報を保存したりするために使用されます。

SharedPreferences で保存および取得できるさまざまな基本データ型 (boolean、float、int、long、string) の永続的なキーと値のペアは、XML ファイルに保存されているキーと値のキーと値のペア データに基づいています。携帯電話のデータ /data/<パッケージ名>/shared_prefs ディレクトリ。

データ アクセスに SharedPreferences を使用する基本的な使用法は次のとおりです。

(1) SharedPreferencesオブジェクトを取得する

SharedPreferences オブジェクトは 2 つの方法で取得できます。

方法 1: Context オブジェクトの getSharedPreferences() メソッドを呼び出します。基本的なコードは次のとおりです。

getSharedPreferences(文字列名、int モード);

方法 2: Activity オブジェクトの getPreferences() メソッドを呼び出す 基本的なコードは次のとおりです。

getPreferences(int モード);

パラメータ名に応じて、対応するSharedPreferencesオブジェクトを取得することができ、nameは操作対象のXMLファイル名を示し、パラメータmodeには以下のオプション値がある。

Context.MODE_PRIVATE : SharedPreferences データはこのアプリケーションによってのみ読み書きできることを指定します。

Context.MODE_WORLD_WRITEABLE : SharedPreferences データが他のアプリケーションによって読み書きできることを指定します。

Context.MODE_WORLD_READABLE : SharedPreferences データを他のアプリケーションで読み取ることはできるが、書き込むことはできないことを指定します。

Context.MODE_MULTI_PROCESS : SDK 2.3 以降に追加されたオプションで、複数のプロセスが同じ SharedPreferences を読み書きするときに、ファイルが変更されているかどうかを確認します。

上記 2 つの方法の違いは次のとおりです。

最初のメソッド (getSharedPreferences()) で取得した SharedPreferences オブジェクトは、同じアプリケーション内の他のコンポーネントで共有できます。

2 番目のメソッド (getPreferences()) で取得した SharedPreferences オブジェクトは、このアクティビティでのみ使用できます

(2) SharedPreferencesに値を書き込む

まず、SharedPreferences.Editor を通じて Editor オブジェクトを取得します。

次に、特定のデータ型に対応するエディターの対応するメソッド (putBoolean() や putString() など) を使用して値を保存します。

最後に、エディターの commit() メソッドを呼び出して、値を書き込む操作を送信します。

さらに、エディターには、基本設定からキー値を削除するためによく使用される 2 つの方法もあります。

editor.remove(String key): 次回 commit() メソッドを通じて操作を送信するときに、キーに対応するキーと値のペアを削除するために使用されます。

editor.clear(): すべてのキーと値のペアを削除するために使用されます。

(3) SharedPreferencesからの値の読み書き

キー値を読み取るには、特定のデータ型に対応するエディターの対応するメソッド getXxxx() を使用します。

例: Android アプリケーションを開発し、SharedPreferences を使用して現在入力されているユーザー名とパスワードの情報を保存し、対応する機能ボタンをクリックして、すべてのキーと値のペアのデータの保存、抽出、および削除の基本機能を実現します。

XML レイアウト コードは次のとおりです。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context="zut.edu.e13_1.MainActivity">
​
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="利用SharedPreferences存储数据"
        android:textColor="@android:color/black"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="用户名:"
            android:textColor="@android:color/black"/>
        <EditText
            android:id="@+id/editText1"
            android:layout_width="120dp"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密码:"
            android:textColor="@android:color/black"/>
        <EditText
            android:id="@+id/editText2"
            android:layout_width="120dp"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="保存数据"/>
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="提取数据"/>
        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="移除键值对"/>
    </LinearLayout>
​
</LinearLayout>
​

MainActivity.java ファイル:

import android.content.Context;
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.Toast;
​
public class MainActivity extends AppCompatActivity {
​
    //定义各个控件
    private EditText username;
    private EditText password;
​
    //1.定义要保存SharedPreferences的XML文件
    String PREFS_NAME = "ex13_1.mySharedPreferences.unm_pwd";
​
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username = (EditText) findViewById(R.id.editText1);
        password = (EditText) findViewById(R.id.editText2);
        final Button button1 = (Button)findViewById(R.id.button1);
        final Button button2 = (Button)findViewById(R.id.button2);
        final Button button3 = (Button)findViewById(R.id.button3);
        //数据保存
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //2.定义一个只允许本程序访问的SharedPreFerences对象
                SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                //3.生成一个保存编辑变量
                SharedPreferences.Editor editor = settings.edit();
                //4.添加要保存的键值和真值
                editor.putString("username",username.getText().toString());
                editor.putString("password",password.getText().toString());
                //5.提交数据保存
                editor.commit();
                //清空输入
                username.setText("");
                password.setText("");
                Toast.makeText(MainActivity.this,"数据保存完成",Toast.LENGTH_LONG).show();
            }
        });
        //数据提取
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //提取保存的用户名,如果无则为空
                username.setText(getUserName());
                //提取保存的密码,如果无则为空
                password.setText(getPassWord());
                Toast.makeText(MainActivity.this,"数据提取完成",Toast.LENGTH_LONG).show();
            }
        });
        //移除所有键值对
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences settings = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
                //生成一个保存编辑对象
                SharedPreferences.Editor editor = settings.edit();
                //移除所有键值对
                editor.clear();
                editor.commit();
                username.setText("");
                password.setText("");
                Toast.makeText(MainActivity.this,"移除所有键值对成功",Toast.LENGTH_LONG).show();;
            }
        });
    }
    private String getUserName(){
​
        SharedPreferences settings = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
        //获取一个键值为"username"的值,若Preference中不存在,就用后面的值作为返回值
        String username = settings.getString("username","");
        return username;
​
    }
    private String getPassWord(){
​
        SharedPreferences settings = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
        //获取一个键值为"username"的值,若Preference中不存在,就用后面的值作为返回值
        String password = settings.getString("password","");
        return password;
​
    }
}
​

ただ実行してください。

おすすめ

転載: blog.csdn.net/weixin_52021660/article/details/124718871