標籤:android style blog http io ar color os 使用
SharedPreference是Android提供的一種輕量級的資料存放區方式,主要用來儲存一些簡單的配置資訊,其以索引值對的方式儲存,使得我們能很方便進行讀取和存入
SharedPreference 檔案儲存在/data/data/<package name>/shared_prefs 路徑下
通過Activity內建的getSharedPreferences方法,可以得到SharedPreferences對象。
public abstract SharedPreferences getSharedPreferences (String name, int mode);
name:表示儲存後 xml 檔案的名稱
mode:表示 xml 文檔的操作許可權模式(私人,可讀,可寫),使用0或者MODE_PRIVATE作為預設的操作許可權模式。
1.資料讀取:
通過SharedPreferences對象的鍵key可以擷取到對應key的索引值。對於不同類型的索引值有不同的函數:getBoolean,getInt,getFloat,getLong.
public abstract String getString (String key, String defValue);
2.資料存入:
資料的存入是通過SharedPreferences對象的編輯器對象Editor來實現的。通過編輯器函數設定索引值,然後調用commit()提交設定,寫入xml檔案
public abstract SharedPreferences.Editor edit ();
public abstract SharedPreferences.Editor putString (String key, String value);
public abstract boolean commit ();
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/textview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello"/> </LinearLayout>
package com.android.test; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.widget.TextView; public class TestSharedPreferences extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SharedPreferences mSharedPreferences = getSharedPreferences("TestSharedPreferences", 0); // SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); int counter = mSharedPreferences.getInt("counter", 0); TextView mTextView = (TextView)findViewById(R.id.textview); mTextView.setText("This app has been started " + counter + " times."); SharedPreferences.Editor mEditor = mSharedPreferences.edit(); mEditor.putInt("counter", ++counter); mEditor.commit(); } }
資料的存入必須通過SharedPreferences對象的編輯器對象Editor來實現,存入(put)之後與寫入資料庫類似一定要commit!
PreferenceManager[Android]