Search code examples
androidlistadapter

Need to get the ID of audiofile in android


I can load a list with the following code

String[] projection = new String[] {
    Audio.Media._ID,
    Audio.Media.DATA,
    Audio.Media.DISPLAY_NAME};

        audioCursor = this.managedQuery(Audio.Media.EXTERNAL_CONTENT_URI, 
            projection, null, null, Audio.Media.DISPLAY_NAME + " ASC");
        startManagingCursor(audioCursor);

        String[] columnsToMap = new String[] {Audio.Media.DISPLAY_NAME};
        int[] mapTo = new int[] {R.id.text1};

        ListAdapter mAdapter = new SimpleCursorAdapter(this, 
            R.layout.song_item , audioCursor, columnsToMap, mapTo);
        this.setListAdapter(mAdapter);

and in the onListItemClick I can get the file name like this

protected void onListItemClick(ListView l, View v, int position, long id) {
    String DisplayName;

    DisplayName =(String) ((TextView) v).getText(); // get name to compare
    Toast.makeText(this,DisplayName, Toast.LENGTH_SHORT).show();

but what I need is the original Audio.Media._ID number from the top. How can retrieve this number from the onListItemClick?


Solution

  • You are doing bad design.

    You should not get the value from the view. You will have to jump your cursor to the position and use the values from the cursor. The id param will hold the _ID of the record.

    if (audioCursor.moveToPosition(position)) {
        String DisplayName;
        DisplayName=audioCursor.getString(audioCursor.getColumnIndex(Audio.Media.DISPLAY_NAME));
    
    }