nicknaky
nicknaky

Reputation: 11

How to filter content resolver query results in android? Passing selection parameter still doesn't work

I'm trying to filer out city names and return matching cities based on the selection parameter being passed.

However the query call still returns all the rows. Even tried putting in a fake city name that doesn't already exist in the database and it still spits out the same original rows.

public void addLocation(String cityName){
    Cursor cursor = mContext.getResolver().query(
            WeatherContract.LocationEntry.CONTENT_URI,
            null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + 
            " = " + cityName,
            null,
            null);

I've read the Android docs over and over, ContentResolver Query, and passing the selection parameter in doesn't seem to be doing anything.

public final Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Upvotes: 1

Views: 2408

Answers (2)

Paul W
Paul W

Reputation: 161

Assuming the provider you're using is androidx.core.content.FileProvider (according to what you've declared in your manifest), the selection, selectionArgs and sortOrder parameters of FileProvider.query are... ignored in AndroidX's implementation !

See the v1.2.0 source here (line 409)

The only solution I found is to filter and sort the results post-query, in your own code. And yeah, that's kinda sad...

Upvotes: 1

fejd
fejd

Reputation: 2565

Instead of passing the value in the selection parameter, put it in selectionArgs.

public void addLocation(String cityName){
    String[] args = { cityName };
    Cursor cursor = mContext.getResolver().query(
            WeatherContract.LocationEntry.CONTENT_URI,
            null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + 
            " = ?",
            args,
            null);

Upvotes: 0

Related Questions