我想帮助加快我的SQLite
数据库中一个相当简单的选择查询。
该查询正在搜索大约 6500 行的表,并且当前在大约 600 毫秒内返回。我不知道这是否可以接受,但我希望它会比这更快。我最终会把它放进去AsyncTask
,但想尽可能地优化。在下面的代码片段中,您可以看到我尝试过的内容。
KEY_songPath 已编入索引。
public ArrayList<Song> getCurrentDirSongs(String currentDir) {
long startTime = System.currentTimeMillis();
ArrayList<Song> songsList = new ArrayList<Song>();
String selectQuery = "";
int strLength = currentDir.length();
//selectQuery = "SELECT * FROM " + TABLE_SONGS + " WHERE (" + KEY_songPath + " >= '" + currentDir + "')";
//selectQuery = "SELECT * FROM " + TABLE_SONGS + " WHERE (" + KEY_songPath + " GLOB '" + currentDir + "*')";
//selectQuery = "SELECT * FROM " + TABLE_SONGS + " WHERE (" + KEY_songPath + " LIKE '" + currentDir + "%')";
selectQuery = "SELECT * FROM " + TABLE_SONGS + " WHERE " + KEY_ID +
" IN (SELECT " + KEY_ID +" FROM "+ TABLE_SONGS + " WHERE length(" + KEY_songPath + ")>= "+ strLength +") AND " +
"(" + KEY_songPath + " LIKE '" + currentDir + "%')";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Song song = new Song();
song.setSongTitle(cursor.getString(1));
song.setSongPath(cursor.getString(2));
song.setSongArtist(cursor.getString(3));
song.setSongAlbum(cursor.getString(4));
song.setTrackNumber(cursor.getString(5));
song.setID(Integer.parseInt(cursor.getString(6)));
song.setAlbumID(Integer.parseInt(cursor.getString(7)));
song.setArtistID(Integer.parseInt(cursor.getString(8)));
song.setSongCheckedStatus(Boolean.parseBoolean(cursor.getString(9)));
song.setSongPosition(Integer.parseInt(cursor.getString(10)));
song.setSongDuration(Integer.parseInt(cursor.getString(11)));
// Adding song to list
songsList.add(song);
} while (cursor.moveToNext());
}
long estimatedTime = System.currentTimeMillis() - startTime;
Log.d("AMCDatabase Database Handler: ", "SongsList.size(): "+ getSongsCount("SongsList") + " Time: " + estimatedTime + "ms");
// return contact list
return songsList;
}
这返回了以下结果: SongsList.size(): 6390 Time: 588ms
任何帮助都感激不尽!
PS 这可能都不是问题 - 可以接受一秒钟的时间查询和 6000 个值ArrayList
吗?