SharedPreferences 简单读写


布局就是两个按钮,通过两个按钮一个读一个写

public class MainActivity extends Activity {
	
	SharedPreferences preferences;
	SharedPreferences.Editor editor;
	Button sread,swrite;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		preferences = getSharedPreferences("pmit",MODE_WORLD_READABLE);
		editor = preferences.edit();
		sread=(Button) findViewById(R.id.spreferences_read);
		swrite=(Button) findViewById(R.id.spreferences_write);
		
		//记录程序使用次数
        int count =preferences.getInt("count", 0);
		Toast.makeText(this, "程序被使用了"+ count +"次", 10000).show();
		editor.putInt("count",  ++count);
		editor.commit();
		//设置对按钮的响应
		sread.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				//
				String time =preferences.getString("time", null);
				int randNum = preferences.getInt("random", 0);
				String result = time == null ? "您暂时还没有写入数据 " : 
					"写入时间 " + time + "\n上次生成的随机数为:" + randNum;
				
			}
		});
		swrite.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日" +"hh:mm:ss");
				//存入当前时间和随机数
				editor.putString("time", sdf.format(new Date()));
				editor.putInt("random", (int) (Math.random()*100));
              	editor.commit();
			}
		});
	}

}






SharedPreferences 的三种权限
1.Context.MODE_PRIVATE 只能在本应用程序读写
2.Context.MODE_WORLD_READABLE 能被其他应用读
3.Context.MODE_WORLD_WRITEABLE 能被其他应用读写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值