完成共用參數的讀寫public class SharedPreference { private Context context; public SharedPreference(Context context) { // TODO Auto-generated constructor stub t... ...
完成共用參數的讀寫
public class SharedPreference { private Context context; public SharedPreference(Context context) { // TODO Auto-generated constructor stub this.context = context; } public boolean saveMessage(String name, String passwd) { boolean flag = false; // 自動保存成 userinfo.xml SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo", Context.MODE_PRIVATE); // 對數據進行編輯 SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("name", name); editor.putString("passwd", passwd); // 將數據持久化到存儲介質中 flag = editor.commit(); return flag; } public Map<String, Object> getMessage() { Map<String, Object> map = new HashMap<String, Object>(); SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo", Context.MODE_PRIVATE); String name = sharedPreferences.getString("name", ""); String passwd = sharedPreferences.getString("passwd", ""); map.put("name", name); map.put("passwd", passwd); return map; } }
編寫測試函數
private Button button1; private Button button2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SharedPreference sharedPreference = new SharedPreference(MainActivity.this); boolean flag = sharedPreference.saveMessage("furong", "123456"); Toast.makeText(MainActivity.this, "---->" + flag, 1).show(); } }); button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Map<String, Object> map; SharedPreference sharedPreference = new SharedPreference(MainActivity.this); map = sharedPreference.getMessage(); Toast.makeText(MainActivity.this, map.toString(), 1).show(); } }); }