Search code examples
androidandroid-contentproviderandroid-cursor

I always get a NULL Cursor for my custom ContentProvider


I have a ContentProvider access problem that I've distilled down into a small test driver.

The provider manifest declares it with:

<provider
  android:name=".MyContentProvider"
  android:authorities="com.foo.provider"
  android:enabled="true"
  android:exported="true">
</provider>

My content provider class is lifted from an example from here:

package com.foo.alpha;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

import java.util.HashMap;

public class MyContentProvider extends ContentProvider {
    // defining authority so that other application can access it
    static final String PROVIDER_NAME = "com.foo.provider";

    // defining content URI
    static final String URL = "content://" + PROVIDER_NAME + "/keys";

    // parsing the content URI
    static final Uri CONTENT_URI = Uri.parse(URL);

    static final int uriCode = 1;
    static final UriMatcher uriMatcher;
    private static HashMap<String, String> values;

    static {

        // to match the content URI
        // every time user access table under content provider
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        // to access whole table
        uriMatcher.addURI(PROVIDER_NAME, "keys", uriCode);

        // to access a particular row
       // uriMatcher.addURI(PROVIDER_NAME, "keys/*", uriCode);
    }

    public MyContentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int count = 0;
        switch (uriMatcher.match(uri)) {
            case uriCode:
                count = db.delete(TABLE_NAME, selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        switch (uriMatcher.match(uri)) {
            case uriCode:
                return "com.foo.provider/keys";
            default:
                throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long rowID = db.insert(TABLE_NAME, "", values);
        if (rowID > 0) {
            Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }
        throw new SQLiteException("Failed to add a record into " + uri);
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        DatabaseHelper dbHelper = new DatabaseHelper(context);
        db = dbHelper.getWritableDatabase();
        if (db != null) {
            return true;
        }

        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(TABLE_NAME);
        switch (uriMatcher.match(uri)) {
            case uriCode:
                qb.setProjectionMap(values);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        Cursor c = qb.query(db, projection, selection, selectionArgs, null,
                null, null);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        int count = 0;
        switch (uriMatcher.match(uri)) {
            case uriCode:
                count = db.update(TABLE_NAME, values, selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }


    // creating object of database
    // to perform query
    private SQLiteDatabase db;

    // declaring name of the database
    static final String DATABASE_NAME = "db";

    // declaring table name of the database
    static final String TABLE_NAME = "keys";

    // declaring version of the database
    static final int DATABASE_VERSION = 1;

    // sql query to create the table
    static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME
            + " (name TEXT PRIMARY KEY NOT NULL, keydata TEXT NOT NULL);";

    // creating a database
    private static class DatabaseHelper extends SQLiteOpenHelper {

        // defining a constructor
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        // creating a table in the database
        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(CREATE_DB_TABLE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            // sql query to drop a table
            // having similar name
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }

}

I've inserted some dummy data into the database within the provider app with:

    // stuff some data into our database
    try {
        ContentValues values = new ContentValues();
        values.put("name", "gordon");
        values.put("keydata", "foobar");
        getContentResolver().insert(MyContentProvider.CONTENT_URI, values);
        Log.d("gordon", "inserted record");
    } catch (Exception e) {
        Log.d("gordon", e.toString());
    }

That all seems good. Now I have a separate test app trying to query data from the provider. Here's the relevant code from that guy:

            String URL = "content://com.foo.provider/keys";
            Uri uri = Uri.parse(URL);
            String[] projection = new String[]{"name", "keydata"};
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);

Cursor is always null here. I suspect I'm just missing something simple but I don't know what I don't know.

UPDATE: I noticed this 1-liner in logcat when I try to access the content provider from the 2nd app:

AppsFilter: interaction: PackageSetting{e4410e4 com.foo.mysender/10346} -> PackageSetting{1e89e76 com.foo.alpha/10347} BLOCKED

I don't know why it's blocked.


Solution

  • Turns out the issue was package visibility.

    I stumbled onto this which lead to this addition in my manifest:

    <queries>
        <package android:name="com.foo.alpha" />
    </queries>
    

    Then it worked.