SharedPreferences を使ってみた

Preference は Androidアプリでデータを保存する方法のひとつ
データをキーと値の組み合わせで保存します.

ファイルなどに保存するよりも非常に簡単にデータを保存できます

今回は SharedPreferences を...

SharedPreferences はまず
getSharedPreferences(String name, int mode);
でを取得してきます
name は Preference 自体の名前を指定します
mode には
  • Activity.MODE_PRIVATE
  • Activity.MODE_WORLD_READABLE
  • Activity.MODE_WORLD_WRITEABLE
などを指定します.

保存された Preference は data/data/パッケージ名/shared_prefs
の中に xmlファイルとして保存されるようです

取得する時は
  • getString(String key, String defValue);
  • getInt(String key, int defValue);
  • getLong(String key, long defValue);
  • ...
などを使って取得して着ます

というわけで,Preference を使ってみた

サンプルコード
public class PreferencesTest extends Activity implements OnClickListener {
  private static final String PREF_KEY = "preferenceTest";
  private static final String KEY_TEXT = "text";

  SharedPreferences pref;
  SharedPreferences.Editor editor;

  EditText mEditText;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.preferencestest);

    // SharedPrefernces の取得
    pref = getSharedPreferences(PREF_KEY, Activity.MODE_PRIVATE);

    mEditText = (EditText) findViewById(R.id.EditText);

    Button button;
    button = (Button) findViewById(R.id.Button);
    button.setOnClickListener(this);
    
    TextView textView;
    textView = (TextView) findViewById(R.id.TextView);
    // SharedPreferences よりデータを取得
    textView.setText(pref.getString(KEY_TEXT, "No Data"));
  }

  public void onClick(View v) {
    if (v.getId() == R.id.Button) {
      // Editor の設定
      editor = pref.edit();
      // Editor に値を代入
      editor.putString(
          KEY_TEXT,
          mEditText.getText().toString()
      );
      // データの保存
      editor.commit();
    }
  }
}

プログラムを実行すると...

保存して...

再び起動

こんな感じ!

ちなみに保存された Preference は
preferencetest.xml
<map>
<string name="text">Test</string>
</map>


参考サイト
http://developer.android.com/intl/ja/reference/android/content/SharedPreferences.html

1 件のコメント:

  1. Betway Group - JTM Hub
    Betway Group is a leading iGaming provider in the 계룡 출장마사지 world and and offer a wide range of sports betting 여주 출장안마 products. to offer the 파주 출장샵 best 대전광역 출장안마 odds 구리 출장샵 and betting

    返信削除