main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
ActivityMain
package com.android;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.widget.Toast;
public class ActivityMain extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//保存数据到SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("test", Context.MODE_WORLD_READABLE);
//获取编辑器对象
Editor editor = sharedPreferences.edit();
editor.putString("name", "android");
editor.putInt("age", 2);
//提交修改
editor.commit();
//获取SharedPreferences中保存的数据
//SharedPreferences sharedPreferences = getSharedPreferences("test", Context.MODE_PRIVATE);
//getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);
Toast.makeText(this, "name:"+name+",age:"+age, Toast.LENGTH_LONG).show();
}
}
1.Context.MODE_PRIVATE指定该SharedPreferences数据只能被本应用程序读写
2.Context.MODE_WORLD_READABLE指定该SharedPreferences数据能被其他程序读,但不能写
3.Context.MODE_WORLD_WRITEABLE指定该SharedPrefernces数据能被其他程序读写
SharedPreferences使用一,布布扣,bubuko.com
原文:http://blog.csdn.net/u010794950/article/details/24315259