我正在构建一个音乐播放器,即使我的应用程序关闭后我想要存储我的播放列表,并在应用程序启动时检索回来。 我现在能够在Array List中获得播放列表。 请帮忙..
答案 0 :(得分:0)
要在应用程序关闭时保存某些内容,请覆盖活动或片段中的onPause方法,然后从ArrayList中保存播放列表,可能是在sqlite数据库,文件或共享首选项中。 要检索它,请在onCreate方法中编写代码,然后就可以检索保存的数据。
我没有处理sqlite,但如果你想
,那么你就是一个共享偏好代码class Playlist {
private final String fileName = "myPlaylist";
private SharedPreferences myPlaylist;
private SharedPreferences.Editor myEditor;
Playlist() {
myPlaylist = getSharedPreferences(fileName, 0);
myEditor = myPlaylist.edit();
}
public void save(ArrayList<String> mySongs){
// Save the size so that you can retrieve the whole list later
myEditor.putInt("listSize", mySongs.size());
for(int i = 0; i < mySongs.size(); i++){
// Save each song with its index in the list as a key
myEditor.putString(String.valueOf(i), mySongs.get(i));
}
myEditor.commit();
}
public ArrayList<String> load() {
// Create new array to be returned
ArrayList<String> savedSongs = new ArrayList<String>();
// Get the number of saved songs
int numOfSavedSongs = myPlaylist.getInt("listSize", 0);
// Get saved songs by their index
for (int i = 0; i < numOfSavedSongs; i++) {
savedSongs.add(myPlaylist.getString(String.valueOf(i)));
}
return savedSongs;
}
}
抱歉,如果代码包含错误,但我没有测试它。希望它有所帮助