如何在列表视图中添加歌曲标题和专辑封面并在点击时启动播放器?

时间:2015-08-08 12:09:55

标签: android listview android-fragments android-mediaplayer

我正在制作一个包含多个标签(歌曲,播放列表,专辑等)的音乐播放器应用。每个代表一个片段。截至目前,我未能使用媒体商店创建一个偶数歌曲列表。

这是我尝试的代码,但它无效

public class Songs extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {

SongsAdapter mAdapter;
private static final String ARG_POSITION = "position";

private int position;

public static Songs newInstance(int position) {
    Songs f = new Songs();
    Bundle b = new Bundle();
    b.putInt(ARG_POSITION, position);
    f.setArguments(b);
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View myFragmentView = inflater.inflate(R.layout.songs, container, false);
    return myFragmentView;
}


@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);

    mAdapter = new SongsAdapter(getActivity(), null);
    setListAdapter(mAdapter);
    getLoaderManager().initLoader(0, null, this);
}


static final String[] SONGS_SUMMARY_PROJECTION = { MediaStore.Audio.Media._ID,MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.DURATION};



public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String select = null;
    return new CursorLoader(getActivity(), MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,SONGS_SUMMARY_PROJECTION, select, null, null);
}



public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mAdapter.swapCursor(data);
}



public void onLoaderReset(Loader<Cursor> loader) {
    mAdapter.swapCursor(null);
}

}

这是适配器类

public class SongsAdapter extends CursorAdapter {

private final LayoutInflater nInflater;

public SongsAdapter(Context context, Cursor c) {
    super(context, c);
    nInflater = LayoutInflater.from(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
    cursor.moveToFirst();
    TextView songTitle = (TextView) view.findViewById(R.id.songTitle);
    songTitle.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
    TextView artist = (TextView) view.findViewById(R.id.songArtist);
    artist.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));

    ImageView albumArt = (ImageView) view.findViewById(R.id.list_image);
    albumArt.setScaleType(ImageView.ScaleType.FIT_XY);

    Long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));

    Bitmap img = getAlbumart(context,albumId);
    if(img != null)
        albumArt.setImageBitmap(img);
    else{ 
        Bitmap def = getDefaultAlbumArt(context);
        albumArt.setImageBitmap(def);

    }

}


@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    final View view = nInflater.inflate(R.layout.song_item, parent, false);
    return view;
}



public Bitmap getAlbumart(Context context, Long album_id) {
    Bitmap bm = null;
    try {
        final Uri sArtworkUri = Uri
                .parse("content://media/external/audio/albumart");

        Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);

        ParcelFileDescriptor pfd = context.getContentResolver()
                .openFileDescriptor(uri, "r");

        if (pfd != null) {
            FileDescriptor fd = pfd.getFileDescriptor();
            bm = BitmapFactory.decodeFileDescriptor(fd);
        }
    } catch (Exception e) {
    }
    return bm;
}

public Bitmap getDefaultAlbumArt(Context context) {
    Bitmap bm = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    try {
        bm = BitmapFactory.decodeResource(context.getResources(),
                R.drawable.musicicon, options);
    } catch (Error ee) {
    } catch (Exception e) {
    }
    return bm;
}

}

这里是logcat消息:

java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
        at android.database.CursorWindow.nativeGetString(Native Method)
        at android.database.CursorWindow.getString(CursorWindow.java:434)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:62)
        at android.database.CursorWrapper.getString(CursorWrapper.java:114)
        at com.screens.SongsAdapter.bindView(SongsAdapter.java:42)
        at android.widget.CursorAdapter.getView(CursorAdapter.java:254)
        at android.widget.AbsListView.obtainView(AbsListView.java:2338)
        at android.widget.ListView.measureHeightOfChildren(ListView.java:1273)
        at android.widget.ListView.onMeasure(ListView.java:1182)
        at android.view.View.measure(View.java:16838)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.view.View.measure(View.java:16838)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1455)
        at android.view.View.measure(View.java:16838)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:926)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
        at android.view.View.measure(View.java:16838)
        at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:868)
        at android.view.View.measure(View.java:16838)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
        at android.view.View.measure(View.java:16838)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
        at android.view.View.measure(View.java:16838)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.view.View.measure(View.java:16838)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
        at android.view.View.measure(View.java:16838)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
        at android.view.View.measure(View.java:16838)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2252)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1315)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5292)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
        at dalvik.system.NativeStart.main(Nativ

请告诉我需要对这些代码进行哪些修改。

如果可能的话,请告诉我如何在点击列表中的歌曲时启动播放器。需要添加什么方法?

1 个答案:

答案 0 :(得分:0)

代码mAdapter = new SongsAdapter(getActivity(), null)不正确。通常,您在第二个参数上传递Cursor对象。 代码示例:

Cursor todoCursor = db.rawQuery("SELECT  * FROM todo_items", null);
TodoCursorAdapter todoAdapter = new TodoCursorAdapter(this, todoCursor);

示例代码来自教程Populating a ListView with a CursorAdapter

这样,cursor.moveToFirst();中代码bindView()中的光标对象有效。但是你必须执行数据库查询。