androidはAPIレベル1以降、Key-Valueペアを保存するためのAPIが用意されています。このAPIは、あなたがandroidに慣れていない場合、またはsharedpreferencesの使い方を学んでいる場合です。
このチュートリアルでは、sharedpreferencesを使ってデータを保存したり取り出したりする例をいくつか見ていきます。主に、プリミティブなdtaa型をsharedpreferencesに格納する予定です。
例 1: Kotlin Android - SharedPreferences の例
これはKotlinで書かれた簡単なsharedpreferencesの例です。
Demo
作成されたもののデモを紹介します。
ステップ1:依存関係
特別な依存関係やサードパーティーの依存関係は必要ありません。
ステップ2: レイアウトの設計
以下のように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="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:padding="10dp"
android:textColor="#101010"
android:textSize="25sp"/>
<EditText
android:id="@+id/edt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/enter_a_text"
android:layout_margin="10dp"
android:textColor="#101010"/>
<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save"
android:layout_margin="10dp"/>
<Button
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/show"
android:layout_margin="10dp"/>
</LinearLayout>
ステップ3: コードの記述
次に、以下のようにkotlinのコードを記述します。
MainActivity.kt
以下は、メインアクティビティーの全コードです。
package arb.test.shared.perferences
import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var shared : SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
shared = getSharedPreferences("Test" , Context.MODE_PRIVATE)
save.setOnClickListener {
val edit = shared.edit()
edit.putString("txt" , edt.text.toString())
Toast.makeText(this , "Was Saved" , Toast.LENGTH_SHORT).show()
edit.apply()
}
show.setOnClickListener {
txt.text = shared.getString("txt" , "No imported" )
Toast.makeText(this , shared.getString("txt" , "No imported" ) , Toast.LENGTH_SHORT).show()
}
}
}
実行
プロジェクトの実行
リファレンス
以下は、ダウンロードのリンクです。
ダウンロード](https://github.com/alirezabashi98/ShardePerferences/archive/refs/heads/master.zip) コード
ブラウズ コード
例2: SharedPreferences を使ったセッション管理
この例では、SharedPreferences を使用して、ユーザーがアプリにサインインした後などのユーザーセッションを管理する方法について学びます。この例も Kotlin で書かれています。
以下の 3 つのファイルが含まれています。
-
- 2つのアクティビティ - First ActivityとLogin Activity。
-
- セッソンマネージャ - SharedPreferences クラス
さあ、始めましょう。
ステップ1: プロジェクトの作成
まず、空の Android Studio
プロジェクトを作成します。
ステップ2: 依存関係
このプロジェクトでは、外部からの依存は必要ありません。
Step 3: レイアウトの設計
2つのレイアウトを設計します。
(a). activity_login.xml ログインアクティビティです。
これは、ログインアクティビティです。2つのTextViewsと1つのButtonを追加します。
<?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="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".LoginActivity">
<TextView
android:id="@+id/Disp_Username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Username"
android:textColor="@color/colorPrimary"/>
<TextView
android:id="@+id/Disp_Password"
android:layout_marginTop="20dp"
android:textColor="@color/colorPrimary"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"/>
<Button
android:id="@+id/btnLogout"
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:background="@color/colorPrimary"
android:textColor="@android:color/white"
android:text="Logout"/>
</LinearLayout>
(b). activity_first.xml
これは、メインのアクティビティのためのレイアウトです。ButtonとEdittextsを2つ追加します。
<?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="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".FirstActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Session Management"
android:textColor="@color/colorPrimary"
android:textSize="30sp"/>
<EditText
android:id="@+id/txtUsername"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="55dp"
android:textColorHint="@color/colorPrimary"
android:textColor="@color/colorPrimary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:background="@null"
android:hint="Username"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:background="@color/colorPrimary"/>
<EditText
android:id="@+id/txtPassword"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="55dp"
android:textColorHint="@color/colorPrimary"
android:textColor="@color/colorPrimary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:background="@null"
android:hint="Password"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:background="@color/colorPrimary"/>
<Button
android:id="@+id/btnLogin"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Login"
android:textColor="@android:color/white"
android:background="@color/colorPrimary"/>
</LinearLayout>
ステップ4:セッション・マネージャーの作成
sharedpreferencesを使用して、セッション・マネージャーを作成します。SharedPreferencesオブジェクト、SharedPreferences.Editorオブジェクト、Contextオブジェクト、プライベートモードを表す整数値などのインスタンスフィールドとともに、SessionManager.kt
ファイルを作成することから始めましょう。
class SessionManager {
var pref: SharedPreferences
var edior: SharedPreferences.Editor
var context: Context
var PRIVATE_MODE: Int = 0
コンストラクターで初期化します。
constructor(context: Context) {
this.context = context
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
edior = pref.edit()
}
コンパニオン・オブジェクトにスタティック・フィールドを定義する。
companion object {
val PREF_NAME: String = "KotlinDemo"
val IS_LOGIN: String = "isLogin"
val KEY_NAME: String = "name"
val KEY_PASS: String = "pass"
}
以下は、ログインセッションの作成方法です。
fun createLoginSession(name: String, emai: String) {
edior.putBoolean(IS_LOGIN, true)
edior.putString(KEY_NAME, name)
edior.putString(KEY_PASS, emai)
edior.commit()
}
以下は、ログインを確認する方法です。
fun checkLogin() {
if (!this.isLoggedIn()) {
var i: Intent = Intent(context, FirstActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(i)
}
}
sharedpreferencesからユーザー情報を取得し、HashMapで返します。
fun getUserDetails(): HashMap<String, String> {
var user: Map<String, String> = HashMap<String, String>()
(user as HashMap).put(KEY_NAME, pref.getString(KEY_NAME, null).toString())
(user as HashMap).put(KEY_PASS, pref.getString(KEY_PASS, null).toString())
return user
}
ユーザーをログアウトさせる方法は以下の通りです。
fun LogoutUser() {
edior.clear()
edior.commit()
val i: Intent = Intent(context, LoginActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(i)
}
そして、ユーザーがログインしているかどうかを確認する方法は以下の通りです。
fun isLoggedIn(): Boolean {
return pref.getBoolean(IS_LOGIN, false)
}
以下は、完全なコードです。
SessionManager.kt
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import com.example.sessionmanagementusingkotlin.FirstActivity
import com.example.sessionmanagementusingkotlin.LoginActivity
class SessionManager {
var pref: SharedPreferences
var edior: SharedPreferences.Editor
var context: Context
var PRIVATE_MODE: Int = 0
constructor(context: Context) {
this.context = context
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
edior = pref.edit()
}
companion object {
val PREF_NAME: String = "KotlinDemo"
val IS_LOGIN: String = "isLogin"
val KEY_NAME: String = "name"
val KEY_PASS: String = "pass"
}
fun createLoginSession(name: String, emai: String) {
edior.putBoolean(IS_LOGIN, true)
edior.putString(KEY_NAME, name)
edior.putString(KEY_PASS, emai)
edior.commit()
}
fun checkLogin() {
if (!this.isLoggedIn()) {
var i: Intent = Intent(context, FirstActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(i)
}
}
fun getUserDetails(): HashMap<String, String> {
var user: Map<String, String> = HashMap<String, String>()
(user as HashMap).put(KEY_NAME, pref.getString(KEY_NAME, null).toString())
(user as HashMap).put(KEY_PASS, pref.getString(KEY_PASS, null).toString())
return user
}
fun LogoutUser() {
edior.clear()
edior.commit()
val i: Intent = Intent(context, LoginActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(i)
}
fun isLoggedIn(): Boolean {
return pref.getBoolean(IS_LOGIN, false)
}
}
ステップ5: アクティビティの作成
2つのアクティビティがあります。
(a). FirstActivity.kt
ユーザーをログインさせ、SharedPreferencesにそのユーザーの詳細を保存します。
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.sdnkcreations.sessionmanagerinkotlin.SessionManager
import kotlinx.android.synthetic.main.activity_first.*
class FirstActivity : AppCompatActivity() {
lateinit var session: SessionManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
session = SessionManager(applicationContext)
if (session.isLoggedIn()) {
var i: Intent = Intent(applicationContext, FirstActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(i)
finish()
}
btnLogin.setOnClickListener {
val username: String = txtUsername.text.toString()
val password: String = txtPassword.text.toString()
if (username.trim().length > 0 && password.trim().length > 0) {
session.createLoginSession(username, password)
var i: Intent = Intent(applicationContext, LoginActivity::class.java)
startActivity(i)
finish()
} else {
Toast.makeText(this, "Login Failed...\n Please enter both credential", Toast.LENGTH_LONG).show()
}
}
}
}
**(b). ログインアクティビティ(LoginActivity.kt)
ログインしたユーザーの詳細情報を表示します。
class LoginActivity : AppCompatActivity() {
lateinit var session: SessionManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
session = SessionManager(applicationContext)
session.checkLogin()
val user: HashMap<String, String> = session.getUserDetails()
val name: String = user.get(SessionManager.KEY_NAME)!!
val pass: String = user.get(SessionManager.KEY_PASS)!!
Disp_Username.setText("Name: " + name)
Disp_Password.setText("Email: " + pass)
btnLogout.setOnClickListener {
session.LogoutUser()
}
}
}
実行
コードをコピーするか、以下のリンクからダウンロードし、ビルドして実行します。
参考
参考文献はこちらです。
ダウンロード 例
SharedPreferences のスニペット
このチュートリアルでは、SharedPreferencesについて、それが何であるか、なぜそれが重要であるか、そしていくつかの例を見ていきたいと思います。
以下は、SharedPreferences の例です。
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.MainThread;
import com.jiangkang.tools.King;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Map;
import java.util.Set;
public class SpUtils {
private SharedPreferences preferences;
private static final String DEFAULT_PREF_NAME = "ktools_pref";
private SharedPreferences.Editor editor;
public static SpUtils getInstance(Context context,String name){
return new SpUtils(context,name);
}
private SpUtils(Context context, String name) {
preferences = context.getSharedPreferences(name,Context.MODE_PRIVATE);
editor = preferences.edit();
}
public <T> SpUtils put(String key, T value){
if (value instanceof String){
editor.putString(key, (String) value);
}else if (value instanceof Boolean){
editor.putBoolean(key, (Boolean) value);
}else if (value instanceof Integer){
editor.putInt(key, (Integer) value);
}else if (value instanceof Long){
editor.putLong(key, (Long) value);
}else if (value instanceof Float){
editor.putFloat(key, (Float) value);
}else {
throw new IllegalArgumentException("value can not support");
}
return this;
}
public SpUtils putString(String key, String value){
editor.putString(key,value).commit();
return this;
}
public SpUtils putBoolean(String key, boolean value){
editor.putBoolean(key, value).commit();
return this;
}
public SpUtils putInt(String key, int value){
editor.putInt(key,value).commit();
return this;
}
public SpUtils putFloat(String key, float value){
editor.putFloat(key, value).commit();
return this;
}
public SpUtils putLong(String key, long value){
editor.putLong(key, value).commit();
return this;
}
public SpUtils putJsonObject(String key, JSONObject object){
editor.putString(key,object.toString());
return this;
}
public JSONObject getJsonObject(String key){
String jsonString = preferences.getString(key,"{}");
try {
return new JSONObject(jsonString);
} catch (JSONException e) {
return null;
}
}
public String getString(String key,String defaultValue){
return preferences.getString(key,defaultValue);
}
public boolean getBoolean(String key, boolean defaultValue){
return preferences.getBoolean(key, defaultValue);
}
public int getInt(String key, int defaultValue){
return preferences.getInt(key, defaultValue);
}
public long getLong(String key, long defaultValue){
return preferences.getLong(key, defaultValue);
}
public float getFloat(String key,float defaultValue){
return preferences.getFloat(key, defaultValue);
}
public Map<String,?> getAll(){
return preferences.getAll();
}
}
2. SharedPreferenceでJSONデータを保存・取得する方法
まず、メインのアプリケーションを作成しましょう。
このクラスは、Applicationクラスから派生しています。このクラスがやってくれることは、アプリケーションのContextを保持し、それを与えてくれることだけです。
import android.app.Application;
import android.content.Context;
public class MainApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
public static Context getContext() {
return context;
}
}
アプリケーションクラスを作成したら、次はjsonデータの保存と読み込みを行います。
最初のメソッドは save()
メソッドです。このメソッドでは、2つの文字列と1つのオブジェクトを受け取ります。
ここでは、Google Gsonライブラリを使用しています。これはサードパーティーのライブラリなので、アプリレベルの build.gradle
ファイルに依存関係として追加する必要があります。
app フォルダにある build.gradle
ファイルに移動して、dependencies closure の下に以下の行を追加してください。
implementation 'com.google.code.gson:gson:2.8.1'
もしかしたら、それ以降のバージョンを確認できるかもしれません。
プロジェクトを同期させたら、Gsonのインスタンス化から始めます。
Gson gson = new Gson();
そして、SharedPreferences
を取得します。
SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);
SharedPreferences クラスの
edit() メソッドを呼び出して、
SharedPreference.Editor` オブジェクトを取得します。
SharedPreferences.Editor editor = pref.edit();
Gsonクラスの toJson()
メソッドを用いて、オブジェクトをJSONに変換します。そして、そのJSONデータを SharedPreference.Editor
インスタンスのキーと一緒に置いて、apply()
メソッドを呼び出すと、そのJSONデータが表示されます。
editor.putString(key, gson.toJson(object));
editor.apply();
これがSharedPreferencesにJSONデータを保存する方法です。
そのデータを読み込むにはどうしたらよいでしょうか。データをロードするのも簡単です。ここでもGsonをインスタンス化し、SharedPreferencesを初期化します。
そして、SharedPreferences
クラスの getString()
メソッドを呼び出して、データをJSONの文字列として取得します。
String json = pref.getString(key, null);
値が null
であるかどうかを調べ、その場合は null
を返します。それ以外の場合は、Gsonクラスの fromJson()
メソッドを使用して、オブジェクトを取得します。
以下はそのコードです。
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.slotnslot.slotnslot.MainApplication;
public class StorageUtil {
public static void save(String identifier, String key, Object object) {
Gson gson = new Gson();
SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, gson.toJson(object));
editor.apply();
}
public static <T> T load(String identifier, String key, Class<T> clazz) {
Gson gson = new Gson();
SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);
String json = pref.getString(key, null);
return json == null ? null : gson.fromJson(json, clazz);
}
}