安卓:复制/复制共享preferences [英] Android: Copy/Duplicate SharedPreferences

查看:203
本文介绍了安卓:复制/复制共享preferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法复制或复制共享preference?或将我需要从一个获得每个变量,然后把它们放到另一个?

Is there a way to copy or duplicate a SharedPreference? Or will I need to get each variable from one and then put them in another?

推荐答案

尝试是这样的:

//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.

希望这有助于。

这篇关于安卓:复制/复制共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆