|
package com.demo.webb.savingkeyvaluesets; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class SavingKeyValueSets extends Activity { private Button save,read; private TextView textView; private EditText editText; private SharedPreferences pref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); read = (Button)findViewById(R.id.button_read); save = (Button)findViewById(R.id.button_save); textView = (TextView)findViewById(R.id.textView); editText = (EditText)findViewById(R.id.editText); /* Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made. Parameters name Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()). mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions. The bit MODE_MULTI_PROCESS can also be used if multiple processes are mutating the same SharedPreferences file. MODE_MULTI_PROCESS is always on in apps targetting Gingerbread (Android 2.3) and below, and off by default in later versions. MODE_PRIVATE MODE_WORLD_READABLE MODE_WORLD_WRITEABLE MODE_MULTI_PROCESS*/ pref = getSharedPreferences("save_key", Context.MODE_PRIVATE); } public void read_key(View view) { // 返回key文件存储的Data,如果找不到key文件则返回“The key file DefValues”位置的String String key = pref.getString("key","The key file DefValues"); textView.setText(key); System.out.print("save key"); } public void save_key(View view) { String key = editText.getText().toString(); //Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, // and not copied back to the original SharedPreferences until you call commit() or apply() SharedPreferences.Editor editor = pref.edit(); editor.putString("key", key); editor.commit(); Toast.makeText(SavingKeyValueSets.this, R.string.save_success, Toast.LENGTH_SHORT).show(); } }