1. 程式人生 > >Android中的5種資料儲存方式之——SharedPreferences

Android中的5種資料儲存方式之——SharedPreferences

SharedPreferences

簡介

  • SharedPreferences是Android平臺上一個輕量級資料儲存方式,用來儲存應用的一些常用配置,比如Activity狀態,Activity暫停時,將此activity的狀態保到SharedPereferences中;當Activity過載,系統回撥方法 onSaveInstanceState時,再從SharedPreferences中將值取出。
  • SharedPreferences提供了java常規的Long、Int、String等型別資料的儲存介面。
  • SharedPreferences類似過去Windows系統上的ini配置檔案,但是它分為多種許可權,可以全域性共享訪問。
  • 提示最終是以xml方式來儲存,整體效率來看不是特別的高,對於常規的輕量級而言比SQLite要好不少,如果真的儲存量不大可以考慮自己定義檔案格式。xml處理時Dalvik會通過自帶底層的本地XML Parser解析,比如XMLpull方式,這樣對於記憶體資源佔用比較好。

實現方式

  • SharedPreferences介面主要負責讀取應用程式的Preferences資料,它提供瞭如下常用方法來訪問SharedPreferences的key_value鍵值對

  • SharedPreferences常用的屬性和方法

    public abstract boolean contains (String key)

    判斷SharedPreferences是否包含特定key的資料

    public abstract SharedPreferences.Editor edit ()

    返回一個Edit物件用於操作SharedPreferences

    public abstract Map

操作模式

SharedPreferences是一個介面,那麼我們怎麼樣來建立SharedPreferences例呢?可以通過Context.getSharedPreferences(Stringname,intmode)來得到一個SharedPreferences例項

name:是指檔名稱,不需要加字尾.xml,系統會自動為我們新增上。一般這個檔案儲存在/data/data/<package name>/shared_prefs

mode:是指定讀寫方式,其值有四種。分別為

Context.MODE_PRIVATE
 Context.MODE_APPEND
Context.MODE_WORLD_READABLE
Context.MODE_WORLD_WRITEABLE  
    ontext.MODE_PRIVATE:為預設操作模式,代表該檔案是私有資料,只能應用本身訪問,在該模式下,寫入的內容會覆蓋原檔案的內容  

    Context.MODE_APPEND:模式會檢查檔案是否存在,存在就往檔案追加內容,否則就建立新檔案.

    Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其他應用是否有許可權讀寫該檔案.

    MODE_WORLD_READABLE:表示當前檔案可以被其他應用讀取.

    MODE_WORLD_WRITEABLE:表示當前檔案可以被其他應用寫入  

用法

SharedPreferences 可以用來進行資料的共享,包括應用程式之間,或者同一個應用程式中的不同元件。比如兩個activity除了通過Intent傳

遞資料之外,也可以通過ShreadPreferences來共享資料。

        Editor sharedata = getSharedPreferences("data", 0).edit();
        sharedata.putString("item","hello getSharedPreferences");
        sharedata.commit();
        SharedPreferences sharedata = getSharedPreferences("data", 0);
        String data = sharedata.getString("item", null);
        Log.v("cola","data="+data);  

例項方法

MainActivity.java


        import android.app.Activity;
        import android.content.SharedPreferences;
        import android.content.SharedPreferences.Editor;
        import android.os.Bundle;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.widget.Toast;

        public class MainActivity extends Activity {
        private TextView tv_read;
        private EditText ed_wirte;
        private Button wirte, read;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ed_wirte = (EditText) findViewById(R.id.ed_write);
            tv_read = (TextView) findViewById(R.id.tv_read);
            wirte = (Button) findViewById(R.id.write);
            read = (Button) findViewById(R.id.read);
            wirte.setOnClickListener(Write);
            read.setOnClickListener(Read);
        }

        OnClickListener Write = new OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = ed_wirte.getText().toString();
                // 例項化SharedPreferences物件(第一步)
                SharedPreferences sharedPreferences = getSharedPreferences(
                        "sptest", MODE_PRIVATE);
                // 例項化SharedPreferences.Editor物件(第二步)
                Editor editor = sharedPreferences.edit();
                // 用putXX的方法儲存資料
                editor.putString("name", name);
                // 提交當前資料
                editor.commit();
                // 使用toast資訊提示框提示成功寫入資料
                Toast.makeText(MainActivity.this, "寫入成功", Toast.LENGTH_SHORT)
                        .show();
            }
        };
        OnClickListener Read = new OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences(
                        "sptest", MODE_PRIVATE);
                String name = sharedPreferences.getString("name", "");
                read.setText(name);

             }
           };

        }
  • 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"
        android:orientation="vertical">

        <EditText
        android:id="@+id/ed_write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

        <Button
        android:id="@+id/write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="write" />

        <Button
        android:id="@+id/read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="read" />

        <TextView
        android:id="@+id/tv_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

        </LinearLayout>
  • 圖片

  • 關於其他程式訪問sharedpreference的問題

OtherSpTest.java

    import java.io.File;
    import java.io.FileInputStream;

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.test.AndroidTestCase;
    import android.util.Log;

    public class OtherSpTest extends AndroidTestCase{
    private static final String TAG = "AccessSharePreferenceTest";

    /**
     * 訪問SharePreference的方式一,注:許可權要足夠
     * @throws Exception
     */
    public void OtherSpTest() throws Exception{
        String path = "/data/data/com.vampire.sharedpreferences.activity/shared_prefs/ljq123.xml";
        File file = new File(path);
        FileInputStream inputStream = new FileInputStream(file);
        //獲取的是一個xml字串
        String data = new FileService().read(inputStream);
        Log.i(TAG, data);
    }

    /**
     * 訪問SharePreference的方式二,注:許可權要足夠
     * @throws Exception
     */
    public void OtherSpTest2() throws Exception{
        Context context = this.getContext().createPackageContext("com.vampire.sharedpreferences.activity", 
                Context.CONTEXT_IGNORE_SECURITY);
        SharedPreferences sharedPreferences = context.getSharedPreferences("ljq123", 
                Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
        String name = sharedPreferences.getString("name", "");
        Log.i(TAG, name);
    }
    }

如果訪問其他應用中的Preference,前提條件是:該preference建立時指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE許可權。

如:有個為com.sp.MainActivity的應用使用下面語句建立了preference。

getSharedPreferences("sptest", Context.MODE_WORLD_READABLE);

其他應用要訪問上面應用的preference,首先需要建立上面應用的Context,然後通過Context 訪問preference ,訪問preference時會在應用所在包下的shared_prefs目錄找到preference :

Context otherAppsContext = createPackageContext("com.sp.MainActivity", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences   sharedPreferences =otherAppsContext.getSharedPreferences("sptest", Context.MODE_WORLD_READABLE); 
String name = sharedPreferences.getString("name", "");

如果不通過建立Context訪問其他應用的preference,也可以以讀取xml檔案方式直接訪問其他應用preference對應的xml檔案,如:

File xmlFile = new File("/data/data/<package name>/shared_prefs/itcast.xml");
//<package name>應替換成應用的包名

SharedPreferences的注意事項:

  • 編輯完SharedPreferences一定要記得呼叫Editor的commit()方法,否則不會將資料寫入到檔案裡的。
    回顧總結:

    1、 如何得到SharedPreferences

    SharedPreferences preferences=getPreferences(“test”,MODE_PRIVATE);
    

    2、 如何編輯SharedPreferences
    得到Editor物件例項

    SharedPreferences.Editor editor=preferences.editor();
    

    3、 SharedPreferences的儲存位置

    /data/data/<package name>/shared_prefs