I am new to android. I have created SharedPreferences to store a playlist name and song names in the playlist. Now I have to rename the playlist.
And another is: How do I delete the SharedPreferences file (i.e PlaylistName.xml
), when I delete the playlist?
The file access from "/data/data/..." is not reliable since I think it is not the same path for all the phones (Samsung devices namely are different AFAIK).
I prefer the following method which basically 'replicates' the old shared prefs and then clears it. This method does not remove the old shared prefs file itself but more relibale IMHO.
SharedPreferences settingsOld = context.getSharedPreferences(nameOld, Context.MODE_PRIVATE);
SharedPreferences settingsNew = context.getSharedPreferences(nameNew, Context.MODE_PRIVATE);
SharedPreferences.Editor editorNew = settingsNew.edit();
Map<String, ?> all = settingsOld.getAll();
for (Entry<String, ?> x : all.entrySet()) {
if (x.getValue().getClass().equals(Boolean.class)) editorNew.putBoolean(x.getKey(), (Boolean)x.getValue());
else if (x.getValue().getClass().equals(Float.class)) editorNew.putFloat(x.getKey(), (Float)x.getValue());
else if (x.getValue().getClass().equals(Integer.class)) editorNew.putInt(x.getKey(), (Integer)x.getValue());
else if (x.getValue().getClass().equals(Long.class)) editorNew.putLong(x.getKey(), (Long)x.getValue());
else if (x.getValue().getClass().equals(String.class)) editorNew.putString(x.getKey(), (String)x.getValue());
}
editorNew.commit();
SharedPreferences.Editor editorOld = settingsOld.edit();
editorOld.clear();
editorOld.commit();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With