首页 > 解决方案 > 如何在android studio中用户输入时从sharedPreferences中删除某些字符串

问题描述

我使用 android studio 创建一个音乐应用程序,我是一个新手程序员。我创建了一个 sharedPreferences 来存储用户“最喜欢的播放列表”的歌曲,并且存储数据有效,但是当我尝试使用“notifyDataSetChanged”告诉观察者用户想要删除一首歌曲时,它不会改变共享首选项。因此,重新打开应用程序时,歌曲不会从播放列表中删除,仍会显示在 xml 文件夹中。

这是将歌曲添加到 sharedpreferences 的函数:

public void addToFavourite(View view) {
    String songId = view.getContentDescription().toString();
    Song song = SongCollection.songSearchById(songId);
    favourite.add(song);
    Gson gson = new Gson();
    String json = gson.toJson(favourite);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("list", json);
    editor.apply();
    Toast.makeText(this,"Song added", Toast.LENGTH_SHORT).show();
}

这是应在单击删除按钮时删除歌曲的功能:

holder.removebtn.setOnClickListener (new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HomePage.favourite.remove(position);
            notifyDataSetChanged();
        }
    });

标签: javaandroid-studio

解决方案


我发现我实际上并没有更改共享首选项文件,我需要做的就是创建另一个编辑器。


推荐阅读