Search code examples
androiddatabasecursor

Database size increases on every launch of application


I have a database .Because I cant check for add/remove of song in device , I am updating my Table for songs on every launch of my application .Therefore I am getting duplicate of what ever already there in database.This is why my database size is increasing on every launch.My question is how to insert if any new songs are added and removed the song from database if any old song deleted.

 Cursor cursorSong = this.managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
 projection,selection, null, null);
while (cursor.moveToNext()) {

                String sdata = cursor.getString(0);
                            ContentValues initialValues = new ContentValues();

                initialValues.put(KEY_PATH, sdata);

                mDB.insert(DataHelper.SONG_TABLE, null,initialValues);
            }

Solution

  • This is something like syncing your application DB with the songs on the phone.

    To Remove deleted songs from DB: If you are maintaining file path of the song, check whether the file exists in that location. If the file doesn't exist, it is that the file/song is deleted. So, delete this entry in DB.

    To add new entry in DB: Before adding new entry, check file path of new file in existing DB. If path already exists, do not insert again.

    By doing this, you will be deleting unwanted entries in DB, and DB maintains only existing files on the device.