Android:复制/复制SharedPreferences

17

有没有一种方法可以复制或复制SharedPreference?还是我需要从一个SharedPreference获取每个变量,然后将它们放到另一个SharedPreference中?


我所知道的唯一方法是从一个变量中获取每个变量并将它们放入另一个变量中。但是SharedPrefs存储为xml文件,我想您可能可以以某种新名称复制整个文件并粘贴它。这种方法可能需要root设备才能够将输入和输出流设置到您的应用程序SharedPreferences文件夹中。 - FoamyGuy
1
你为什么想要复制共享首选项?更详细地解释一下你想要实现什么,这将有助于我们提供一个合适的答案。 - Kenny
1
我的应用程序将其变量存储在共享首选项中。我有大约50个不断变化的变量,换句话说,它们不能在应用程序中硬编码。我希望能够将这些变量设置在一旁,以便应用程序用户可以启动新会话,然后在两者之间进行切换。我想我可以忍受并将所有变量写入另一个共享首选项,但如果我只能这样做:savedSharedPreference = sharedPreference,那就容易多了。哈哈 - cerealspiller
3个回答

18
尝试类似这样的东西:
//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
/* 用户设置在“设置活动”中被持久化 */ if (SystemUtils.getSDKVersion() > Build.VERSION_CODES.FROYO) { editor.apply(); } else { editor.commit(); } - Andrew Mackenzie

13
Kotlin版本:
fun SharedPreferences.copyTo(dest: SharedPreferences) = with(dest.edit()) {
  entry.entries.forEach { entry ->
    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 -> putInt(key, value)
      is Long -> putLong(key, value)
      is Float -> putFloat(key, value)
      is Boolean -> putBoolean(key, value)
      else -> error("Unknown value type: $value")
    }
  }
  apply()
}

使用方法:

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

prefs1.copyTo(prefs2)

8
这里有一个支持字符串集的版本。
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);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接