700 views
この記事は最終更新から 1143日 が経過しています。
1. やりたいこと
以下の Android公式ページの記述に従って SharedPreferences を使い Key-Value型 のデータの Read/Writeを実装してみた。
https://developer.android.com/training/data-storage/shared-preferences
2. やってみる
1) 作るプログラムの仕様
1. 画面上に、EditText, Button(WRITE), Button(READ), TextView の全 4個の Viewを配置する。
2. EditTextにテキストを入力し、Button(W)を押下すると、SharedPreferencesにテキストを保存する。
3. Button(R)を押下すると、SharedPreferencesに保存された全データを読み出し、TextViewに保存する。
4. SharedPreferencesに保存するデータの Key-Value の組み合わせは以下の通り。
| # | key | value |
| 1 | n | 登録数 |
| 2 | t1 | テキスト(1番目) |
| t2 | テキスト(2番目) | |
| : | : | |
| tn | テキスト(n番目) |

(1) リソース
共有環境設定ファイルにアクセスするためのユニークな識別子を作る。
{applicationId}.PREFERENCE_FILE_KEY
にしておけば、他のアプリとは被らないはず、とのこと。(上記の Android公式サイトの説明を参照のこと)
<resources>
<string name="app_name">TestSharedPreferences</string>
<string name="preference_file_key">com.example.testsharedpreferences.PREFERENCE_FILE_KEY</string>
</resources>
(2) Javaソースコード
package com.example.testsharedpreferences;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private SharedPreferences sharedPref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.sharedPref = this.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
}
/* 保存するデータ構造
n : データ数
t1~tn : データ(Text)
*/
private void ExecSave(String txt){
int n = this.sharedPref.getInt("n", 0);
if(txt != ""){
String newKey = String.format("t%d", n);
n++;
SharedPreferences.Editor editor = this.sharedPref.edit();
editor.putInt("n", n);
editor.putString(newKey, txt);
editor.apply();
}
}
private List<String> ExecRead(){
List<String> list = new ArrayList<>();
int n = this.sharedPref.getInt("n", 0);
for(int i = 0 ; i < n ; i++ ){
String key = String.format("t%d", i);
String val = this.sharedPref.getString(key, "*");
list.add(val);
}
return list;
}
public void onPushWrite(View view){
EditText et = this.findViewById(R.id.et_text);
String txt = et.getText().toString();
ExecSave(txt);
}
public void onPushRead(View view){
List<String> txtList = this.ExecRead();
String txt = "";
for(String s : txtList){
txt += s + "\n";
}
TextView tv = this.findViewById(R.id.tv_list);
tv.setText(txt);
}
}
アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済2026-04-19: 0回 2026-04-18: 2回 2026-04-17: 1回 2026-04-16: 0回 2026-04-15: 0回 2026-04-14: 0回 2026-04-13: 0回