Pages

Friday, July 1, 2011

How to get distinct values from android mediastore using contentresolver


In this post we can see a very easy way to get a list of distinct values from the android's Mediastore. In past I need that, but I haven't found an easy solution when I search for this to the Internet. So I found a solution and I show you with a  small tutorial.(It's my first attemp).


We say that we want to get the distinct values of the years*, which we have at least one song recorded.
So we create an new activity(I hope to know how, else the internet is full of  tutorials) and into the onCreate method we put our code.

1:          // get the content resolver instance  
2:          ContentResolver contentResolver = getContentResolver();  
3:          // the column of the year  
4:          final String year = MediaStore.Audio.AudioColumns.YEAR;  
5:          // create the string array with the returned values, there is the trick  
6:          // we use the DISTINCT before the name of the column  
7:          String[] values = new String[] { "DISTINCT " + year };  
8:          // execute the query  
9:          // we also check not to get null values  
10:          Cursor cursor = contentResolver  
11:                  .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,  
12:                         values,year + " not null", null,  
13:                         MediaStore.Audio.AudioColumns.YEAR);  
14:          // for each returned row we printed using android Logging fuctions  
15:          // we use loggat with tag distinct to see the result  
16:          // also you can show the results in the gui of your app  
17:          while (cursor.moveToNext()) {  
18:              Log.d("distinct", "year " + cursor.getString(0));  
19:          }  


*You can see the columns about audios in the mediastore from here http://developer.android.com/reference/android/provider/MediaStore.Audio.AudioColumns.html