实例,一个按钮用于读数据,一个按钮用于写数据
activity_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"
tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:id="@+id/red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="读数据"/>
<Button android:id="@+id/write"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="写数据"/>
</LinearLayout>
<TextView android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity.java
package com.example.sharedpreferences;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
SharedPreferences preferences;
SharedPreferences.Editor edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//第二个参数表示,该SharedPreferences数据能被其他应用程序读,但不能写
preferences=getSharedPreferences("hanqing", Context.MODE_WORLD_READABLE);
edit=preferences.edit();
Button read=(Button) super.findViewById(R.id.red);
Button write=(Button) super.findViewById(R.id.write);
final TextView result=(TextView) super.findViewById(R.id.result);
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日"+"hh:mm:ss");
//存入当前时间
edit.putString("time", sdf.format(new Date()));
//存入一个随机数
edit.putInt("random", (int)(Math.random()*100));
edit.commit();
}
});
read.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//读取字符串
String time=preferences.getString("time", null);
//读取随机数,默认值为0
int random=preferences.getInt("random", 0);
String text="时间:"+time+"\n随机数"+random;
result.setText(text);
}
});
}
}