android SharedPreferences的使用



public class MainActivity extends Activity {

 private EditText et;
 private Button bt;
 private TextView tv;
 SharedPreferences preferences;
 SharedPreferences.Editor editor;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  et = (EditText) findViewById(R.id.editText1);
  bt = (Button) findViewById(R.id.button1);
  tv = (TextView) findViewById(R.id.textView1);
  preferences = getSharedPreferences("crazyit", MODE_WORLD_READABLE);
  editor = preferences.edit();
  bt.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View arg0) {
    // 读取字符串
    String time = preferences.getString("time", null);
    int randNum = preferences.getInt("random", 0);
    String result = time == null ? "您暂时还未写入数据" : "写入的时间为" + time
      + "\n 上次生成的随机数是" + randNum;
    Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
   }
  });
  tv.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    SimpleDateFormat adf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
    editor.putString("time", adf.format(new Date()));
    editor.putInt("random", (int)(Math.random()*100));
    editor.commit();
   }
  });

 }

}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。