Saturday, April 2, 2011

Accessing the data

At first when displaying the data from the media store I was basically doing a query and iterating the results to populate an ArrayList which got fed into the ListView. Something like this:


//--------------------------------------------------------------------------------------------------------------

cursor = managedQuery(Audio.Albums.EXTERNAL_CONTENT_URI, new String[] {
     Audio.Albums.ARTIST}, null, null, Audio.Albums.ARTIST + " ASC");

int artist_index = cursor.getColumnIndexOrThrow(Audio.Albums.ARTIST);
       
cursor.moveToFirst();
artist_list = new ArrayList<String>();
do
{
   String artist = cursor.getString(artist_index);
   artist.add(artist);
}
while (cursor.moveToNext());
       
setListAdapter(new ArrayAdapter<String>(this, R.id.def_listitem, artist_list));
//--------------------------------------------------------------------------------------------------------------

After looking into the api more I discovered there is actually a class that does this for you.  Awesome.
So my code is now much shorter

//--------------------------------------------------------------------------------------------------------------
cursor = managedQuery(Audio.Artists.EXTERNAL_CONTENT_URI, new String[] {
     Audio.Artists._ID, Audio.Artists.ARTIST }, null, null, Audio.Artists.ARTIST + " ASC");
        
adapter = new SimpleCursorAdapter(this, R.layout.list_item, m_cursor , new String[] { Audio.Artists.ARTIST }, new int[]{R.id.def_listitem});

setListAdapter(adapter);
//--------------------------------------------------------------------------------------------------------------

I am still unsure which approach I am going to use.  The second way is much cleaner but in order to get the information needed to make the album and song queries I had to extra it from text fields which is pretty ghetto.  Must investigate more.  Now for that beer.