gpt4 book ai didi

android - 一次编写整个 Android shared_preferences.xml

转载 作者:行者123 更新时间:2023-11-30 03:03:48 24 4
gpt4 key购买 nike

是否可以一次写一个完整的shared_preferences.xml?

我想实现一种设置导入/导出,所以我需要在不丢失 xml 标签的情况下读取和写入整个文件。

读取文件很容易,但是当我写入我的值(使用 PrintWriter)时,存储在内存中的旧值会在几秒钟后覆盖它们。

如果不使用首选项编辑器编写单个值,我能做些什么来防止这种情况。

最佳答案

现在我从一个设计得像Android自己的preferences.xml的文件中读取它,然后像这样在我自己的函数中依次写入它:

public static void preferencesImport(String PreferenceFilepath) {
preferencesImportPreferenceFilepath = PreferenceFilepath;
try {
// Parsing
// see http://theopentutorials.com/tutorials/android/xml/android-simple-xml-dom-parser/
XMLParserHelper parser = new XMLParserHelper(); // reference to described XMLDOMParser helper class
BufferedInputStream stream;
try {
stream = new BufferedInputStream(new FileInputStream(preferencesImportPreferenceFilepath));
org.w3c.dom.Document doc = parser.getDocument(stream);

// string value
NodeList nodeListString = doc.getElementsByTagName("string");
for (int i = 0; i < nodeListString.getLength(); i++) {
Element eString = (Element) nodeListString.item(i);
Pref.setString(eString.getAttribute("name"), eString.getTextContent()); // Own getter/setter -> use Android's preference manager instead in similar way
}

// repeat code above for boolean, long, int, float values

stream.close();
} catch (IOException e1) {
// output IOException
} catch (Throwable t1) {
// output Throwable1
}
writer.close();
} catch (Throwable t2) {
// output Throwable2
}
}

关于android - 一次编写整个 Android shared_preferences.xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22143141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com