SharedPreferences的使用

本文介绍SharedPreferences及PreferenceActivity、PreferenceFragment。

1、SharedPreferences简单使用示例

public class MainActivity extends Activity {
	private static final String TAG = MainActivity.class.getSimpleName();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setContentView(R.layout.activity_main);
		//all apps sharing the same user ID
		SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		//save 5 kinds of datas: boolean,int,long,float,String
		editor.putBoolean("isMan", true);
		editor.putFloat("weight", 68f);
		editor.putInt("age", 25);
		editor.putLong("salary", 10000L);
		editor.putString("name", "Victor");
		Set<String> relatives = new HashSet<String>();
		editor.putStringSet("relatives", relatives);
//		editor.apply();//asynchronous,main thread
		long start = SystemClock.elapsedRealtime();
		editor.commit();
		Log.i(TAG, "commit:"+(SystemClock.elapsedRealtime()-start)+"ms");
	}
	public void onClick(View v){
		switch (v.getId()) {
		case R.id.btn:
			Log.i(TAG, "getLocalClassName()="+getLocalClassName());
			SharedPreferences sp = getSharedPreferences(getLocalClassName(), Context.MODE_PRIVATE);
			sp.getBoolean("isMan", false);
			sp.getFloat("weight", 60);
			sp.getInt("age", 16);
			sp.getLong("salary", 6000L);
			sp.getString("name", "none");
			sp.getStringSet("relatives", null);
			Map<String, ?> map = sp.getAll();
			if(sp.contains("salary")){
				long salary = (Long) map.get("salary");
				Log.i(TAG, "contains:"+salary);
			}
		}
	}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get"
        android:onClick="onClick"/>
</LinearLayout>

2、PreferenceActivity、PreferenceFragment使用示例

1) MyFragmentPreferenceActivity.java

public class MyFragmentPreferenceActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
	private static final String TAG = MyFragmentPreferenceActivity.class.getSimpleName();
	@Override
	public void onBuildHeaders(List<Header> target) {
		super.onBuildHeaders(target);
		loadHeadersFromResource(R.xml.preferenceheaders, target);
		//getPackageName()+"_preferences"
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		sharedPreferences.registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if(key.equals("CheckBox")){
			boolean value = sharedPreferences.getBoolean(key, false);
			Log.i(TAG, "CheckBox:"+value);
		}else if(key.equals("ListPreference")){
			String value = sharedPreferences.getString(key, null);
			Log.i(TAG, "ListPreference:"+value);
		}else if(key.equals("MultiSelectListPreference")){
			Set<String> values = sharedPreferences.getStringSet("MultiSelectListPreference", null);
			Log.i(TAG, "MultiSelectListPreference:"+values);
		}else if(key.equals("RingtonePreference")){
			String value = sharedPreferences.getString("RingtonePreference", null);
			//content://media/internal/audio/media/49
			Log.i(TAG, "RingtonePreference:"+value);
		}
	}
}

2) preferenceheaders.xml

preference-headers作为顶级标签,包含多个header

<?xml version="1.0" encoding="utf-8"?>
<preference-headers
    xmlns:android="http://schemas.android.com/apk/res/android">
    <header
        android:fragment="com.qinuli.buttontest2.MyPreferenceFragment"
        android:title="My header"
        android:icon="@drawable/ic_launcher"
        android:summary="description of header"/>
    <header
        android:title="Intent"
        android:summary="launch an intent">
        <intent android:action="android.settings.DISPLAY_SETTINGS"/>
    </header>
</preference-headers>

3) MyPreferenceFragment.java

public class MyPreferenceFragment extends PreferenceFragment {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.userpreferences);
	}
}

4) userpreferences.xml

PreferenceScreen作为顶级标签,包含多个PreferenceCategory

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="Category1">
        <CheckBoxPreference
            android:key="CheckBox"
            android:title="CheckBox"
            android:summaryOn="laugh"
            android:summaryOff="cry"
            android:defaultValue="true"/>
        <ListPreference
            android:key="ListPreference"
            android:title="ListPreference"
            android:summary="many things, but you can only choose one"
            android:entries="@array/mylist"
            android:entryValues="@array/myvalues"/>
        <PreferenceScreen
            android:title="PreferenceScreen"
            android:summary="child screen">
            <SwitchPreference
	            android:key="SwitchPreference"
	            android:title="SwitchPreference"
	            android:summaryOn="Active"
	            android:summaryOff="Deactive"
	            android:switchTextOn="Good"
	            android:switchTextOff="Bad"/>
        </PreferenceScreen>
    </PreferenceCategory>
    <PreferenceCategory
        android:title="Category2">
        <EditTextPreference
            android:key="EditText"
            android:title="EditText"
            android:summary="input something"
            android:defaultValue="fantastic job!"/>
        <MultiSelectListPreference
            android:key="MultiSelectListPreference"
            android:title="MultiSelectListPreference"
            android:summary="you can choose as many as you want"
            android:entries="@array/mylist"
            android:entryValues="@array/myvalues"/>
        <RingtonePreference
            android:key="RingtonePreference"
            android:title="RingtonePreference"
            android:summary="select your favourite ringtone"/>
    </PreferenceCategory>
    <PreferenceScreen
        android:title="Intent"
        android:summary="launch an intent">
        <intent android:action="android.settings.WIFI_SETTINGS"/>
    </PreferenceScreen>
</PreferenceScreen>

5) strings.xml

ListPreference引用的资源

<resources>

    <string name="app_name">ButtonTest2</string>
	<string-array name="mylist">
	    <item >good</item>
	    <item >great</item>
	    <item >nice</item>
	    <item >fine</item>
	    <item >beautiful</item>
	    <item >pretty</item>
	</string-array>
	<string-array name="myvalues">
	    <item >_GOOD</item>
	    <item >_GREAT</item>
	    <item >_NICE</item>
	    <item >_FINE</item>
	    <item >_BEAUTIFUL</item>
	    <item >_PRETTY</item>
	</string-array>
</resources>

时间: 2024-10-26 01:01:10

SharedPreferences的使用的相关文章

SharedPreferences 源码分析

我们先看一下SharedPreferences (下文用 SP 简写替代)的用法. SharedPreferences preferences = getSharedPreferences("name", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("key", "value"); editor.comm

安卓-SharedPreferences和Editor保存数据

SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据. 在做连连看游戏的时候,需要保存游戏进度,所以稍微用了一下,这里做个小结. 我的做法是,首先给出如下定义: private SharedPreferences sp; private static String MY_APP="MYAPP"; 然后再写两个方法,执行数

Android -- Sharedpreferences

//采用android sharedpreferences 进行数据的保存读取 SharedPreferences sharedPreferences; private final String mediaShare = "test"; private void InitMediaSharePreference() { sharedPreferences = this.getSharedPreferences(mediaShare, MODE_PRIVATE); } //写入 Stri

SharedPreferences 使用

1,获取到SharedPreferences 2,编辑SharedPreferences SharedPreferences.Editor 3,提交 commit() 4,获取get**** package com.example.listactivity; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Vie

SharedPreferences作业

安卓作业: 使用SharedPreference将姓名和年龄信息保存到文件,然后再读取 1.主要xml文件代码: <EditText android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入姓名:"/> <EditText android:i

使用SharedPreferences将姓名和年龄信息保存在文件中,并读取信息

第一个是XML文件: 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:id="@+id/activi

[Android]数据篇 --- SharedPreferences

转载请标注:转载于http://www.cnblogs.com/Liuyt-61/p/6637515.html --------------------------------------------------------------- Android数据的四种存储方式: 1.SharedPreferences 2.SQLite 3.Content Provider 4.File ----------------------分割线--------------------------------

【Mark】Android应用开发SharedPreferences存储数据的使用方法

Android应用开发SharedPreferences存储数据的使用方法 SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据. 1.使用SharedPreferences保存数据方法如下: //实例化SharedPreferences对象(第一步) SharedPreferences mySharedPreferences=

android-数据存储之SharedPreferences

数据存储:SharedPreferences 一.基础概要 1.说明 1>主要用于存储单一小数据: 2>存储类型:boolean.float.String.long.int 3>数据保存路径:/data/data/packageName/shared_prefs/xxx.xml 4>应用卸载时会删除此数据(实际上---包名文件夹下所有数据在应用卸载是都会删除"packageName") 5>可以设置操作数据的权限,eg.只能是当前应用读取--MODE_PR

android API文档查询---context、toast、SharedPreferences

/*查阅api ---context1.abstract AssetManager     getAssets() Returns an AssetManager instance for the application's package. 得到assets目录下的资源 2.abstract File     getCacheDir() Returns the absolute path to the application specific cache directory on the fi