AndroidのSharedPreferences(共有プリファレンス)の使い方をサンプルコード付きで解説
Androidアプリ開発では、SharedPreferences(共有プリファレンス)を使うことで、データを「キーと値」のペアとして手軽に保存・取得できます。本記事では、SharedPreferencesで利用できる主要なメソッドの概要と、実際に動作するサンプルアプリの作成手順を順を追って解説します。
SharedPreferencesの主なメソッド
edit() ― SharedPreferencesの値を編集するためのEditorオブジェクトを取得します。
commit() ― 編集内容をXMLファイルに同期的に保存(コミット)します。処理結果はboolean型の戻り値で確認できます。
apply() ― エディターでの変更をSharedPreferencesへ反映します。commit()と異なり非同期で処理されるため、UIスレッドをブロックしません。
remove(String key) ― 指定したキーと、そのキーに対応する値をSharedPreferencesから削除します。
putString() / putInt() など ― キーと値をSharedPreferencesのXMLファイルに書き込むために使用します。
SharedPreferencesの基本構文
final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);
上記のコードでは、「USER.xml」という名前のSharedPreferencesファイルを作成しています。第2引数にMODE_PRIVATEを指定しているため、このファイルはプライベートモードとなり、他のアプリからアクセスすることはできません。
それでは、AndroidアプリでSharedPreferencesを実際に使う方法を、ステップごとに見ていきましょう。
ステップ1:新規プロジェクトの作成
Android Studioを開き、[File] → [New Project] を選択して、必要事項を入力し、新しいプロジェクトを作成します。
ステップ2:レイアウトファイル(res/layout/activity_main.xml)の編集
以下のコードを activity_main.xml に追加します。
<?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "https://schemas.android.com/apk/res/android" xmlns:app = "https://schemas.android.com/apk/res-auto" xmlns:tools = "https://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>
このレイアウトには、名前(NAME)と電話番号(Phone Number)を入力するための2つのEditText、データを保存する「Save」ボタン、保存済みデータを読み込む「read」ボタン、そして結果を表示するTextViewが配置されています。「Save」ボタンをタップすると入力内容がSharedPreferencesに保存され、「read」ボタンをタップすると保存された値を読み出して画面に表示される仕組みです。
ステップ3:MainActivity.java の実装
以下のコードを 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();
}
});
}
}
このコードでは、まず「USER」という名前のSharedPreferencesインスタンスを取得しています。「Save」ボタンが押されると、入力フィールドの空チェックを行い、問題がなければ edit() でエディターを取得し、putString() で名前と電話番号を書き込んだ後、commit() で保存します。一方、「read」ボタンが押されると、getString() を使って保存済みの値を取り出し、TextViewに表示します。値が存在しない場合のデフォルト値も指定できる点がポイントです。
ステップ4:アプリの実行
manifest.xml に変更を加える必要はありません。AndroidスマートフォンをPCに接続し、Android Studioでプロジェクト内のアクティビティファイルを開いて、ツールバーの実行アイコン
をクリックしてください。実行デバイスとして自分のスマートフォンを選択すると、端末に以下のような初期画面が表示されます。

上の画面では、名前と電話番号を入力して「Save」ボタンをタップしたところです。これでデータがSharedPreferencesに保存されました。

続けて「read」ボタンをタップすると、先ほど保存した名前と電話番号がTextViewに表示されます。このようにSharedPreferencesを使えば、少量のデータならデータベースを用意しなくても、シンプルに永続化できるのが大きなメリットです。ユーザー設定やログイン状態の保持など、さまざまな場面で活用してみてください。
-
AndroidでSharedPreferences(共有プリファレンス)を取得してデータを保存・読み出す方法
はじめに Androidアプリ開発では、ユーザー名やメールアドレス、各種設定値など、少量のデータを端末内に保存しておきたい場面が多くあります。こうしたデータの永続化に最適なのがSharedPreferences(共有プリファレンス)です。本記事では、SharedPreferencesを使ってデータを保存・取得・クリアする方法を、サンプルコードとともにステップごとに解説します。 SharedPreferencesとは SharedPreferencesは、キーと値(Key-Valueペア)の形式でデータをXMLファイルとして保存する仕組みです。文字列・数値・真偽値などのプリミティブ型データを手軽
-
Phoenix OSでPCにAndroid環境を構築する方法|インストールから起動トラブルの解決まで
Phoenix OS(フェニックスOS)は、Androidをベースに開発されたPC向けオペレーティングシステムです。WindowsパソコンとMacの両方に対応しており、現行バージョンではAndroid 7.1をサポート。ノートPC、デスクトップPC、タブレットなど幅広いデバイスでの動作を想定して設計されています。書き込み可能なストレージであれば、USBフラッシュドライブに収めて持ち運び、別のPCから起動することも可能です。 最大のメリットは、すでにインストール済みのWindowsやmacOSにまったく影響を与えない点です。軽量なOSなので、パーティションのルートディレクトリを大きく占有しませ