首页 > 学院 > 开发设计 > 正文

SharedPreferences存储

2019-11-09 15:27:09
字体:
来源:转载
供稿:网友

界面有【写入数据】和【读取数据】两个按钮

程序代码如下:

package com.twac.sharedPReferancestests;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity {	private Button btn_save;	private Button btn_load;	private SharedPreferences preferences;	private SharedPreferences.Editor editor;	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		btn_save = (Button) findViewById(R.id.btn_save);		btn_load = (Button) findViewById(R.id.btn_load);		// 获取只能被本应用程序读写的sharedpreferances对象		preferences = getSharedPreferences("twac", MODE_PRIVATE);		editor = preferences.edit();		// 写入数据		btn_save.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View arg0) {				SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日"						+ "hh:mm:ss");				int randomNumber = (int) (Math.random() * 1000);				editor.putString("date", sdf.format(new Date()));				editor.putInt("randomNumber", randomNumber);				editor.commit();				Toast.makeText(MainActivity.this, "数据写入成功", Toast.LENGTH_LONG)						.show();			}		});		// 读出数据		btn_load.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View arg0) {				String date = preferences.getString("date", null);				int randomNumber = preferences.getInt("randomNumber", 0);				String message = date == null ? "数据还未写入" : "写入时间为:" + date						+ "/n 写入的随机数为:" + randomNumber;				// 使用toast显示信息				Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG)						.show();			}		});	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表