如何将sharedpreferences
复制到保留xml format
的外部存储空间,以便以后可以共享首选项。
尝试阅读sharedpreferences
并将string
保存到文件中,创建JSON
类型的string
,但我需要xml
。考虑遍历应用程序的内部存储和复制文件并将其放在外部存储中,但这可能过于复杂。
真的很想知道是否有一种简单而明智的方式来传递`sharedpreferences。
答案 0 :(得分:0)
使用此代码,
SharedPreferences preferences=this.getSharedPreferences("com.example.application", Context.MODE_PRIVATE);
Map<String,?> keys = preferences.getAll();
Properties properties = new Properties();
for(Map.Entry<String,?> entry : keys.entrySet()){
String key = entry.getKey();
String value = entry.getValue().toString();
properties.setProperty(key, value);
}
try {
File file = new File("externalPreferences.xml");
FileOutputStream fileOut = new FileOutputStream(file);
properties.storeToXML(fileOut, "External Preferences");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
并且要反复使用它,
try {
File file = new File("externalPreferences.xml");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.loadFromXML(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
SharedPreferences.Editor editor = preferences.edit();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
editor.putString(key, value);
editor.commit();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
注意您只能使用此代码处理字符串类型首选项
答案 1 :(得分:0)
对于文件中的负载共享首选项,请尝试此
private fun loadSharedPreferences(src: File, sharedPreferences : SharedPreferences) {
try{
var fileInput : FileInputStream = FileInputStream(src)
val properties : Properties = Properties()
properties.loadFromXML(fileInput)
fileInput.close()
val enuKeys = properties.keys()
val editor = sharedPreferences.edit()
while (enuKeys.hasMoreElements()){
var key = enuKeys.nextElement() as String
var value = properties.getProperty(key)
when {
key.contains("string",true) -> { //in my case the key of a String contain "string"
editor.putString(key, value)
}
key.contains("int", true) -> { //in my case the key of a Int contain "int"
editor.putInt(key, value.toInt())
}
key.contains("boolean", true) -> { // //in my case the key of a Boolean contain "boolean"
editor.putBoolean(key, value.toBoolean())
}
}
editor.apply();
}
}catch ( e : FileNotFoundException) {
e.printStackTrace();
} catch ( e : IOException) {
e.printStackTrace();
}
}