I have this cuestion for you...
We are trying to pass an argument to a query in a content resolver. We want to get all rows if the argument is NULL, or get the specific value indicated at the argument as contrary.
The method we use declares:
static String allArtists = "";
////
Some code
...
Vector<String> discs = new 开发者_开发百科Vector<String>();
discs = getDiscs(allArtists);
////
public Vector<String> getDiscs(String artistName){
So, the query we made is as follows:
Uri discsUri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
ContentResolver contRes = getContentResolver();
String[] queryColumns = { MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ARTIST };
String selectionQuery = "? = ?";
String [] selectionArgs = { MediaStore.Audio.Albums.ARTIST, artistName };
String sortOrderClause = MediaStore.Audio.Albums.ALBUM + " ASC";
Cursor queryRes = contRes.query(discsUri,
queryColumns,
selectionQuery,
selectionArgs,
sortOrderClause
);
In order to make this method reusable, we pass artistName as argument, and because we want all rows to be selected, we pass the constant allArtists.
The point is that this query returns no rows, because the constant allArtists = "" doesnt act as the null value as we expected.
The question finally is: How must I declare the constant in a way that the query takes it as a NULL value instead of ""?.
Thanks a lot.
Turn empty strings into null
String selectionQuery = "? = nullif(?,'''')";
We resolved our problem making the selection this way:
String[] queryColumns = { MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ARTIST };
String selectionQuery = "( nullif('" + artistName + "','') ISNULL )" +
" OR (" + MediaStore.Audio.Albums.ARTIST + " == '" + artistName + "' )";
String sortOrderClause = MediaStore.Audio.Albums.ALBUM + " ASC";
Cursor queryRes = contRes.query(discsUri,
queryColumns,
selectionQuery,
null,
sortOrderClause);
Hope this helps anyone else. Greetings!
精彩评论