2013年12月3日

SharedPreferencesとは

SharedPreferences

データを保存するときに使用します。設定値などの簡易なデータ保存に向きます。

大容量なデータ保存の場合は、SQLiteDatabaseを使用します。


SharedPreferences
保存後
MainAcitivity.java
public class MainActivity extends Activity implements OnClickListener{

 private SharedPreferences pref;
 private Editor editor;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);  
  
  Button button1 = (Button)findViewById(R.id.button1);
  button1.setOnClickListener(this);

  dataload();//保存データ読み込み
 }

 private void dataload() {
  // TODO 自動生成されたメソッド・スタブ 
  //////////データ読み込み//////////////
  pref = getSharedPreferences("SampleData", MODE_PRIVATE);//("データファイル名",モード)
     String _text = pref.getString("key", "初期値");//("key"任意のキー,"データが無い場合の初期値")
     
     TextView textview1 = (TextView)findViewById(R.id.textView1);
     textview1.setText(_text);
 }

 @Override
 public void onClick(View v) {
  // TODO 自動生成されたメソッド・スタブ
        switch (v.getId()) {
        case (R.id.button1)://保存ボタンクリック
      EditText edittext1 = (EditText)findViewById(R.id.editText1);
      String _edit = edittext1.getText().toString();
      
            editor = pref.edit();
            editor.putString("key", _edit);//("任意キー"."保存したいデータ")
            editor.commit();//.commit()で保存実行
            
            Toast.makeText(MainActivity.this,"保存しました",Toast.LENGTH_SHORT).show();
            
            dataload();
            
            break;  
        }
  }
}


res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="保存する文字を入力して下さい"
        android:inputType="text"/>


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"/>
   
</LinearLayout>

0 件のコメント:

コメントを投稿