Android SharedPreferences を使ってデータの保存と取得をしてみる。

データベースを使うまでもないが気軽に永続化したいぜ
といったような希望に応える簡単な処理である。

 

データ保存と取得処理

保存と取得には
PreferenceManager.getDefaultSharedPreferences()
を使用する。

Stringを保存取得するためにUtilクラスとして作り
どこからでもアクセスできるようにしてみた。

PreferenceUtil.java

public class PreferenceUtil {
enum PreferenceKey {
YEAH
}
public static void putString(Context context, PreferenceKey key, String value) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key.name(), value);
editor.apply();
}
public static String getString(Context context, PreferenceKey key) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(key.name(), "");
}
}
public class PreferenceUtil { enum PreferenceKey { YEAH } public static void putString(Context context, PreferenceKey key, String value) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = pref.edit(); editor.putString(key.name(), value); editor.apply(); } public static String getString(Context context, PreferenceKey key) { return PreferenceManager.getDefaultSharedPreferences(context) .getString(key.name(), ""); } }
public class PreferenceUtil {
    enum PreferenceKey {
        YEAH
    }

    public static void putString(Context context, PreferenceKey key, String value) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(key.name(), value);
        editor.apply();
    }

    public static String getString(Context context, PreferenceKey key) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getString(key.name(), "");
    }
}

 

保存と取得を実行

Activity側でUtilクラスのメソッドを呼び出して
保存と取得を実行する。

ボタン押下で保存した文字列を取得して
Toastで表示するだけの簡単な画面。

MainActivity.java

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceUtil.putString(getApplicationContext(),
PreferenceUtil.PreferenceKey.YEAH, "よっしゃ");
Button button = findViewById(R.id.button);
button.setOnClickListener(view -> {
String strYeah = PreferenceUtil.getString(
getApplicationContext(), PreferenceUtil.PreferenceKey.YEAH);
Toast.makeText(this, strYeah, Toast.LENGTH_LONG).show();
});
}
}
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PreferenceUtil.putString(getApplicationContext(), PreferenceUtil.PreferenceKey.YEAH, "よっしゃ"); Button button = findViewById(R.id.button); button.setOnClickListener(view -> { String strYeah = PreferenceUtil.getString( getApplicationContext(), PreferenceUtil.PreferenceKey.YEAH); Toast.makeText(this, strYeah, Toast.LENGTH_LONG).show(); }); } }
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PreferenceUtil.putString(getApplicationContext(),
                PreferenceUtil.PreferenceKey.YEAH, "よっしゃ");

        Button button = findViewById(R.id.button);
        button.setOnClickListener(view -> {
            String strYeah = PreferenceUtil.getString(
                    getApplicationContext(), PreferenceUtil.PreferenceKey.YEAH);
            Toast.makeText(this, strYeah, Toast.LENGTH_LONG).show();
        });
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="うれしいとき"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="うれしいとき" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="うれしいとき"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

xmlファイルに保存されている

今回保存した値がどこに格納されているか?

エミュレータで実行した場合は、
以下のパスのxmlファイルとして保存されている。

/data/data/com.example.myapplication/shared_prefs/com.example.myapplication_preferences.xml

xmlファイルの中身はこんな感じ。

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="YEAH">よっしゃ</string>
</map>
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="YEAH">よっしゃ</string> </map>
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="YEAH">よっしゃ</string>
</map>

 

ファイル名を指定して保存する

getSharedPreferences() を利用することで
保存先のxmlファイルのファイル名を指定することができる。

ただ、ファイルが複数あると管理が大変だし
使わなくなったらずっと残ってることになるし
理由があって使う以外は使わなくていい気がする。

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String fileName = "mogumogu";
String key = "rice";
String value = "ごはん";
SharedPreferences.Editor editor = getSharedPreferences(fileName, Context.MODE_PRIVATE).edit();
editor.putString(key, value);
editor.apply();
Button button = findViewById(R.id.button);
button.setOnClickListener(view -> {
SharedPreferences sp = getSharedPreferences(fileName, Context.MODE_PRIVATE);
String strYeah = sp.getString(key, "");
Toast.makeText(this, strYeah, Toast.LENGTH_LONG).show();
});
}
}
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String fileName = "mogumogu"; String key = "rice"; String value = "ごはん"; SharedPreferences.Editor editor = getSharedPreferences(fileName, Context.MODE_PRIVATE).edit(); editor.putString(key, value); editor.apply(); Button button = findViewById(R.id.button); button.setOnClickListener(view -> { SharedPreferences sp = getSharedPreferences(fileName, Context.MODE_PRIVATE); String strYeah = sp.getString(key, ""); Toast.makeText(this, strYeah, Toast.LENGTH_LONG).show(); }); } }
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String fileName = "mogumogu";
        String key = "rice";
        String value = "ごはん";

        SharedPreferences.Editor editor = getSharedPreferences(fileName, Context.MODE_PRIVATE).edit();
        editor.putString(key, value);
        editor.apply();

        Button button = findViewById(R.id.button);
        button.setOnClickListener(view -> {
            SharedPreferences sp = getSharedPreferences(fileName, Context.MODE_PRIVATE);
            String strYeah = sp.getString(key, "");
            Toast.makeText(this, strYeah, Toast.LENGTH_LONG).show();
        });
    }
}

 

String以外の型をつかう

保存、取得できる型は6つある

String
Set<String>
int
long
float
boolean

先ほどのUtilクラスに
型だけ変更したものを追加していけば良い。

booleanSet<String> を追加してみる。

PreferenceKeyStringbooleanSet<String>
と3つあるので、3つ分用意する。
keyの名称は適当にしたが、実際作る時はちゃんと考えよう。。

public class PreferenceExUtil {
enum PreferenceKey {
YEAH,
GOODBYE,
THANKS,
}
public static void putString(Context context, PreferenceKey key, String value) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key.name(), value);
editor.apply();
}
public static void putBoolean(Context context, PreferenceKey key, boolean value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean(key.name(), value);
editor.apply();
}
public static void putStringSet(Context context, PreferenceKey key, Set<String> value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putStringSet(key.name(), value);
editor.apply();
}
public static String getString(Context context, PreferenceKey key) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(key.name(), "");
}
public static boolean getBoolean(Context context, PreferenceKey key) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(key.name(), false);
}
public static Set<String> getStringSet(Context context, PreferenceKey key) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getStringSet(key.name(), new HashSet<>());
}
}
public class PreferenceExUtil { enum PreferenceKey { YEAH, GOODBYE, THANKS, } public static void putString(Context context, PreferenceKey key, String value) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = pref.edit(); editor.putString(key.name(), value); editor.apply(); } public static void putBoolean(Context context, PreferenceKey key, boolean value) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putBoolean(key.name(), value); editor.apply(); } public static void putStringSet(Context context, PreferenceKey key, Set<String> value) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putStringSet(key.name(), value); editor.apply(); } public static String getString(Context context, PreferenceKey key) { return PreferenceManager.getDefaultSharedPreferences(context) .getString(key.name(), ""); } public static boolean getBoolean(Context context, PreferenceKey key) { return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(key.name(), false); } public static Set<String> getStringSet(Context context, PreferenceKey key) { return PreferenceManager.getDefaultSharedPreferences(context) .getStringSet(key.name(), new HashSet<>()); } }
public class PreferenceExUtil {

    enum PreferenceKey {
        YEAH,
        GOODBYE,
        THANKS,
    }

    public static void putString(Context context, PreferenceKey key, String value) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(key.name(), value);
        editor.apply();
    }

    public static void putBoolean(Context context, PreferenceKey key, boolean value) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean(key.name(), value);
        editor.apply();
    }

    public static void putStringSet(Context context, PreferenceKey key, Set<String> value) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putStringSet(key.name(), value);
        editor.apply();
    }

    public static String getString(Context context, PreferenceKey key) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getString(key.name(), "");
    }

    public static boolean getBoolean(Context context, PreferenceKey key) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getBoolean(key.name(), false);
    }

    public static Set<String> getStringSet(Context context, PreferenceKey key) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getStringSet(key.name(), new HashSet<>());
    }
}

開発日記

Posted by konp