BCA / B.Tech 14 min read

Sharing Data with Content Providers

Sharing Data with Content Providers

What is a Content Provider?

A Content Provider is a component of the Android framework that provides a standard way to share structured data between applications. It manages access to the data and ensures data security.

It acts as an abstraction layer between a database and other applications. Apps do not access the database directly; they send requests through the Content Provider.

Example: Android's built-in "Contacts" app exposes its data through a Content Provider, so that other apps (like WhatsApp) can read the contact list with the user's permission.


1: Creating Your Own Content Provider

To share your data with other apps, you can create your own Content Provider.

Key Steps:

  1. Create a ContentProvider Class: Create a new Java class that extends `ContentProvider`.
  2. Create a Contract Class: (Optional but recommended) Create a contract class that defines constants for URIs, table names, and column names.
  3. Implement the Methods: Override and implement the `query()`, `insert()`, `update()`, `delete()`, `getType()`, and `onCreate()` methods.
  4. Register in the Manifest: Register your provider in the `AndroidManifest.xml` file using the `` tag.

Example in Java: (Building on the DatabaseHelper from Topic 21)

Step 1: Creating the ContentProvider Class


public class UserProvider extends ContentProvider {
    
    // The authority for our provider. This must be unique.
    public static final String AUTHORITY = "com.example.myapp.UserProvider";
    // The content URI
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/users");
    
    private DatabaseHelper dbHelper;

    @Override
    public boolean onCreate() {
        dbHelper = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        return db.query("users", projection, selection, selectionArgs, null, null, sortOrder);
    }

    // The insert, update, delete, getType methods would be implemented here...
    // For simplicity, we are focusing on the query method.
    
    @Override
    public String getType(Uri uri) {
        return null; // Not implemented for this example
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null; // Not implemented for this example
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0; // Not implemented for this example
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0; // Not implemented for this example
    }
}

Step 2: Registering in AndroidManifest.xml


<application ...>
    ...
    <provider
        android:name=".UserProvider"
        android:authorities="com.example.myapp.UserProvider"
        android:exported="true" /> 
        <!-- exported="true" means other apps can access it -->
</application>

2: Using a Content Provider

To access data from another app, you use the `ContentResolver` object.

What is a ContentResolver?

Every application has its own instance of a `ContentResolver`. This object is the standard way to communicate with a Content Provider. You get it by calling `getContentResolver()`.

Example: Querying Users from a Different App


// This code would be in a separate app

public class ConsumerActivity extends AppCompatActivity {
    TextView dataTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consumer);
        dataTextView = findViewById(R.id.data_tv);
    }
    
    public void loadDataFromProvider(View view) {
        // The Content URI of the provider
        Uri usersUri = Uri.parse("content://com.example.myapp.UserProvider/users");

        // Query using the ContentResolver
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(usersUri, null, null, null, null);
        
        StringBuilder stringBuilder = new StringBuilder();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                // Extract data using column names
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String email = cursor.getString(cursor.getColumnIndex("email"));
                stringBuilder.append("Name: ").append(name).append(", Email: ").append(email).append("
");
            } while (cursor.moveToNext());
            cursor.close();
        }
        
        dataTextView.setText(stringBuilder.toString());
    }
}

In this way, the `ConsumerActivity` app cannot access the `UserProvider` app's data without its permission (if permissions are defined), and it also does not touch the database directly, making data sharing secure and organized.