Writing your own content provider
- Mobile
Writing your own content provider
What is Content Provider.??
A content provider manages access to a central repository of data. A provider is part of an Android application, which often provides its own UI for working with the data. However, content providers are primarily intended to be used by other applications, which access the provider using a provider client object.
Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content using insert(), update(), delete(), and query() methods. In most cases, this data is stored in an SQLite database.
Content Uris
To query a content provider, you specify the query string in the form of a URI which has the following format −
<prefix>://<authority>/<data_type>/<id>
prefix
This is always set to content://
Authority
This specifies the name of the content provider, for example, contacts, browser etc. like com.example.app.provider
Data Type
This indicates the type of data that this particular provider provides. Best practice is use table name here.
id
This specifies the specific record requested. like prefix://Authority/id/5
How to implement content provider.
ContentProvider is a class in Android SDK, You need to extend this then code look like.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class DataProvider extends ContentProvider { @Override public boolean onCreate() { return false; } @Nullable @Override public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) { return null; } @Nullable @Override public String getType(Uri uri) { return null; } @Nullable @Override public Uri insert(Uri uri, ContentValues contentValues) { return null; } @Override public int delete(Uri uri, String s, String[] strings) { return 0; } @Override public int update(Uri uri, ContentValues contentValues, String s, String[] strings) { return 0; } |
Now you need to override method according to need.
Query()
Retrieve data from your provider.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Nullable @Override public Cursor query(Uri uri, String[] projection, String s, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder sqb = new SQLiteQueryBuilder(); ourDatabase = ourHelper.getWritableDatabase(); Cursor cursor = null; int uriCode = URI_MATCHER.match(uri); String tableName = uriCodeToTable(uriCode); if (tableName.length() == 0) { return null; } sqb.setTables(tableName); cursor = ourDatabase.query(tableName, projection, s, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } |
insert()
Insert a new row into your provider.
1 2 3 4 5 6 7 8 9 10 11 |
@Nullable @Override public Uri insert(Uri uri, ContentValues contentValues) { SQLiteDatabase db = ourHelper.getWritableDatabase(); int uriCode = URI_MATCHER.match(uri); String TABLE = uriCodeToTable(uriCode); if (TABLE.length() == 0) { return null; } long id = db.insertWithOnConflict(TABLE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE); return getUriForId(id, uri); } |
For getting Id you take from here
1 2 3 4 5 6 7 8 9 10 11 |
private Uri getUriForId(long l, Uri uri) { if (l > 0L) { uri = ContentUris.withAppendedId(uri, l); getContext().getContentResolver().notifyChange(uri, null); return uri; } else { throw new SQLException((new StringBuilder()).append("Problem while inserting into uri: ") .append(uri) .toString()); } } |
Update existing rows in your provider
1 2 3 4 5 6 7 8 9 10 |
@Override public int update(Uri uri, ContentValues contentValues, String s, String[] strings) { SQLiteDatabase db = ourHelper.getWritableDatabase(); int updateCount = 0; String TABLE = uriCodeToTable(URI_MATCHER.match(uri)); if (TABLE.length() == 0) { return 0; } updateCount = db.update(TABLE, contentValues, s, strings); return updateCount; } |
Delete rows from your provider.
1 2 3 4 5 6 7 8 9 10 |
@Override public int delete(Uri uri, String s, String[] strings) { SQLiteDatabase db = ourHelper.getWritableDatabase(); int delCount = 0; String TABLE = uriCodeToTable(URI_MATCHER.match(uri)); if (TABLE.length() == 0) { return 0; } delCount = db.delete(TABLE, s, strings); return delCount; } |
1 2 3 |
@Nullable @Override public String getType(Uri uri) { return null; } |
Initialize your provider. The Android system calls this method immediately after it creates your provider. Notice that your provider is not created until a ContentResolver object tries to access it.
1 2 3 4 |
@Override public boolean onCreate() { ourHelper = new DBHandler(getContext()); return true; } |
For URI Table Mapping you can use
1 2 3 4 5 6 7 8 9 10 |
String uriCodeToTable(int code) { String tableName = ""; switch (code) { case TABLE_ITEM: tableName = TABLE_NAME; break; } return tableName; } |
Now Final code like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
public class ABCProvider extends ContentProvider { public static final String AUTHORITY = "com.example.provider"; public static final Uri RECORD_URI = Uri.parse("content://" + AUTHORITY + "/" + ABC_TABLE_NAME); private static final int ABC_ITEM = 1; private static UriMatcher URI_MATCHER; static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(AUTHORITY, ABC_TABLE_NAME, ABC_ITEM); } private SQLiteDatabase ourDatabase; private DBHandler ourHelper; @Override public boolean onCreate() { ourHelper = new DBHandler(getContext()); return true; } @Nullable @Override public Cursor query(Uri uri, String[] projection, String s, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder sqb = new SQLiteQueryBuilder(); ourDatabase = ourHelper.getWritableDatabase(); Cursor cursor = null; int uriCode = URI_MATCHER.match(uri); String tableName = uriCodeToTable(uriCode); if (tableName.length() == 0) { return null; } sqb.setTables(tableName); cursor = ourDatabase.query(tableName, projection, s, selectionArgs, null, null, sortOrder); // Common.L(DatabaseUtils.dumpCursorToString(cursor)); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Nullable @Override public String getType(Uri uri) { return null; } @Nullable @Override public Uri insert(Uri uri, ContentValues contentValues) { SQLiteDatabase db = ourHelper.getWritableDatabase(); int uriCode = URI_MATCHER.match(uri); String TABLE = uriCodeToTable(uriCode); if (TABLE.length() == 0) { return null; } long id = db.insertWithOnConflict(TABLE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE); return getUriForId(id, uri); } @Override public int delete(Uri uri, String s, String[] strings) { SQLiteDatabase db = ourHelper.getWritableDatabase(); int delCount = 0; String TABLE = uriCodeToTable(URI_MATCHER.match(uri)); if (TABLE.length() == 0) { return 0; } delCount = db.delete(TABLE, s, strings); return delCount; } @Override public int update(Uri uri, ContentValues contentValues, String s, String[] strings) { SQLiteDatabase db = ourHelper.getWritableDatabase(); int updateCount = 0; String TABLE = uriCodeToTable(URI_MATCHER.match(uri)); if (TABLE.length() == 0) { return 0; } updateCount = db.update(TABLE, contentValues, s, strings); return updateCount; } private Uri getUriForId(long l, Uri uri) { if (l > 0L) { uri = ContentUris.withAppendedId(uri, l); getContext().getContentResolver().notifyChange(uri, null); return uri; } else { throw new SQLException((new StringBuilder()).append("Problem while inserting into uri: ") .append(uri) .toString()); } } String uriCodeToTable(int code) { String tableName = ""; switch (code) { case ABC_ITEM: tableName = ABC_TABLE_NAME; break; } return tableName; } } |
Use case of retrieving data
1 2 3 4 5 6 7 8 9 10 11 |
mCursor=getContentResolver().query( CONTENT_URI, // The content URI of the words table mProjection, // The columns to return for each row mSelectionClause // Selection criteria mSelectionArgs, // Selection criteria mSortOrder); // The sort order for the returned rows |
Use case of inserting data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Defines a new Uri object that receives the result of the insertion Uri mNewUri; // Defines an object to contain the new values to insert ContentValues mNewValues = new ContentValues(); /* * Sets the values of each column and inserts the word. The arguments to the "put" * method are "column name" and "value" */ mNewValues.put(KEY_USER, "user"); mNewUri = getContentResolver().insert( CONTENT_URI, // the user dictionary content URI mNewValues // the values to insert ); |
Use case of updating data
1 2 3 4 5 6 7 8 9 10 11 12 |
// Defines an object to contain the updated values ContentValues mUpdateValues = new ContentValues(); int mRowsUpdated = 0; mUpdateValues.putNull(KEY); mRowsUpdated = getContentResolver().update( CONTENT_URI, // the user dictionary content URI mUpdateValues // the columns to update mSelectionClause // the column to select on mSelectionArgs // the value to compare to ); |
Use case of deleting data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Defines selection criteria for the rows you want to delete String mSelectionClause = KEY + " LIKE ?"; String[] mSelectionArgs = {"user"}; // Defines a variable to contain the number of rows deleted int mRowsDeleted = 0; ... // Deletes the words that match the selection criteria mRowsDeleted = getContentResolver().delete( .CONTENT_URI, // the user dictionary content URI mSelectionClause // the column to select on mSelectionArgs // the value to compare to ); |
Related content
Auriga: Leveling Up for Enterprise Growth!
Auriga’s journey began in 2010 crafting products for India’s