SharedPreferencedは、アプリ開発において設定の保存・テキスト単体の読み出しの処理に
向いている便利なライブラリですが、gridviewと合わせることでpositionに合わせた
テキストを表示させることもできます。
まず最初に、ここではオブジェクトリテラルを使いたいのでputメソッドでkeyとvalueを
追加します。
sampleActivity↓
</pre> <pre>Map<Integer, String> contents = new HashMap<Integer, String>(); </pre> <pre>contents.put(0, "みかん"); contents.put(1, "りんご"); contents.put(2, "ぶどう"); contents.put(3, "すいか"); contents.put(4, "メロン"); contents.put(5, "マンゴー"); contents.put(6, "いちご"); contents.put(7, "パイナップル"); contents.put(8, "洋ナシ"); content = getSharedPreferences("content", MODE_PRIVATE);</pre> <pre>
gridviewを押した時にcontentsに追加したvalueと比較をするので
onItemClickの中で処理をしていきます。
</pre> <pre>//押した項目によって内容が変わる @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { System.out.println(position); SharedPreferences.Editor editor = content.edit(); for(Map.Entry<Integer, String> entry : contents.entrySet()){ System.out.println(entry.getKey() + ":" + entry.getValue()); if(entry.getKey() == position){ editor.putString("key", String.valueOf(entry.getValue())); editor.apply(); } } Intent intent = new Intent(getApplication(), GetPictureActivity.class); startActivity( intent ); }</pre> <pre>
新たにMap.entryでinteger・String型の配列を作ります。
4行目のforで先ほどvalueを入れたcontentsをentry配列に入れているのが分かります。
ここで一つずつgetKeyで得たキーの値と押された番号(int position)が合っているか
確認し、一致すればeditor.applyで保存をします。
値が合うまではずっと回り続けるので空の値が保存されましたーなんてことも
防ぐことができます。
次は、遷移先でさきほど取得したvalueの取り出し作業をします。
</pre> <pre>TextView contentsText = findViewById(R.id.contents); SharedPreferences data = getSharedPreferences("content", MODE_PRIVATE); String state = data.getString("key", "" ); contentsText.setText(state);</pre> <pre>
こちらでは従来のSharedPreferencesの取り出ししかしていないので特に説明は
しなくても大丈夫そう。
テキストだけ取得する場合はsqlliteで保存したりintentでいちいち手渡しする
必要もなさそうなのでこっちのがいいかなと思っています。