Android:复制/复制SharedPreferences

有没有办法复制或复制SharedPreference?或者我需要从一个变量中获取每个变量然后将它们放入另一个变量中?

解决方法

尝试像这样的东西:
//sp1 is the shared pref to copy to
SharedPreferences.Editor ed = sp1.edit(); 
SharedPreferences sp = Sp2; //The shared preferences to copy from
ed.clear(); // This clears the one we are copying to,but you don't necessarily need to do that.
//Cycle through all the entries in the sp
for(Entry<String,?> entry : sp.getAll().entrySet()){ 
 Object v = entry.getValue(); 
 String key = entry.getKey();
 //Now we just figure out what type it is,so we can copy it.
 // Note that i am using Boolean and Integer instead of boolean and int.
 // That's because the Entry class can only hold objects and int and boolean are primatives.
 if(v instanceof Boolean) 
 // Also note that i have to cast the object to a Boolean 
 // and then use .booleanValue to get the boolean
    ed.putBoolean(key,((Boolean)v).booleanValue());
 else if(v instanceof Float)
    ed.putFloat(key,((Float)v).floatValue());
 else if(v instanceof Integer)
    ed.putInt(key,((Integer)v).intValue());
 else if(v instanceof Long)
    ed.putLong(key,((Long)v).longValue());
 else if(v instanceof String)
    ed.putString(key,((String)v));         
}
ed.commit(); //save it.

希望这可以帮助.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...