Android -SharedPreferences

SharedPreferences

 

[功能]

大家在android開發中 一點有這樣的需求 就是需要保存一下與該程序有關的屬性設置的問題

比如:window xp 中 <假設系統盤爲 C:/> 的位置爲: C:\Program Files

 

那麼在android中是怎樣呢? 那就是:SharedPreferences

 

 

既然它是用來保存數據的 那麼一點下面問題:

1. 如何創建

2. 如何加入數據

3. 如何取出數據

 

 

因爲 很多程序都有這個需要 所以自己把該功能集成並列出一些接口函數 以後用的話 會方便很多 這個類名爲:SharedPreferencesHelper

 

[代碼]

1. 以指定名字來創建

 

SharedPreferences sp;
	SharedPreferences.Editor editor;
	
	Context context;
	
	public SharedPreferencesHelper(Context c,String name){
		context = c;
		sp = context.getSharedPreferences(name, 0);
		editor = sp.edit();
	}

 

 

2. 以鍵值<String Key,String Value> 的方式加入數據

 
public void putValue(String key, String value){
		editor = sp.edit();
		editor.putString(key, value);
		editor.commit();
	}

 

 

 

3. 以 String Key 爲索引來取出數據

public String getValue(String key){
		return sp.getString(key, null);
	}

 

 

 

 

4. 如何使用 SharedPreferencesHelper

package com.android.SharedPreferences;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
  
/*
 * to access from: data/data/com.android.SharedPreferences/share_prefs
 */
public class SharedPreferencesUsage extends Activity {
 public final static String COLUMN_NAME ="name";
 public final static String COLUMN_MOBILE ="mobile";
 
 SharedPreferencesHelper sp;
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        sp = new SharedPreferencesHelper(this, "contacts");
        
        //1. to store some value
        sp.putValue(COLUMN_NAME, "Gryphone");
        sp.putValue(COLUMN_MOBILE, "123456789");
        
        
        //2. to fetch the value
        String name = sp.getValue(COLUMN_NAME);
        String mobile = sp.getValue(COLUMN_MOBILE);
        
        TextView tv = new TextView(this);
        tv.setText("NAME:"+ name + "\n" + "MOBILE:" + mobile);
        
        setContentView(tv);
    }
}

 

 

 

5. 其他問題

* 文件存放路徑: 因爲我的這個例子的pack_name 爲:package com.android.SharedPreferences;

  所以存放路徑爲:data/data/com.android.SharedPreferences/share_prefs/contacts.xml

* contacts.xml 的內容爲:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="mobile">123456789</string>
<string name="name">Gryphone</string>
</map>

 

 

* 取出的數據爲:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章