SharedPreferences的创建
有下边3种方式,一种是用系统默认的,一种自己起个名字
PreferenceManager.getDefaultSharedPreferences(context)
context.getSharedPreferences("name", Context.MODE_PRIVATE);
activity.getPreferences(Context.MODE_PRIVATE)
那么这个文件在哪里?
/data/data/"+getPackageName()+"/shared_prefs/name.xml
系统默认生成的那个文件名字是这样的context.getPackageName() + "_preferences"
public static SharedPreferences getDefaultSharedPreferences(Context context) {
return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
getDefaultSharedPreferencesMode());
}
private static String getDefaultSharedPreferencesName(Context context) {
return context.getPackageName() + "_preferences";
}
activity下的名字,就是这个activity的类名,不带路径的
/**
* 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.
*/
public SharedPreferences getPreferences(int mode) {
return getSharedPreferences(getLocalClassName(), mode);
}
/**
* 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.
*/
@NonNull
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);
}
看一下存储的文件长啥样
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<int name="key2" value="2222" />
<float name="key5" value="22.4" />
<long name="key4" value="3333" />
<string name="key1">aaaa</string>
<boolean name="key3" value="true" />
</map>
打印xml文件的方法
try {
File bb=new File("/data/data/"+getPackageName()+"/shared_prefs/bbb.xml");
FileInputStream fileInputStream=new FileInputStream(bb);
BufferedReader bReader=new BufferedReader(new InputStreamReader(fileInputStream));
StringBuffer sBuffer=new StringBuffer();
String line;
while((line=bReader.readLine())!=null) {
sBuffer.append(line);
}
System.out.println("===file======="+sBuffer.toString());
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
几个问题
1. sp如果想要改名字咋办
这个其实比较简单,使用File的rename即可
File file=new File("/data/data/"+getPackageName()+"/shared_prefs/aaa.xml");
boolean result=file.renameTo(new File("/data/data/"+getPackageName()+"/shared_prefs/bbb.xml"));
2. 如果要把一个sp的数据复制到另一个sp咋办
关键是取出来的value,我们得先判断它的类型才能操作比较麻烦。
所以就把key和value都取出来放到集合里,然后根据value的类型,用对应的put方法存到新的sp里边
public static void copyOldSP2NewSP(Context context) {
SharedPreferences sp_old= context.getSharedPreferences("xxxx", 0);
if(sp_old.getAll().size()==0) {
Log.d(TAG, "copyOldSP2NewSP ========old have been cleared.");
return;
}
SharedPreferences sp_new= PreferenceManager.getDefaultSharedPreferences(context);
ArrayList<String> listkey=new ArrayList<String>();
ArrayList<Object> listValue=new ArrayList<Object>();
try {
Map<String, ?> map=sp_old.getAll();
Set<String> set=map.keySet();
Iterator<String> keys= set.iterator();
//StringBuffer sBuffer=new StringBuffer();
while(keys.hasNext()) {
String key=keys.next();
//sBuffer.append(key+" , ");
listkey.add(key);
}
//System.out.println("keys====="+sBuffer.toString());
Collection<?> collection= map.values();
//StringBuffer sBuffer2=new StringBuffer();
Iterator<?> values= collection.iterator();
while (values.hasNext()) {
Object value=values.next();
listValue.add(value);
//sBuffer2.append(value+" , ");
}
//System.out.println("values==============="+sBuffer2.toString());
Editor editor=sp_new.edit();
for(int i=0;i<listkey.size();i++) {
String key=listkey.get(i);
Object value=listValue.get(i);
save(editor, key, value);
}
editor.commit();
//clear old sharedPreference
sp_old.edit().clear().commit();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "copyOldSP2NewSP error==="+e.getMessage());
}
}
save方法如下
private void save(Editor editor,String key,Object value) {
if (value instanceof Integer) {
editor.putInt(key, (Integer) value); }
else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value); }
else if (value instanceof String) {
editor.putString(key, (String) value); }
else if (value instanceof Float) {
editor.putFloat(key, (Float) value); }
else if (value instanceof Long) {
editor.putLong(key, (Long) value);
}
}
最后说下
如下,我们哪怕新弄一个xxxx的sp,那么keyset也不是null,所以可以不用做空判断,只需要判断size是否是0即可。
getSharedPreferences("xxxx", 0).getAll().keySet()
studio或者eclipse的日志打印,需要了解下,它一次能打印的字符串最长就4035个,如果你要打印的string长度有个1万,那么只显示4035个,