Junior — Middle
Tell us about your experience using Content Provider in Android applications.
sobes.tech AI
Answer from AI
Content Provider in Android is used for data sharing between applications or for managing access to data within a single application. In my experience, I have used Content Provider to implement shared access to an SQLite database so that other components or applications can safely read and modify data.
Key points when working with Content Provider:
- Defining URI for data access.
- Implementing methods query(), insert(), update(), delete() for data operations.
- Registering the provider in AndroidManifest.xml.
Example of a simple Content Provider for the "notes" table:
public class NotesProvider extends ContentProvider {
private static final String AUTHORITY = "com.example.notesprovider";
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private SQLiteDatabase database;
static {
uriMatcher.addURI(AUTHORITY, "notes", 1);
uriMatcher.addURI(AUTHORITY, "notes/#", 2);
}
@Override
public boolean onCreate() {
DBHelper dbHelper = new DBHelper(getContext());
database = dbHelper.getWritableDatabase();
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor cursor;
switch (uriMatcher.match(uri)) {
case 1:
cursor = database.query("notes", projection, selection, selectionArgs, null, null, sortOrder);
break;
case 2:
selection = "_id=?";
selectionArgs = new String[]{uri.getLastPathSegment()};
cursor = database.query("notes", projection, selection, selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
// Implementation of insert(), update(), delete() similarly
}
Thus, Content Provider helps organize centralized and controlled access to data.