android中使用SharedPreferences進行資料存放區的操作方法_Android

來源:互聯網
上載者:User

很多時候我們開發的軟體需要向使用者提供軟體參數設定功能,例如我們常用的QQ,使用者可以設定是否允許陌生人添加自己為好友。對於軟體配置參數的儲存,如果是window軟體通常我們會採用ini檔案進行儲存,如果是 j2se應用,我們會採用properties屬性檔案或者xml進行儲存。如果是Android應用,我們最適合採用什麼方式儲存軟體配置參數呢?Android 平台給我們提供了一個SharedPreferences類,它是一個輕量級的儲存類,特別適合用於儲存軟體配置參數。使用 SharedPreferences儲存資料,其背後是用xml檔案存放資料,檔案存放在/data/data/<package name>/shared_prefs目錄下:

SharedPreferences sharedPreferences = getSharedPreferences("ljq", Context.MODE_PRIVATE);

Editor editor = sharedPreferences.edit();//擷取編輯器

editor.putString("name", "林計欽");

editor.putInt("age", 24);

editor.commit();//提交修改                  

產生的ljq.xml檔案內容如下:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>

<map>

   <string name="name">林計欽</string>

   <int name="age" value="24" />

</map>

因為SharedPreferences背後是使用xml檔案儲存資料,getSharedPreferences(name,mode)方法的第一個參數用於指定該檔案的名稱,名稱不用帶尾碼,尾碼會由Android自動加上。方法的第二個參數指定檔案的操作模式,共有四種操作模式,這四種模式前面介紹使用檔案方式儲存資料時已經講解過。如果希望SharedPreferences背後使用的xml檔案能被其他應用讀和寫,可以指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE許可權。

另外Activity還提供了另一個getPreferences(mode)方法操作SharedPreferences,這個方法預設使用當前類不帶包名的類名作為檔案的名稱。                                

訪問SharedPreferences中的資料

訪問SharedPreferences中的資料代碼如下:

SharedPreferences sharedPreferences = getSharedPreferences("ljq", Context.MODE_PRIVATE);

//getString()第二個參數為預設值,如果preference中不存在該key,將返回預設值

String name = sharedPreferences.getString("name", "");

int age = sharedPreferences.getInt("age", 1);

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

如:有個<package name>為com.ljq.action的應用使用下面語句建立了preference。

getSharedPreferences("ljq", Context.MODE_WORLD_READABLE);

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

Context otherAppsContext = createPackageContext("com.ljq.action", Context.CONTEXT_IGNORE_SECURITY);

SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("ljq", Context.MODE_WORLD_READABLE);

String name = sharedPreferences.getString("name", "");

int age = sharedPreferences.getInt("age", 0);

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

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

案例:

string.xml檔案

複製代碼 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, SpActivity!</string>
    <string name="app_name">軟體配置參數</string>
    <string name="name">姓名</string>
    <string name="age">年齡</string>
    <string name="button">儲存設定</string>
    <string name="showButton">顯示</string>
</resources>

main.xml布局檔案
複製代碼 代碼如下:

<?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">
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/name"
            android:textSize="20px"
            android:id="@+id/nameLable" />
        <EditText android:layout_width="80px"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/nameLable"
            android:layout_alignTop="@id/nameLable"
            android:layout_marginLeft="10px"
            android:id="@+id/name" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20px"
            android:text="@string/age"
            android:id="@+id/ageLable" />
        <EditText android:layout_width="80px"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/ageLable"
            android:layout_alignTop="@id/ageLable"
            android:layout_marginLeft="10px"
            android:id="@+id/age" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button"
            android:id="@+id/button" />
        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/showButton"
            android:layout_toRightOf="@id/button"
            android:layout_alignTop="@id/button"
            android:id="@+id/showButton" />
    </RelativeLayout>
    <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="20px"
            android:id="@+id/showText" />
</LinearLayout>

複製代碼 代碼如下:

package com.ljq.activity;

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

public class SpActivity extends Activity {
    private EditText nameText;
    private EditText ageText;
    private TextView resultText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        nameText = (EditText)this.findViewById(R.id.name);
        ageText = (EditText)this.findViewById(R.id.age);
        resultText = (TextView)this.findViewById(R.id.showText);

        Button button = (Button)this.findViewById(R.id.button);
        Button showButton = (Button)this.findViewById(R.id.showButton);
        button.setOnClickListener(listener);
        showButton.setOnClickListener(listener);

        // 回顯
        SharedPreferences sharedPreferences=getSharedPreferences("ljq123",
                Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
        String nameValue = sharedPreferences.getString("name", "");
        int ageValue = sharedPreferences.getInt("age", 1);
        nameText.setText(nameValue);
        ageText.setText(String.valueOf(ageValue));
    }

    private View.OnClickListener listener = new View.OnClickListener(){
        public void onClick(View v) {
            Button button = (Button)v;
            //ljq123檔案存放在/data/data/<package name>/shared_prefs目錄下
            SharedPreferences sharedPreferences=getSharedPreferences("ljq123",
                    Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
            switch (button.getId()) {
            case R.id.button:
                String name = nameText.getText().toString();
                int age = Integer.parseInt(ageText.getText().toString());
                Editor editor = sharedPreferences.edit(); //擷取編輯器
                editor.putString("name", name);
                editor.putInt("age", age);
                editor.commit();//提交修改
                Toast.makeText(SpActivity.this, "儲存成功", Toast.LENGTH_LONG).show();
                break;
            case R.id.showButton:
                String nameValue = sharedPreferences.getString("name", "");
                int ageValue = sharedPreferences.getInt("age", 1);
                resultText.setText("姓名:" + nameValue + ",年齡:" + ageValue);
                break;
            }
        }
    };
}


運行結果



如何訪問其他應用中的Preference?

複製代碼 代碼如下:

package com.ljq.sp;

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 AccessSharePreferenceTest extends AndroidTestCase{
    private static final String TAG = "AccessSharePreferenceTest";

    /**
     * 訪問SharePreference的方式一,註:許可權要足夠
     * @throws Exception
     */
    public void testAccessPreference() throws Exception{
        String path = "/data/data/com.ljq.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 testAccessPreference2() throws Exception{
        Context context = this.getContext().createPackageContext("com.ljq.activity",
                Context.CONTEXT_IGNORE_SECURITY);
        SharedPreferences sharedPreferences = context.getSharedPreferences("ljq123",
                Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
        String name = sharedPreferences.getString("name", "");
        int age = sharedPreferences.getInt("age", 1);
        Log.i(TAG, name + " : " +age);
    }
}

聯繫我們

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