AndroidのSharedPreferencesでapply()を使う方法を実例付きで解説
SharedPreferencesのapply()メソッドについて詳しく見ていく前に、まずAndroidにおけるSharedPreferences(共有プリファレンス)の基本をおさらいしておきましょう。SharedPreferencesを使うと、データを「キーと値」のペア形式で手軽に保存・取得できます。主なメソッドは以下の5つです。
edit() – SharedPreferencesの値を編集するためのEditorオブジェクトを取得します。
commit() – 変更内容をXMLファイルに同期的に書き込みます。処理結果をbooleanで返します。
apply() – Editorで行った変更内容をSharedPreferencesへ反映します。非同期で書き込まれるのが特徴です。
remove(String key) – 指定したキーと、それに対応する値をSharedPreferencesから削除します。
putString() / putInt() など – キーと値をSharedPreferencesのXMLファイルに書き込むためにEditorへ登録します。
SharedPreferencesの基本的な記述例は以下のとおりです。
final SharedPreferences sharedPreferences = getSharedPreferences("USER", MODE_PRIVATE);
この構文では「USER.xml」というSharedPreferencesファイルを作成しています。MODE_PRIVATE を指定しているため、このアプリ以外からはアクセスできないプライベートな設定ファイルになります。
apply()メソッドの役割
apply()は、変更内容を即座にメモリ上(インメモリ)のストレージへ書き込み、その後、永続ストレージへの書き込みをバックグラウンドで非同期に実行します。commit()のようにUIスレッドをブロックしないため、画面の動きを止めることなく安全に保存処理を行えるのが最大のメリットです。
以下では、名前と電話番号をSharedPreferencesに保存・読み出しするシンプルなサンプルを通して、apply()の具体的な使い方を紹介します。
ステップ1:プロジェクトの作成
Android Studioで新しいプロジェクトを作成します。「File」⇒「New Project」を選択し、必要事項を入力してプロジェクトを作成してください。
ステップ2:レイアウト(activity_main.xml)の作成
res/layout/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>
このXMLには、名前用と電話番号用の2つのEditTextを配置しています。ユーザーが「Save」ボタンをタップすると入力値がSharedPreferencesに保存され、「read」ボタンをタップすると保存された値を読み出してTextViewに表示される仕組みです。
ステップ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.apply();
}
}
});
}
}
ポイントは保存ボタンのクリック処理内にある editor.apply() の呼び出しです。ここでputString()で登録したキーと値が、非同期でSharedPreferencesに書き込まれます。
ステップ4:アプリの実行
manifest.xmlを変更する必要はありません。実際のAndroid端末をPCに接続し、Android Studioでプロジェクトのアクティビティファイルを開いて、ツールバーの「Run」アイコンをクリックしましょう。接続した端末を選択して実行すると、次のような画面が表示されます。

上の画面では、名前と電話番号を入力して「Save」ボタンをタップしたところです。

続いて「read」ボタンをタップすると、apply()で保存された名前と電話番号が読み出され、TextViewに表示されます。このようにapply()を使えば、UIスレッドを妨げることなく、手軽かつ効率的にデータを永続化できます。
-
AndroidでSharedPreferences(共有プリファレンス)を取得してデータを保存・読み出す方法
はじめに Androidアプリ開発では、ユーザー名やメールアドレス、各種設定値など、少量のデータを端末内に保存しておきたい場面が多くあります。こうしたデータの永続化に最適なのがSharedPreferences(共有プリファレンス)です。本記事では、SharedPreferencesを使ってデータを保存・取得・クリアする方法を、サンプルコードとともにステップごとに解説します。 SharedPreferencesとは SharedPreferencesは、キーと値(Key-Valueペア)の形式でデータをXMLファイルとして保存する仕組みです。文字列・数値・真偽値などのプリミティブ型データを手軽
-
AndroidアプリでSQLiteデータベースを使う方法を徹底解説【CRUD実装の手順】
この記事では、AndroidアプリケーションでSQLiteデータベースを活用する方法を、実際のコード例とともに段階的に解説します。データの追加・一覧表示・更新・削除(CRUD操作)をすべて網羅したサンプルアプリを作成しながら、SQLiteの基本的な使い方をマスターしましょう。全体の流れ本チュートリアルでは、サッカー選手の名前と所属国を管理するシンプルなアプリを題材にします。主な構成要素は以下の通りです。DatabaseHelper:SQLiteOpenHelperを継承し、データベースの作成・管理を行うクラスDataBaseManager:データの挿入・取得・更新・削除を担当するクラスMain