使用SharedPreference時,資料的儲存必須使用commit()方法,否則資料不會儲存;
資料會儲存在DDMS的包目錄下的shared_prefs下:
Activity代碼
public class ContentProviderActivity extends Activity { /** Called when the activity is first created. */ private static final String FILENAME = "tmacsky"; private TextView author = null; private TextView age = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /*SharedPreferences share = getSharedPreferences(FILENAME,Activity.MODE_PRIVATE); SharedPreferences.Editor editor = share.edit();//指定操作的檔案名稱 editor.putString("author", "huanglong"); editor.putInt("age", 24); editor.commit();*///第一段代碼 setContentView(R.layout.main); author = (TextView)findViewById(R.id.author); age = (TextView)findViewById(R.id.age); SharedPreferences share = getSharedPreferences(FILENAME, Activity.MODE_PRIVATE); author.setText("作者: "+share.getString("author", "沒有作者資訊")); age.setText("年齡: "+share.getInt("age", 0));//第2段代碼 } } public class ContentProviderActivity extends Activity { /** Called when the activity is first created. */ private static final String FILENAME = "tmacsky"; private TextView author = null; private TextView age = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /*SharedPreferences share = getSharedPreferences(FILENAME,Activity.MODE_PRIVATE); SharedPreferences.Editor editor = share.edit();//指定操作的檔案名稱 editor.putString("author", "huanglong"); editor.putInt("age", 24); editor.commit();*///第一段代碼 setContentView(R.layout.main); author = (TextView)findViewById(R.id.author); age = (TextView)findViewById(R.id.age); SharedPreferences share = getSharedPreferences(FILENAME, Activity.MODE_PRIVATE); author.setText("作者: "+share.getString("author", "沒有作者資訊")); age.setText("年齡: "+share.getInt("age", 0));//第2段代碼 }}
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:textColor="#FFFFFF" android:textSize="22px" android:id="@+id/author"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textSize="22px" android:id="@+id/age"/> </LinearLayout> <?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:textColor="#FFFFFF" android:textSize="22px" android:id="@+id/author"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textSize="22px" android:id="@+id/age"/></LinearLayout>
先用第一段代碼裡的內容寫入資料,然後把第一段注釋掉,用下面第2段代碼加上main.xml來讀取資料: