PreferenceManager[Android]
SharedPreference是Android提供的一种轻量级的数据存储方式,主要用来存储一些简单的配置信息,其以键值对的方式存储,使得我们能很方便进行读取和存入
SharedPreference 文件保存在/data/data/<package name>/shared_prefs 路径下
通过Activity自带的getSharedPreferences方法,可以得到SharedPreferences对象。
public abstract SharedPreferences getSharedPreferences (String name, int mode);
name:表示保存后 xml 文件的名称
mode:表示 xml 文档的操作权限模式(私有,可读,可写),使用0或者MODE_PRIVATE作为默认的操作权限模式。
1.数据读取:
通过SharedPreferences对象的键key可以获取到对应key的键值。对于不同类型的键值有不同的函数:getBoolean,getInt,getFloat,getLong.
public abstract String getString (String key, String defValue);
2.数据存入:
数据的存入是通过SharedPreferences对象的编辑器对象Editor来实现的。通过编辑器函数设置键值,然后调用commit()提交设置,写入xml文件
public abstract SharedPreferences.Editor edit ();
public abstract SharedPreferences.Editor putString (String key, String value);
public abstract boolean commit ();
<?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">
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
</LinearLayout>
package com.android.test;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class TestSharedPreferences extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences mSharedPreferences = getSharedPreferences("TestSharedPreferences", 0);
// SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int counter = mSharedPreferences.getInt("counter", 0);
TextView mTextView = (TextView)findViewById(R.id.textview);
mTextView.setText("This app has been started " + counter + " times.");
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putInt("counter", ++counter);
mEditor.commit();
}
}
数据的存入必须通过SharedPreferences对象的编辑器对象Editor来实现,存入(put)之后与写入数据库类似一定要commit!

浙公网安备 33010602011771号