SharedPreferences的写数据简单使用步骤如下:
第一步:获取SharedPreferences对象
第二步:获取SharedPreferences.Editor对象
第三步:通过此Editor对象来写入数据
第四步:通过此Editor对象来提交数据写入文件。
SharedPreferences的读数据简单使用步骤如下:
第一步:获取SharedPreferences对象
第二步:通过此对象来读数据。
注:
1、通过SharedPreferences可以将String类型数据和基本类型数据以XML格式存入到本地系统路径。
2、这种方式写入文件和读文件,不需要在manifest.xml配置中添加读写权限,因为它没有涉及到外部存储器。
public class MainActivity extends Activity {
TextView t;
EditText e;
SharedPreferences sp ;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getSharedPreferences("test", Activity.MODE_PRIVATE);
editor = sp.edit();
t = (TextView) findViewById(R.id.textView);
e = (EditText) findViewById(R.id.editText);
/*将数据写入/data/data/<package name>/share_prefs/目录下的文件去*/
Button w = (Button) findViewById(R.id.write);
w.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
editor.putString("content", e.getText().toString());
editor.commit();
}
});
/*将数据从文件中读出并显示*/
Button r = (Button) findViewById(R.id.read);
r.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String content = sp.getString("content", "");
t.setText(content);
}
});
}
}