典型应用场合:
进入某一界面以后,显示默认值(其实这个也可以通过直接在布局文件中指定)
基本点:
1)SharePreferences所生成的文件最终还是以.xml文件的形式存在于/data/data/应用包名/share_prefs/xxx.xml中
2)SharePreferences适合用于存储key-value型的数据
基本使用:
存:
Editor editor = sp.edit();//获取编辑器
editor.putString("name", name);//存储数据(还没进入进入文件)
editor.putString("phone", phone);
editor.putString("email", email);
editor.commit();//提交修改(类似于事务)
取:
sp = getSharedPreferences("data", MODE_PRIVATE);//获取对象,默认指向当前应用.文件名为data.xml,模式为私有
// sp = getPreferences(MODE_PRIVATE);//这时候生成的文件名为MainActivity.xml
et_name.setText(sp.getString("name", ""));
et_phone.setText(sp.getString("phone", ""));
et_email.setText(sp.getString("email", ""));
解析:为什么我们使用getPreferences(MODE_PRIVATE)时生成的文件名为MainActivity.xml呢??如下图所示:
其实在之前的博客我就提过,这种很类似的函数,在底层实现的时候,很可能就是你调我,我调你的。。。事实胜于雄辩,源码面前无秘密。。现在我们就去看看Android源码中这两个函数就知道了。。。
源码分析:
先看getSharedPreferences(String name, int mode):
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return mBase.getSharedPreferences(name, mode);
}
接下来,看一下getPreferences(int mode):
/**
* Retrieve a {@link SharedPreferences} object for accessing preferences
* that are private to this activity. This simply calls the underlying
* {@link #getSharedPreferences(String, int)} method by passing in this activity's
* class name as the preferences name.
*
* @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
* operation, {@link #MODE_WORLD_READABLE} and
* {@link #MODE_WORLD_WRITEABLE} to control permissions.
*
* @return Returns the single SharedPreferences instance that can be used
* to retrieve and modify the preference values.
*/
public SharedPreferences getPreferences(int mode) {
return getSharedPreferences(getLocalClassName(), mode);
}
getPreferences(int mode)方法中用到了getLocalClassName()这个函数,其实这个函数不需要看它的源码,单单是看它的名字就知道他是干什么的了:获取当前Activity的名字。。。。不过既然看到这里了,我们还是去看一下它的源码都是怎么写的吧。
/**
* Returns class name for this activity with the package prefix removed.
* This is the default name used to read and write settings.
*
* @return The local class name.
*/
public String getLocalClassName() {
final String pkg = getPackageName();
final String cls = mComponent.getClassName();//获取长类名:包名+类名
int packageLen = pkg.length();
if (!cls.startsWith(pkg) || cls.length() <= packageLen
|| cls.charAt(packageLen) != '.') {
return cls;
}
return cls.substring(packageLen+1);//截取包名后面的那一段.也就是类名
}
例子:
1、MainActivity
package com.example.sharepreferencetest;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_phone;
private EditText et_email;
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et_name = (EditText) findViewById(R.id.nameET);
et_phone = (EditText) findViewById(R.id.phoneET);
et_email = (EditText) findViewById(R.id.emailET);
sp = getSharedPreferences("data", MODE_PRIVATE);//获取对象,默认指向当前应用.文件名为data.xml,模式为私有
// sp = getPreferences(MODE_PRIVATE);//这时候生成的文件名为MainActivity.xml
et_name.setText(sp.getString("name", ""));
et_phone.setText(sp.getString("phone", ""));
et_email.setText(sp.getString("email", ""));
}
public void onClick(View view){
String name = et_name.getText().toString();
String phone = et_phone.getText().toString();
String email = et_email.getText().toString();
Editor editor = sp.edit();//获取编辑器
editor.putString("name", name);//存储数据(还没进入进入文件)
editor.putString("phone", phone);
editor.putString("email", email);
editor.commit();//提交修改(类似于事务)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
2、main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名" />
<EditText
android:id="@+id/nameET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="电话" />
<EditText
android:id="@+id/phoneET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="邮箱" />
<EditText
android:id="@+id/emailET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="保存为默认" />
</LinearLayout>
效果图:
生成的data.xml文件的内容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="email">1019648568@qq.com</string>
<string name="phone">13675173829</string>
<string name="name">hjd</string>
</map>
源码下载:http://download.csdn.net/detail/caihongshijie6/7615023