SharedPreferences保存数据以及取出数据

XML布局:两个EditText(账号和密码),两个Button(保存和取出)

代码:

private EditText et_userName, et_passWord;
private Button bt2, bt3;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_userName = (EditText) findViewById(R.id.editText1);
et_passWord = (EditText) findViewById(R.id.editText2);
bt2 = (Button) findViewById(R.id.button2);
bt3 = (Button) findViewById(R.id.button3);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);

}


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button2:
// 用SharedPreferences保存数据(SharedPreferences可在stop()方法之后保存当前的数据)
SharedPreferences sp = getSharedPreferences("User", 0);
Editor edit = sp.edit();
edit.putString("name", et_userName.getText().toString().trim());
edit.putString("pwd", et_passWord.getText().toString().trim());
edit.commit();
break;

case R.id.button3:(取出数据)
SharedPreferences sp1 = getSharedPreferences("User", 0);
String name = sp1.getString("name","");
String pwd = sp1.getString("pwd", "");
et_userName.setText(name);
et_passWord.setText(pwd);
break;
}

}



关键代码:

SharedPreferences保存数据:

                            SharedPreferences   sp  = getSharedPreferences("表名", 0);
                             Editor edit = sp.edit();
                              edit.putString("键名","值");

                              edit.commit();//提交

SharedPreferences取出数据:

                            SharedPreferences   sp1  = getSharedPreferences("表名", 0)
                            String name = sp1.getString("键名","如果键名不存在,默认显示当前String");

你可能感兴趣的:(Android)