GC support for playcounts

This commit is contained in:
Adrian Ulrich 2014-04-16 22:19:18 +02:00
parent 37e26c87be
commit d8093e4450

View File

@ -18,6 +18,7 @@
package ch.blinkenlights.android.vanilla;
import android.content.Context;
import android.content.ContentResolver;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
@ -42,9 +43,11 @@ public class PlayCountsHelper extends SQLiteOpenHelper {
private static final String INDEX_TYPE_CREATE = "CREATE INDEX idx_type ON "+TABLE_PLAYCOUNTS
+ " (type);";
private Context ctx;
public PlayCountsHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
ctx = context;
}
@Override
@ -68,6 +71,7 @@ public class PlayCountsHelper extends SQLiteOpenHelper {
SQLiteDatabase dbh = this.getWritableDatabase();
dbh.execSQL("INSERT OR IGNORE INTO "+TABLE_PLAYCOUNTS+" (type, type_id, playcount) VALUES ("+MediaUtils.TYPE_SONG+", "+id+", 0);"); // Creates row if not exists
dbh.execSQL("UPDATE "+TABLE_PLAYCOUNTS+" SET playcount=playcount+1 WHERE type="+MediaUtils.TYPE_SONG+" AND type_id="+id+";");
performGC(dbh, MediaUtils.TYPE_SONG);
dbh.close();
}
@ -77,14 +81,45 @@ public class PlayCountsHelper extends SQLiteOpenHelper {
public ArrayList<Long> getTopSongs() {
ArrayList<Long> payload = new ArrayList<Long>();
SQLiteDatabase dbh = this.getReadableDatabase();
Cursor c = dbh.rawQuery("SELECT type_id FROM "+TABLE_PLAYCOUNTS+" WHERE type="+MediaUtils.TYPE_SONG+" ORDER BY playcount DESC limit 4096", null);
Cursor cursor = dbh.rawQuery("SELECT type_id FROM "+TABLE_PLAYCOUNTS+" WHERE type="+MediaUtils.TYPE_SONG+" ORDER BY playcount DESC limit 4096", null);
while (c.moveToNext()) {
payload.add(c.getLong(0));
while (cursor.moveToNext()) {
payload.add(cursor.getLong(0));
}
c.close();
cursor.close();
return payload;
}
/**
* Picks a random amount of 'type' items from the provided DBH
* and checks them against Androids media database.
* Items not found in the media library are removed from the DBH's database
*/
private int performGC(SQLiteDatabase dbh, int type) {
ArrayList<Long> toCheck = new ArrayList<Long>(); // List of songs we are going to check
QueryTask query; // Reused query object
Cursor cursor; // recycled cursor
int removed = 0; // Amount of removed items
// We are just grabbing a bunch of random IDs
cursor = dbh.rawQuery("SELECT type_id FROM "+TABLE_PLAYCOUNTS+" WHERE type="+type+" ORDER BY RANDOM() LIMIT 10", null);
while (cursor.moveToNext()) {
toCheck.add(cursor.getLong(0));
}
cursor.close();
for (Long id : toCheck) {
query = MediaUtils.buildQuery(type, id, null, null);
cursor = query.runQuery(ctx.getContentResolver());
if(cursor.getCount() == 0) {
dbh.execSQL("DELETE FROM "+TABLE_PLAYCOUNTS+" WHERE type="+type+" AND type_id="+id);
removed++;
}
cursor.close();
}
Log.v("VanillaMusic", "performGC: items removed="+removed);
return removed;
}
}