
我在很多地方看到将SharedPreferences文件复制到SD卡是一个问题,因为每个制造商都将它放在其他地方.
无论文件位于何处,我都想在SD卡上备份.
有没有办法做到这一点?
解决方法:
SharedPreferences接口包含一个名为getAll()的方法,该方法返回带有键值对的映射.因此,我只是序列化从此方法返回的映射,而不是复制文件本身,然后将其检索回来.
一些代码:
private boolean saveSharedPreferencesTofile(file dst) { boolean res = false; ObjectOutputStream output = null; try { output = new ObjectOutputStream(new fileOutputStream(dst)); SharedPreferences pref = getSharedPreferences(prefname, MODE_PRIVATE); output.writeObject(pref.getAll()); res = true; } catch (fileNotFoundException e) { e.printstacktrace(); } catch (IOException e) { e.printstacktrace(); }finally { try { if (output != null) { output.flush(); output.close(); } } catch (IOException ex) { ex.printstacktrace(); } } return res;}@SuppressWarnings({ "unchecked" })private boolean loadSharedPreferencesFromfile(file src) { boolean res = false; ObjectinputStream input = null; try { input = new ObjectinputStream(new fileinputStream(src)); Editor prefEdit = getSharedPreferences(prefname, MODE_PRIVATE).edit(); prefEdit.clear(); Map<String, ?> entrIEs = (Map<String, ?>) input.readobject(); for (Entry<String, ?> entry : entrIEs.entrySet()) { Object v = entry.getValue(); String key = entry.getKey(); if (v instanceof Boolean) prefEdit.putBoolean(key, ((Boolean) v).booleanValue()); else if (v instanceof float) prefEdit.putfloat(key, ((float) v).floatValue()); else if (v instanceof Integer) prefEdit.putInt(key, ((Integer) v).intValue()); else if (v instanceof Long) prefEdit.putLong(key, ((Long) v).longValue()); else if (v instanceof String) prefEdit.putString(key, ((String) v)); } prefEdit.commit(); res = true; } catch (fileNotFoundException e) { e.printstacktrace(); } catch (IOException e) { e.printstacktrace(); } catch (ClassNotFoundException e) { e.printstacktrace(); }finally { try { if (input != null) { input.close(); } } catch (IOException ex) { ex.printstacktrace(); } } return res;}我希望我能帮助别人,如果有什么不对的地方请告诉我.
埃拉德
总结以上是内存溢出为你收集整理的android – 如何将SharedPreferences备份到SD卡?全部内容,希望文章能够帮你解决android – 如何将SharedPreferences备份到SD卡?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)