Android SharedPreferences本地缓存

来源:互联网 发布:怎么选基金 知乎 编辑:程序博客网 时间:2024/05/16 00:54

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >        <Button         android:id="@+id/read"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="读取数据" />        <Button         android:id="@+id/write"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="写入数据" />            </LinearLayout>

SharedPreferencesTest.java

package com.example.sharedpreferences;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Locale;import android.os.Bundle;import android.app.Activity;import android.content.SharedPreferences;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class SharedPreferencesTest extends Activity {SharedPreferences preferences;SharedPreferences.Editor editor;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);preferences = getSharedPreferences("crazyit", MODE_WORLD_READABLE);editor = preferences.edit();Button read = (Button)findViewById(R.id.read);Button write = (Button)findViewById(R.id.write);read.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubString time = preferences.getString("time", null);int randNum = preferences.getInt("random", 0);String result = time == null? "您暂时还未写入数据":"写入时间为:"+ time + "\n上次生成的随机数为:" + randNum;Toast.makeText(SharedPreferencesTest.this, result, 5000).show();}});write.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubSimpleDateFormat time = new SimpleDateFormat("yyyy年MM月dd日 "+ "hh:mm:ss a", Locale.ENGLISH);editor.putString("time", time.format(new Date()));editor.putInt("random", (int)(Math.random() * 100));editor.commit();}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.shared_preferences_test, menu);return true;}}


0 0