android数据存储_SharedPreferences的简单使用

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);
			}
		});
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值