Android:复制/复制SharedPreferences

时间:2011-09-20 23:36:24

标签: android sharedpreferences

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

4 个答案:

答案 0 :(得分:13)

尝试这样的事情:

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

希望这有帮助。

答案 1 :(得分:7)

这是一个也支持字符串集的版本。

public static void copySharedPreferences(SharedPreferences fromPreferences, SharedPreferences toPreferences) {
    copySharedPreferences(fromPreferences, toPreferences, true);
}

public static void copySharedPreferences(SharedPreferences fromPreferences, SharedPreferences toPreferences, boolean clear) {

    SharedPreferences.Editor editor = toPreferences.edit();
    if (clear) {
        editor.clear();
    }
    copySharedPreferences(fromPreferences, editor);
    editor.commit();
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressWarnings({"unchecked", "ConstantConditions"})
public static void copySharedPreferences(SharedPreferences fromPreferences, SharedPreferences.Editor toEditor) {

    for (Map.Entry<String, ?> entry : fromPreferences.getAll().entrySet()) {
        Object value = entry.getValue();
        String key = entry.getKey();
        if (value instanceof String) {
            toEditor.putString(key, ((String) value));
        } else if (value instanceof Set) {
            toEditor.putStringSet(key, (Set<String>) value); // EditorImpl.putStringSet already creates a copy of the set
        } else if (value instanceof Integer) {
            toEditor.putInt(key, (Integer) value);
        } else if (value instanceof Long) {
            toEditor.putLong(key, (Long) value);
        } else if (value instanceof Float) {
            toEditor.putFloat(key, (Float) value);
        } else if (value instanceof Boolean) {
            toEditor.putBoolean(key, (Boolean) value);
        }
    }
}

答案 2 :(得分:4)

Kotlin版本:

fun SharedPreferences.copyTo(dest: SharedPreferences) = with(dest.edit()) {
  for (entry in all.entries) {
    val value = entry.value
    val key = entry.key
    when (value) {
      is String -> putString(key, value)
      is Set<*> -> putStringSet(key, value as Set<String>)
      is Int -> putInt(key, value)
      is Long -> putLong(key, value)
      is Float -> putFloat(key, value)
      is Boolean -> putBoolean(key, value)
    }
  }
  apply()
}

用法:

val prefs1 = getSharedPreferences("test1", MODE_PRIVATE)
val prefs2 = getSharedPreferences("test2", MODE_PRIVATE)

prefs1.copyTo(prefs2)

答案 3 :(得分:1)

我很惊讶这个答案被认为有用。 使用with(dest.edit())时使用this.putString(key, value)指向dest的首选项编辑器,而不是扩展名的编辑器。因此它将价值从复制到相同的命运。 我的意思是,prefs1.copyTo(prefs2)从prefs2复制到prefs2。 您可以通过将with(dest.edit())更改为with(this.edit())来进行测试。 它将以另一种方式起作用。

考虑此修复程序:

fun SharedPreferences.copyTo(dest: SharedPreferences) = with(this.edit()){
   dest.let { 
      for (entry in it.all.entries) {
         val value = entry.value ?: continue
         val key = entry.key
         when (value) {
            is String -> putString(key, value)
            is Set<*> -> putStringSet(key, value as Set<String>)
            is Int -> this.putInt(key, value)
            is Long -> this.putLong(key, value)
            is Float -> this.putFloat(key, value)
            is Boolean -> this.putBoolean(key, value)
            else -> error("Unknown value type: $value")
         }
      }
   }
   this.apply()
}