Android: call custom methods in a ContentProvider
Asked Answered
B

2

14

I have a custom ContentProvider I use to store fixes obtained from the GPS into a SQLite database. This class overrides ContentProvider methods (delete, insert, query...), but notice I have also included a method to query the last fix.

public class FixesContentProvider extends ContentProvider {
    @Override
    public int delete(...) { ... }
    ...
    @Override
    public Cursor query(...) { ... }

    public Cursor getLastFix(Uri uri) { ... }
}

It is pretty easy to query data from other services or activities by calling getContentResolver().

ContentResolver cR = getContentResolver();
Cursor fixes = cR.query(CONTENT_URI, ...);

But I am not able to call my custom method (FixesContentProvider#getLastFix). How could I call custom methods defined in a ContentProvider?

Maybe I don't understand how ContentProviders/ContentResolvers work in this case, but official Android documentation provided by Google is not very clear in this sense.

Burlburlap answered 24/7, 2010 at 15:12 Comment(0)
L
13

But I am not able to call my custom method (FixesContentProvider#getLastFix).

That's completely true. In this very case though, you can take advantage of one fact: both query and getLastFix methods return a Cursor object. So, what I do would be adding some value to the URI that you pass to query and, then decide what you want to actually do: query or getLastFix. For instance:

public Cursor query(Uri uri,...) { 
    if ( uri says it has to return the last fix )
        return getLastFix(uri);
    // otherwise, do normal operations...
    return cursor;
}

In fact, the query method is suppose to return a result, given a Uri. So, if you need to retrieve the last fix, you have to specify in the URI that you want the last fix.

Leandraleandre answered 24/7, 2010 at 15:25 Comment(1)
That is what I did. I've used UriMatcher.addUri to match "content://xxx/fixes" and "content://xxx/fixes/last" to two different codes, acting accordingly (as you propose) in a switch (myUriMatcher.match(uri)) { case CODE_1: xxx; case CODE_2: yyy; }. Thank you very much.Burlburlap
B
10

As of API level 11 there is a method ContentResolver.call(Uri, String, String, Bundle) which provides extra flexibility.

Background answered 27/2, 2013 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.