从音乐的标题中,尝试得到对应的艺术家、专辑名称和专辑封面。我使用LoaderManager
和CursorLoader
。创建 Activity 后,我用getLoaderManager().initLoader(1, null, this)
. 这是我的加载器的代码:
在创建加载器时
static final String[] PLAYER_SUMMARY_PROJECTION = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM};
static final String[] PLAYER_COVER_SUMMARY_PROJECTION = { MediaStore.Audio.Albums.ALBUM_ID, MediaStore.Audio.Albums.ALBUM_ART, MediaStore.Audio.Albums.ALBUM};
public Loader<Cursor> onCreateLoader(int id, Bundle arg1) {
CursorLoader loader;
if(id==1){
String where = android.provider.MediaStore.Audio.Media.TITLE
+ "=?";
String whereVal[] = {dataalbumsTrackRequested};
loader = new CursorLoader(getActivity(), MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
PLAYER_SUMMARY_PROJECTION, where, whereVal,null); }
else{
String where2 = android.provider.MediaStore.Audio.Media.ALBUM
+ "=?";
String whereVal2[] = {album};
loader = new CursorLoader(getActivity(), MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
PLAYER_COVER_SUMMARY_PROJECTION, where2, whereVal2,null); }
return loader;
}
加载完成
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if(loader.getId()==1){
//Fill the text view with their value
//Set Title
String title =cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
TextView titleView = (TextView)getView().findViewById(R.id.musicTitle);
titleView.setText(title);
//Set Artist
String artist =cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
TextView artistView = (TextView)getView().findViewById(R.id.artistName);
if (artist.equals("<unknown>")){artistView.setText(R.string.unknown_album);}
else { artistView.setText(artist);}
//Set Album
album =cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
TextView albumView = (TextView)getView().findViewById(R.id.albumTitle);
if (album.equals("<unknown>")){albumView.setText(R.string.unknown_album);}
else { albumView.setText(album);}
}
else {
ImageView coverView = (ImageView)getView().findViewById(R.id.playerCoverView);
if (cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)).equals(null)){
//if no cover returned, display the by default (empty) cover
coverView.setImageResource(R.drawable.listcoverthumbnail);}
else{
Bitmap coverImage = BitmapFactory.decodeFile(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)));
coverView.setImageBitmap(coverImage);}
getLoaderManager().initLoader(2, null, this);
}
该变量album
是为整个类定义的,dataalbumsTrackRequested
是一个字符串,等于所需专辑的标题。
该应用程序崩溃,我得到:
06-19 16:21:42.720: E/AndroidRuntime(6516): Caused by: android.database.sqlite.SQLiteException: no such column: album_art: , while compiling: SELECT album_id, album_art, album FROM audio WHERE (album=?)
如果我删除了第二个加载器(Id=2),那么封面当然不会显示,但应用程序不会崩溃。所以问题来自第二个Loader。
我究竟做错了什么 ?我确信这个专栏album_art
存在,因为我已经在我的另一个应用程序中获得了这样的封面。但是在这里,我找不到错误的来源。是因为我使用了多个 Loaders 吗?