如何在 Android 中从 SQLite 数据库传入文件名?

How to pass in a filename from a SQLite database in Android?

我找不到解决问题的方法。我有一个 ExpandableListView,它在单击 child 视图时创建一个新的 MediaPlayer 实例。目前,这是通过硬编码 link 到我的原始文件夹中的文件来完成的,但我想将其切换为从数据库中获取文件名,然后使用该文件名从原始文件夹。

我的数据库是这样设置的:

_id|English|Hanzi|Pinyin|Filename

1  |Hello! |你好  |nǐ hǎo|hello

光标已加载并填充 ExpandableListView。我如何使用数据库中的文件名加载此 mediaPlayer 实例,以便每个 child 都加载它自己的音频文件?

    //load cursor
    public void fillData() {
    Cursor mGroupsCursor = mydb.fetchColorsGroup();
    startManagingCursor(mGroupsCursor);
    mGroupsCursor.moveToFirst();

    //Basic ExpandableListView Adapter
    MyExpandableListAdapter mAdapter = new MyExpandableListAdapter(mGroupsCursor, this,
            R.layout.group_item,                    // Group layout
            R.layout.child_item,                    // Child layout
            new String[]{"English"},                // Group fields
            new int[]{R.id.english_text},           // Widget ids for group data
            new String[]{"Hanzi", "Pinyin"},        // Child fields
            new int[]{R.id.foreign_text, R.id.romanization});          // Widget ids for child data
    final ExpandableListView elv = (ExpandableListView) this.findViewById(R.id.shell_expList);
    elv.setAdapter(mAdapter);                         // Set the list adapter



    // Set the listener for child clicks
    elv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                                    int groupPosition, int childPosition, long id) {


                    // Stop the media player
                    if (mediaPlayer != null) {
                        mediaPlayer.release();
                    }


                    // Start the media player
                    mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shi);
                    mediaPlayer.start();
                    return true;
            }
        });

使用一个MediaPlayer实例!不要为每一行重新创建一个。您可以使用它的 reset() 和方法来传递新的数据源。要在适配器的 getView/bindView(对于行)中传递这个新数据源,您可以在视图上使用 setTag() 方法。为了避免产生歧义,在res/ids.xml中添加一个id(如果你不想创建另一个资源文件,你也可以在res/styles.xml中添加它)比如然后做类似的事情:

public void bindView(View view, Context context, Cursor cursor) { ... // some method retrieving the song path from the cursor such as String uriLiteral = cursor.getString(COLUMN_INDEX_SONG_URI); // then you can do view.setTag(R.id.view_tag_song_play_path, uriLiteral); return mView; } 在点击监听器中:

@Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { String uriLiteral = (String) v.getTag(R.id.view_tag_song_uri); if (uriLiteral != null) { mediaPlayer.stop(); mediaPlayer.reset(); mediaPlayer.setDataPath(uriLiteral); mediaPlayer.prepare(); // .start(); } }

*代码按原样:mediaPlayer 可能有除 setDataPath 之外的其他内容,具体取决于您用来引用音乐文件的句柄类型(例如,磁盘路径、资产 ID 等)。