AndroidのShared Preferencesの例に関するチュートリアル

このチュートリアルでは、AndroidアプリケーションでShared Preferencesを使用して、キーバリューペアの形式でデータを保存します。

Android Shared Preferencesの概要

Shared Preferencesは、アクティビティやアプリケーションが設定情報を保持するための機能であり、キーと値のペア形式のデータ(Mapと似ています)を利用します。これらの情報は、ユーザーがアプリケーションを終了しても永続的に保存されます。Androidは、Shared Preferencesの設定をXMLファイルとしてshared_prefsフォルダ内のDATA/data/{アプリケーションパッケージ}ディレクトリに保存します。DATAフォルダは、Environment.getDataDirectory()を呼び出すことで取得できます。ただし、SharedPreferencesはアプリケーションに特有のものであり、以下のいずれかの操作を実行するとデータが消失します。

  • on uninstalling the application
  • on clearing the application data (through Settings)

名前の通り、主な目的はユーザー指定の設定詳細を保存することであり、ユーザー固有の設定やアプリケーションにログインしたままにするためのものです。設定にアクセスするためには、選べるAPIは3つあります。

  • getPreferences() : used from within your Activity, to access activity-specific preferences
  • getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferences
  • getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework

このチュートリアルでは、getSharedPreferences()を使用します。このメソッドは以下のように定義されています。getSharedPreferences(String PREFS_NAME, int mode) PREFS_NAMEはファイルの名前です。modeは動作モードです。以下に適用可能な動作モードが示されています。

  • MODE_PRIVATE: the default mode, where the created file can only be accessed by the calling application
  • MODE_WORLD_READABLE: Creating world-readable files is very dangerous, and likely to cause security holes in applications
  • MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and likely to cause security holes in applications
  • MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loaded
  • MODE_APPEND: This will append the new preferences with the already existing preferences
  • MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write ahead logging by default

初期化

共有プリファレンスの編集と変更の保存には、エディターが必要です。以下のコードを使用することで、共有プリファレンスを取得できます。

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();

データを保存する

editor.commit()は、共有プリファレンスへの変更内容を保存するために使用されます。

editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
 
editor.commit(); // commit changes

データの取得

保存された設定からデータを取得するには、以下のようにgetString()を呼び出すことができます。

pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean

データを削除する

「remove(“key_name”)」は、その特定の値を削除するために使用されます。「clear()」は全てのデータを削除するために使用されます。

editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
 
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes

プロジェクトの構造

Androidの共有プリファレンスプロジェクトのコード

activity_main.xmlのレイアウトは、名前とメールアドレスを保存および表示する2つのEditTextビューで構成されています。3つのボタンは、それぞれMainActivityでonClickを実装しています。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="Save"
        android:text="Save" />

    <Button
        android:id="@+id/btnRetr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="Get"
        android:text="Retrieve" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/etEmail"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="clear"
        android:text="Clear" />

    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:layout_below="@+id/etName"
        android:layout_marginTop="20dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Name"
        android:inputType="text"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/etEmail"
        android:layout_alignStart="@+id/etEmail" />

</RelativeLayout>

MainActivity.javaファイルは、キーを使用してデータを保存し、取得するために使用されます。

package com.scdev.sharedpreferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    SharedPreferences sharedpreferences;
    TextView name;
    TextView email;
    public static final String mypreference = "mypref";
    public static final String Name = "nameKey";
    public static final String Email = "emailKey";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);
        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }

    }

    public void Save(View view) {
        String n = name.getText().toString();
        String e = email.getText().toString();
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(Name, n);
        editor.putString(Email, e);
        editor.commit();
    }

    public void clear(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        name.setText("");
        email.setText("");

    }

    public void Get(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

}

私の好みは、共有プリファレンスのキー-バリューペアが保存されているファイルの名前です。以下の画像は、プロジェクトの最終的な出力を示しています。このチュートリアルはこれにて終了です。下記のリンクからAndroid Shared Preferencesプロジェクトをダウンロードできます。

AndroidのShared Preferencesの例のプロジェクトをダウンロードしてください。

コメントを残す 0

Your email address will not be published. Required fields are marked *