Android開發之路十一———–SharedPreferes

來源:互聯網
上載者:User
SharedPreferes

SharedPreferences是Android平台上一個輕量級的儲存類,主要是儲存一些常用的配置比如視窗狀態,一般在Activity中 重載視窗狀態onSaveInstanceState儲存一般使用SharedPreferences完成,它提供了Android平台常規的Long長 整形、Int整形、String字串型的儲存,它是什麼樣的處理方式呢?SharedPreferences類似過去Windows系統上的ini設定檔,但是它分為多種許可權,可以全域共用訪問,android123提示最 終是以xml方式來儲存,整體效率來看不是特別的高,對於常規的輕量級而言比SQLite要好不少,如果真的儲存量不大可以考慮自己定義檔案格式。xml
處理時Dalvik會通過內建底層的本地XML Parser解析,比如XMLpull方式,這樣對於記憶體資源佔用比較好。

這種方式應該是用起來最簡單的Android讀寫外部資料的方法了。他的用法基本上和J2SE(java.util.prefs.Preferences)中的用法一樣,以一種簡單、透明的方式來儲存一些使用者個人化的字型、顏色、位置等參數資訊。一般的應用程式都會提供“設定”或者“喜好設定”的這樣的介面,那麼這些設定最後就可以通過Preferences來儲存,而程式員不需要知道它到底以什麼形式儲存的,儲存在了什麼地方。當然,如果你願意儲存其他的東西,也沒有什麼限制。只是在效能上不知道會有什麼問題。

在Android系統中,這些資訊以XML檔案的形式儲存在 

/data/data/PACKAGE_NAME /shared_prefs 目錄下。

SharedPreferencespre = getSharedPreferences("soft",

Context.MODE_WORLD_READABLE);

在這裡我們可以調用 activity 為我們提供的方法,這個方法有兩個參數:

1). 檔案名稱。 在這裡要特別注意。 因為在Android 中已經確定了SharedPreferences 是以 xm l形式儲存,所以,在填寫檔案名稱參數時,不要給定 ” .xml ”尾碼, android 會自動添加 。它是採用索引值對的形式儲存參數。 當你需要獲得某個參數值時, 按照參數的鍵索引即可。

2). 第二個可以理解為建立模式和之前的檔案儲存體的模式是一樣的。

Context. MODE_PRIVATE

Context.MODE_APPEND MODE_APPEND

Context.MODE_WORLD_READABLE

Context.MODE_WORLD_WRITEABLE

 

實驗步驟

 

1、       資源

    <string name="name_text">姓名</string>

<string name="age_text">年齡</string>

<string name="save_text">提交</string>

 

2、       布局

<?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" >

 

    <LinearLayout

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal" >

 

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginRight="30dp"

            android:text="@string/name_text" />

 

        <EditText

            android:id="@+id/nameEt"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content" />

    </LinearLayout>

 

    <LinearLayout

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal" >

 

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginRight="30dp"

            android:text="@string/age_text" />

 

        <EditText

            android:id="@+id/ageEt"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content" />

    </LinearLayout>

 

    <Button

        android:id="@+id/saveBtn"

        android:layout_marginTop="30dp"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/save_text" />

</LinearLayout>

3、       實現儲存

private void findViews() {

       nameEt = (EditText) this.findViewById(R.id.nameEt);

       ageEt = (EditText) this.findViewById(R.id.ageEt);

       saveBtn = (Button) this.findViewById(R.id.saveBtn);

 

       saveBtn.setOnClickListener(new View.OnClickListener() {

 

           public void onClick(View v) {

   

              String name = nameEt.getText().toString().trim();

              int age =

Integer.valueOf(ageEt.getText().toString().trim());

             

              SharedPreferences sharedPreferences =

SharedpreferencesTestActivity.this

.getSharedPreferences("myOption", MODE_PRIVATE);

              Editor editor = sharedPreferences.edit();

              editor.putString("name"  ,name);

              editor.putInt("age", age);

             

              editor.commit();

           }

       });

}

4、       添加讀取功能

 

資源添加

<string name="read_text">讀取</string>

布局修改為

…  

 <TableLayout

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_margin="15dp"

        android:stretchColumns="*">

 

        <TableRow >

            <Button

                android:id="@+id/saveBtn"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_marginTop="30dp"

                android:text="@string/save_text"
/>

 

            <Button

                android:id="@+id/readBtn"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_marginTop="30dp"

                android:text="@string/read_text" />

        </TableRow>

    </TableLayout>

代碼修改為

public void onClick(View v) {

    SharedPreferences sp = getSharedPreferences("myOption",

MODE_PRIVATE);

    String name="無名氏";

    int age = -1;

   

    switch (v.getId()) {

    case R.id.saveBtn:

       name = nameEt.getText().toString().trim();

       age = Integer.valueOf(ageEt.getText().toString().trim());

 

       Editor editor = sp.edit();

       editor.putString("name", name);

       editor.putInt("age", age);

 

       editor.commit();        

       break;

    case R.id.readBtn:

       name = sp.getString("name", "無名氏");

       age = sp.getInt("age", -1);

       Toast.makeText(this,

"姓名: "+name+ " 年齡: " +String.valueOf(age),

Toast.LENGTH_SHORT).show();

       break;

    }

}

 

5、       讀取其它應用程式的SharedPreferences

首先保證建立SharedPreferences的工程中使用的是:

Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE

其次,當前工程中讀取的代碼為:

try {

    Context otherContext =

this.createPackageContext("cn.class3g.activity",

Context.CONTEXT_IGNORE_SECURITY);

    SharedPreferences sp =

otherContext.getSharedPreferences("myOption",

MODE_PRIVATE);

 

    String res = "姓名:"+ sp.getString("name", null).toString()

+ " 年齡:"+ String.valueOf(sp.getInt("age", -1));

    Toast.makeText(this, res, Toast.LENGTH_LONG).show();

          

} catch (NameNotFoundException e) {

    e.printStackTrace();

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.