SharedPreferences共用參數類

來源:互聯網
上載者:User

一、作用

    主要用於存放軟體的配置參數等資訊。sharedPreferences用於存取和修改軟體配置參數資料的介面,由getSharedPreferences(String, int)函數返回。任何具體的參數,都有一個單獨的該類執行個體向所有用戶端共用。修改參數必須通過SharedPreferences.Editor 對象,以確保這些參數在被提交到外存的時候它們的值處於一致的狀態和控制之下。該類暫不支援多進程操作,但是以後將提供該功能。

原文:

Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage.

Note: currently this class does not support use across multiple processes. This will be added later.

 

二、SharedPreferences.Editor 類簡介

public abstract SharedPreferences.Editor edit ()

Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.

Note that you must call commit() to have any changes you perform in the Editor actually show up in the SharedPreferences.

 

三、存放參數執行個體源碼:

            @Override
public void onClick(View v)
{
String name = nameText.getText().toString();
String age = ageText.getText().toString();
SharedPreferences preferences = getSharedPreferences("itcast",
Context.MODE_WORLD_READABLE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.putInt("age", new Integer(age));
editor.commit();
Toast.makeText(MainActivity.this, R.string.success, 1).show();
}

四、讀取參數執行個體源碼:

            @Override
public void onClick(View v)
{
SharedPreferences preferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
String name = preferences.getString("name", "");
int age = preferences.getInt("age", 20);
nameText.setText(name);
ageText.setText(String.valueOf(age));
}

五、歸納

通過以上類的介紹和執行個體源碼分析,可以總結出一般步驟:

存放:

1.獲得SharedPreferences 的執行個體對象,通過getSharedPreferences()傳遞檔案名稱和模式;

2.獲得Editor 的執行個體對象,通過SharedPreferences 的執行個體對象的edit()方法;

3.存入資料,利用Editor 對象的putXXX()方法;

4.提交修改的資料,利用Editor 對象的commit()方法。

 

讀取:

1.獲得SharedPreferences 的執行個體對象,通過getSharedPreferences()傳遞檔案名稱和模式;

2.讀取資料,通過SharedPreferences 的執行個體對象的getXXX()方法。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.