1. 程式人生 > >sharedPreferences 增加資料和檢視資料

sharedPreferences 增加資料和檢視資料

public static void saveUserInfo(Context context,String username,String password) {
		SharedPreferences sharedPreferences = context.getSharedPreferences("config",Context.MODE_PRIVATE);
		//得到一個sharedPreferences編輯器
		Editor ed = sharedPreferences.edit();
		ed.putString("username",username);
		ed.putString("password",password);
		ed.commit();
	}
protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//初始化
		et_username = (EditText) this.findViewById(R.id.et_username);
		et_password = (EditText) this.findViewById(R.id.et_password);
		cb= (CheckBox) this.findViewById(R.id.et_remember_pwd);
		
		SharedPreferences sp = getSharedPreferences("config",MODE_PRIVATE);
		String username = sp.getString("username","");//第二個引數是 username不存在的時候的值 即預設值
		String password = sp.getString("password","");
		
		et_username.setText(username);
		et_password.setText(password);
	}