SharedPreferences
SharedPreferences简介
SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。
运用SharedPreferences记住用户名和密码
package com.xiaogao.user.android2lesson_12_sharedpreferencedemo;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn;
private EditText username;
private EditText password;
String etN;
String etP;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username= (EditText) findViewById(R.id.main_name);
password= (EditText) findViewById(R.id.main_psw);
btn= (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
etN =username.getText().toString().trim();
etP =password.getText().toString().trim();
//写入
//创建sharedPreference
SharedPreferences sharedSetting= MainActivity.this.getSharedPreferences("com.lanou.user.android2lesson_12_sharedpreferencedemo",MODE_PRIVATE);
//拿到sharedPreferences编辑对象
SharedPreferences.Editor editor=sharedSetting.edit();
editor.putString("username",etN);
editor.putString("password",etP);
editor.commit();
Toast.makeText(MainActivity.this, "sharedPreference显示", Toast.LENGTH_SHORT).show();
}
});
SharedPreferences sharedStting1=this.getSharedPreferences("com.lanou.user.android2lesson_12_sharedpreferencedemo",MODE_PRIVATE);
String name=sharedStting1.getString("username",etN);
String pasword=sharedStting1.getString("password",etP);
// Toast.makeText(MainActivity.this, "名字:"+name+"密码:"+password, Toast.LENGTH_SHORT).show();
username.setText(name);
password.setText(pasword);
}
}
显示出来是这样的: