Question

I am using the following code to get a list of songs on my device. Eventually I'd like to do more with them but to just get started I want to find audio/music in an Android device.

I have used this code to query the media store and I keep getting a null cursor... I've checked out these stack overflow answers but their either not relevant or I don't understand them enough to implement them...

Would appreciate any help! Thanks in advance

public class AudioFinalActivity extends Activity {

    private TextView tv;
    private String res;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // link text view obj
        tv = (TextView) findViewById(R.id.tv);
        res = "";

         String[] proj = { MediaStore.Audio.Media._ID,
         MediaStore.Audio.Media.DATA,
         MediaStore.Audio.Media.DISPLAY_NAME,
         MediaStore.Audio.Artists.ARTIST };
         // managed query doesn't need startManagingCursor called on the
         Cursor c = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
         proj, null, null, null);

//      ContentResolver contentResolver = getContentResolver();
//      String[] columns = { MediaColumns.TITLE, AudioColumns.DURATION,
//              MediaColumns.DATA
//      // add more columns if you want to fetch more data
//      };
//
//      Cursor c = contentResolver.query(
//              MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, null,
//              null, null);

        if (c != null) {
            Log.d("AFA", "Cursor returned NULL");
        } else if (c.getCount() < 1) {
            Log.d("AFA", "Cursor query is empty.. :( ...");
        } else {
            // do stuff with our content...
            while (c.moveToNext()) {

                //String title = c.getString(c
                        .getColumnIndex(MediaColumns.TITLE));
                //Long duration = c.getLong(c
                        .getColumnIndex(AudioColumns.DURATION));
                //String data = c.getString(c
                        .getColumnIndex(MediaColumns.DATA));

                //res += title + "\n";
                res +=  c.getString(c.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)) + "\n";
                tv.setText(res);
            }
        }
    }
}

I the stock music player can play my phones audio just fine..

EDIT:

I just removed my checking for the cursor being empty and for the cursor being null and I seem to get a result.. strange why the cursor is null yet the while(c.MoveToNext())... returns values... hmmm

Was it helpful?

Solution

your checking is if (c != null) {}, but I suppose it is if (c == null) {} (if you are checking the cursor being null)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top