如何在Android中重命名现有的共享首选项文件

Bab*_*heb 2 android sharedpreferences

我是android的新手.我创建了SharedPreferences以在播放列表中存储播放列表名称和歌曲名称.现在我必须重命名播放列表.

另一个是:PlaylistName.xml当我删除播放列表时,如何删除SharedPreferences文件(即)?

Bab*_*heb 6

最后,我能够重命名共享首选项文件.

作为参考,在我的上下文中代码是:

String fileName=etlistName.getText().toString();
File f=new File("/data/data/eywa.musicplayer/shared_prefs/"+PlayListName+".xml");
f.renameTo(new File("/data/data/eywa.musicplayer/shared_prefs/"+fileName+".xml"));

SharedPreferences mySharedPreferences=getSharedPreferences("list_of_playlist",Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.remove(PlayListName);
editor.putString(fileName, fileName);
editor.commit();
PlayListName=fileName;
Run Code Online (Sandbox Code Playgroud)

并删除playlistName.xml:

for (int i=0; i<selectedItems.size();i++)
{//remove the songs names from the playlist
    SharedPreferences sp=getSharedPreferences(selectedItems.get(i),Activity.MODE_PRIVATE);
    SharedPreferences.Editor ed=sp.edit();
    ed.clear();
    ed.commit();
    //remove the play list name from the list_of_playlist
    SharedPreferences.Editor editor = mainPref.edit();
    editor.remove(selectedItems.get(i));
    //delete .xml file
    File f=new File("/data/data/eywa.musicplayer/shared_prefs/"+selectedItems.get(i)+".xml");
    if(f.delete())
        System.out.println("file deleted")
    editor.commit();
}
selectedItems.clear();
Run Code Online (Sandbox Code Playgroud)


Ash*_*usa 6

从“ / data / data / ...”访问文件不可靠,因为我认为所有电话的路径都不相同(三星设备即为不同的AFAIK)。

我更喜欢以下方法,该方法基本上是“复制”旧的共享首选项,然后将其清除。此方法不会删除旧的共享prefs文件本身,而是会删除恕我直言的恕我直言。

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(); 
Run Code Online (Sandbox Code Playgroud)