I'm making a "Recently played" playlist in my music app. I have created a database for storing the info related to songs. What my current code does is whenever I play a song it add it the database and I can successfully display it. But the problem is when I play the same song twice, the database isn't updating. Example, I played song A,song B, song C, song D respectively. Then it will display song A, song B, song C, song D. But if i play song A,song B, song C, song D and song B again respectively. Then it again displays the same(song A, song B, song C, song D). But what I want is: song A, song C, song D, song B. It should update and show the latest song played, that is what i meant. I can't figure out how to do it.
Code for table creation:
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_ARTIST + " TEXT,"
+ KEY_DURATION + " INTEGER,"
+ KEY_ART + " TEXT"
+ ");";
sqLiteDatabase.execSQL(CREATE_TABLE);
}
Code for getting and displaying the data :
public ArrayList<SongInfoModel> getRecentlyPlayed(){
ArrayList<SongInfoModel> rpList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor.moveToFirst()){
do{
long id = cursor.getLong(0);
String SongName = cursor.getString(1);
String artistName = cursor.getString(2);
long dur = cursor.getLong(3);
String Art = cursor.getString(4);
SongInfoModel sh = new SongInfoModel(id,SongName,artistName,dur,null,Art);
rpList.add(sh);
}while (cursor.moveToNext());
}
return rpList;
Code for adding data:
public void addSong(SongInfoModel songInfoModel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, songInfoModel.getSongID());
values.put(KEY_NAME, songInfoModel.getSongName());
values.put(KEY_ARTIST, songInfoModel.getArtistName());
values.put(KEY_DURATION, songInfoModel.getDuration());
values.put(KEY_ART, songInfoModel.getAlbumIDArtwork());
db.insert(TABLE_NAME,null,values);
db.close();
}