Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

java - How to transfer sharedpreferences file from internal storage to external storage?

How to copy sharedpreferences to external storage keeping xml format, so later it could be possible to share preferences.

Tried to read sharedpreferences and save as a string into file, created JSON type of a string, but I need an xml. Thought of traversing through app's internal storage and copy file and put it in external storage, but that could be too complex.

Just really would want to know if there is an easy and sensible way to transfer `sharedpreferences.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use this code,

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();
}

and to retrive use this,

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();
}

NOTE You can handle only String type preferences with this code,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...