KotlinでAndroidのSharedPreferences(共有プリファレンス)を実装する方法を徹底解説
SharedPreferencesとは?
SharedPreferencesは、Androidアプリにおいて少量のデータを「キーと値」のペア形式で永続的に保存するための軽量なストレージ仕組みです。ユーザー名やパスワードといったログイン情報、アプリの設定値の保持などに広く活用されています。
本記事では、Kotlinを使ってSharedPreferencesでログイン情報を保存・復元するサンプルアプリを、ステップごとにわかりやすく解説します。
ステップ1:新規プロジェクトを作成する
まず、Android Studioで新しいプロジェクトを作成しましょう。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。
ステップ2:レイアウトファイル(activity_main.xml)を編集する
次に、res/layout/activity_main.xml に以下のコードを追加します。このレイアウトには、ユーザー名とパスワードの入力欄(EditText)、ログインボタン(Button)、そして「認証情報を記憶する」チェックボックス(CheckBox)を配置しています。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <EditText android:id="@+id/etName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView" android:layout_centerInParent="true" android:layout_marginTop="75dp" android:ems="10" android:hint="Enter Name" /> <EditText android:id="@+id/etPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/etName" android:layout_centerHorizontal="true" android:ems="10" android:hint="Enter Password" /> <Button android:id="@+id/btnLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/etPassword" android:layout_alignStart="@id/etPassword" android:layout_marginTop="10dp" android:text="Login" /> <CheckBox android:id="@+id/checkBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/btnLogin" android:layout_alignStart="@id/btnLogin" android:layout_marginTop="10dp" android:text="Remember my credentials" /> </RelativeLayout>
ステップ3:MainActivity.kt を実装する
続いて、src/MainActivity.kt に以下のコードを追加します。
このコードのポイントは以下の通りです。
- チェックボックスがオンの状態でログインボタンを押すと、入力されたユーザー名とパスワードがSharedPreferencesに保存されます。
- チェックボックスがオフの場合は、保存されているデータがクリアされます。
- アプリ起動時には
checkSharedPreference()メソッドが呼ばれ、保存済みの値を読み込んで各ビューに自動反映します。
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var sharedPreferences: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
private lateinit var name: EditText
private lateinit var password: EditText
private lateinit var button: Button
private lateinit var checkBox: CheckBox
private lateinit var strName: String
private lateinit var strPassword: String
private lateinit var strCheckBox: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
name = findViewById(R.id.etName)
password = findViewById(R.id.etPassword)
button = findViewById(R.id.btnLogin)
checkBox = findViewById(R.id.checkBox)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
editor = sharedPreferences.edit()
checkSharedPreference()
button.setOnClickListener {
if (checkBox.isChecked) {
editor.putString(getString(R.string.checkBox), "True")
editor.apply()
strName = name.text.toString()
editor.putString(getString(R.string.name), strName)
editor.commit()
strPassword = password.text.toString()
editor.putString(getString(R.string.password), strPassword)
editor.commit()
} else {
editor.putString(getString(R.string.checkBox), "False")
editor.commit()
editor.putString(getString(R.string.name), "")
editor.commit()
editor.putString(getString(R.string.password), "")
editor.commit()
}
}
}
private fun checkSharedPreference() {
strCheckBox = sharedPreferences.getString(getString(R.string.checkBox), "False").toString()
strName = sharedPreferences.getString(getString(R.string.name), "").toString()
strPassword = sharedPreferences.getString(getString(R.string.password), "").toString()
name.setText(strName)
password.setText(strPassword)
checkBox.isChecked = strCheckBox == "True"
}
}ステップ4:AndroidManifest.xml を確認する
最後に、androidManifest.xml に以下のコードを追加します。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
アプリを実行してみよう
それでは、作成したアプリを実際に実行してみましょう。ここでは、実機のAndroidスマートフォンをパソコンに接続していることを前提としています。
Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーにある実行アイコンをクリックします。表示される選択肢から接続済みのモバイルデバイスを選択すると、端末の画面にアプリの初期画面が表示されます。

-
【Android】SharedPreferencesの使い方をサンプルコード付きでわかりやすく解説
AndroidのSharedPreferencesとは? SharedPreferencesは、Androidアプリで少量のデータを「キーと値(Key-Value)」のペアとして永続的に保存するための標準的な仕組みです。保存されたデータはアプリ内部のファイルに書き込まれるため、アプリを終了して再起動した後でも値が保持されます。ユーザー名やパスワード、各種設定情報の保存などによく利用されます。 この記事では、ログイン画面を例に「名前・パスワード・チェックボックスの状態を保存し、次回起動時に復元する」サンプルを通じて、SharedPreferencesの基本的な使い方をステップごとに解説します。
-
【Android】ScrollViewでスクロールバーを実装・カスタマイズする方法
はじめにこの記事では、AndroidアプリでScrollView(スクロールビュー)を使用して、画面の内容が収まらない場合でも上下にスクロールできるようにする方法を、実際のコード例とともにステップ形式で解説します。あわせて、android:scrollbarSize属性を使ってスクロールバーの太さを変更する方法も紹介します。ステップ1:新規プロジェクトを作成するまず、Android Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な設定項目をすべて入力し、プロジェクトのセットアップを完了させてください。ステップ2:acti