■ はじめに
SharedPreferencesクラスを使って、設定用データを保存するやり方を学ぶ
■ 使用上の注意
1)PreferenceManager.getDefaultSharedPreferences(this) は、非推奨になっている => getSharedPreferences() なら非推奨の表示がされない
https://developer.android.com/reference/android/preference/PreferenceManager
■ 構文
設定値取得
// SharedPreferences 取得 var preference = getSharedPreferences("KeyName", MODE_PRIVATE) // 値取得 (getInt/getBoolean etc...) var value = preference.getString([キー], [デフォルト値])
設定値保存
// SharedPreferences 取得 var preference = getSharedPreferences("KeyName", MODE_PRIVATE) preference.edit().apply { putString([キー], [設定値]) putInt([キー], [設定値]) putBoolean([キー], [設定値]) commit() }
■ サンプル
Kotlin
デザイン部
Spinner 部分については、以下の関連記事を参照のこと
https://dk521123.hatenablog.com/entry/2013/10/08/000037
PreferenceActivity.kt
import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.preference.PreferenceManager import android.view.View import android.widget.AdapterView import android.widget.Spinner import io.realm.Realm import kotlinx.android.synthetic.main.activity_preference.* import java.util.prefs.Preferences class PreferenceActivity : AppCompatActivity() { val KeyOfIndexForMaxWordsInCard = "IndexForMaxWordsInCard" val DefalutIndexForMaxWordsInCard = 1 private lateinit var preference: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_preference) this.preference = getSharedPreferences("MySample", MODE_PRIVATE) var indexForMaxWordsInCard = this.preference.getInt( KeyOfIndexForMaxWordsInCard, DefalutIndexForMaxWordsInCard) indexForMaxWordsInCardSpinner.setSelection(indexForMaxWordsInCard) this.preference.edit().apply { putInt(KeyOfIndexForMaxWordsInCard, indexForMaxWordsInCard) commit() } // リスナーを登録 this.indexForMaxWordsInCardSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{ // 選択時 override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { val targetSpinner = parent as Spinner // 初回の動作 if (!targetSpinner.isFocusable) { targetSpinner.isFocusable = true; return; } preference.edit().apply { putInt(KeyOfIndexForMaxWordsInCard, position) commit() } } // 既に選択された項目を選択した場合 override fun onNothingSelected(parent: AdapterView<*>?) { // Do nothing } } } }
Java
MainActivity.java
import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preference = getSharedPreferences("Key", MODE_PRIVATE); SharedPreferences.Editor editor = preference.edit(); editor.putString("StringValue", "String"); editor.putInt("IntValue", 123); editor.commit(); } }
■ 確認方法
* 実行後、Android Studio で以下の手順で確認する [1] [Tools]-[Android]-[Android Dvice Monitor]を選択 [2] 「File Expoler」の/data/data 配下にある対象パッケージ名を選択 [3] 対象パッケージ配下のフォルダー「Shared_pref」にある xml (ここでは「Key.xml」)を選択 [4] フロッピーアイコンの「Pull a file from device」をクリックしてファイルを保存
出力結果
Key.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="StringValue">String</string> <int name="IntValue" value="123" /> </map>
参考文献
https://maku77.github.io/android/fw/shared-preference.html
https://akira-watson.com/android/sharedpreferences.html
関連記事
画面コンポーネント / RadioButton etc ~ 選択肢 ~
https://dk521123.hatenablog.com/entry/2013/10/08/000037
Kotlin ~ 基本編 / 配列・コレクション ~
https://dk521123.hatenablog.com/entry/2020/07/07/000000
Kotlin ~ 基本編 / Enum・列挙型関連 ~
https://dk521123.hatenablog.com/entry/2020/08/10/125112