Introduction:
ContentProvider is one of the pillars of Android. It is a component which
i)- hides database details (database name, table name, column info. etc.)
ii)- allows the application to share data among multiple applications.
Steps to create ContentProvider:
i)- Create ContentProvider subclass (android.ContentProvider).
ii)- Register ContentProvider in AndroidManifest.xml file using provider element. (<provider>).
To Register ContentProvider use following attributes:
i)- android:name -> ContentProvider subclass name.
ii)- android:authorities -> authority used for ContentProvider
iii)- android:exported -> true/false.
true: ContentProvider can be used in other applications.
false: ContentProvider can be used in local application.
By default, it is “true”.
URI:
i)- Stands for Universal Resource Identifier.
ii)- URI is used to identify a ContentProvider uniquely in the current device.
iii)- URI has a special format i.e.
Content://Authority/Path
where,
content -> protocol used to communicate with the ContentProvider.
Authority -> A unique identifier used to identify ContentProvider (generally Authority is the name of the package in which ContentProvider is registered).
Path -> It is a unique string that appears after authority which is used to identify the table used in an operation.
Let’s Create Custom ContentProvider programmatically with the help of Example.
Example with Code:
- Create an Application AndroidContentProviderExample.
Requirements:
StudentProvider.java
activity_main.xml
MainActivity.java
Let’s do it one by one.
StudentProvider.java:
Create a subclass of ContentProvider in your application and override its methods.
Add the code
Initialize the fields for your ContentProvider and database.
1 2 3 4 5 6 7 8 9 10 11 12 |
static final String PROVIDER_NAME = "com.example.androidcontentproviderexample"; static final String URL = "content://" + PROVIDER_NAME + "/students"; static final Uri CONTENT_URI = Uri.parse(URL); static final String ID = "id"; static final String NAME = "name"; static final String PHONE = "phone"; static final int STUDENTS = 1; static final int STUDENTS_ID = 2; DBHelper dbHelper; |
To know the coming URI is of which type, we use URIMatcher class, it matches the patterns.
1 2 3 4 5 6 |
static final UriMatcher uriMatcher; static{ uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS); uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENTS_ID); } |
Add the code in these methods onCreate(), query(), update(), delete(), insert(), getType().
onCreate():
Add the code in this method
1 2 3 4 |
Context context = getContext(); dbHelper = new DBHelper(context); // permissions to be writable database = dbHelper.getWritableDatabase(); |
query(….):
Add the code in this method
Here we set the table and maps all database column names.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); queryBuilder.setTables(TABLE_NAME); switch (uriMatcher.match(uri)) { case STUDENTS: queryBuilder.setProjectionMap(StudentMap); break; case STUDENTS_ID: queryBuilder.appendWhere( ID + "=" + uri.getLastPathSegment()); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } if (sortOrder == null || sortOrder == ""){ sortOrder = NAME; } Cursor cursor = queryBuilder.query(database, projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; |
insert(..):
Here, in this method, we add the record.
Add the code
1 2 3 4 5 6 7 |
long row = database.insert(TABLE_NAME, "", values); if(row > 0) { Uri newUri = ContentUris.withAppendedId(CONTENT_URI, row); getContext().getContentResolver().notifyChange(newUri, null); return newUri; } throw new SQLException("Fail to add a new record into " + uri); |
update(..):
Add the code here
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
int count = 0; switch (uriMatcher.match(uri)){ case STUDENTS: count = database.update(TABLE_NAME, values, selection, selectionArgs); break; case STUDENTS_ID: count = database.update(TABLE_NAME, values, ID + " = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection) ? " AND (" +selection + ')' : ""), selectionArgs); break; default: throw new IllegalArgumentException("Unsupported URI " + uri ); } getContext().getContentResolver().notifyChange(uri, null); return count; |
delete(..):
To delete all the records of the table.
Add the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
int count = 0; switch (uriMatcher.match(uri)){ case STUDENTS: count = database.delete(TABLE_NAME, selection, selectionArgs); break; case STUDENTS_ID: String id = uri.getLastPathSegment(); count = database.delete( TABLE_NAME, ID + " = " + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs); break; default: throw new IllegalArgumentException("Unsupported URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; |
getType(..):
In this method, we get all the records or a particular record with using id.
Add the code here
1 2 3 4 5 6 7 8 |
switch (uriMatcher.match(uri)){ case STUDENTS: return "vnd.android.cursor.dir/vnd.example.students"; case STUDENTS_ID: return "vnd.android.cursor.item/vnd.example.students"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } |
activity_main.xml:
Create an XML file of the main layout.
Add the code inside RelativeLayout.
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 |
<EditText android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" android:hint="@string/name" /> <EditText android:id="@+id/phone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignLeft="@+id/name" android:layout_below="@+id/name" android:ems="10" android:hint="@string/phone" /> <Button android:id="@+id/btnAdd" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="addStudent" android:layout_alignLeft="@+id/phone" android:layout_below="@+id/phone" android:layout_marginTop="30dp" android:text="@string/add" android:background="#ADD8E6"/> <Button android:id="@+id/btnShow" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btnAdd" android:layout_below="@+id/btnAdd" android:layout_marginTop="20dp" android:onClick="showAllStudentsRecord" android:text="@string/show" android:background="#ADD8E6" /> <Button android:id="@+id/btnDelete" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/btnShow" android:layout_alignLeft="@+id/btnShow" android:layout_marginTop="20dp" android:onClick="deleteAllStudentsRecord" android:text="@string/delete" android:background="#ADD8E6" /> |
MainActivity.java:
Inside this, we implement three onclick methods for add, delete and show the records of students.
Add the code for adding a new student record inside addStudent() method:
1 2 3 4 5 6 7 8 |
ContentValues values = new ContentValues(); values.put(StudentProvider.NAME, ((EditText)findViewById(R.id.name)).getText().toString()); values.put(StudentProvider.PHONE, ((EditText)findViewById(R.id.phone)).getText().toString()); Uri uri = getContentResolver().insert( StudentProvider.CONTENT_URI, values); Toast.makeText(getBaseContext(), "Example: " + uri.toString() + " inserted!", Toast.LENGTH_LONG).show(); |
Add the code for delete all the records inside deleteAllStudentsRecord() method:
1 2 3 4 5 6 7 |
String URL = "content://com.example.androidcontentproviderexample/students"; Uri friends = Uri.parse(URL); int count = getContentResolver().delete( friends, null, null); String countNum = "Example: "+ count +" records are deleted."; Toast.makeText(getBaseContext(), countNum, Toast.LENGTH_LONG).show(); |
Add the code for show all the records inside showAllStudentsRecord() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
String URL = "content://com.example.androidcontentproviderexample/students"; Uri students = Uri.parse(URL); Cursor c = getContentResolver().query(students, null, null, null, "name"); String result = "Results:"; if (!c.moveToFirst()) { Toast.makeText(this, result+" no content yet!", Toast.LENGTH_LONG).show(); }else{ do{ result = result + "\n" + c.getString(c.getColumnIndex(StudentProvider.NAME)) +" with id " + c.getString(c.getColumnIndex(StudentProvider.ID)) + " has phone: " + c.getString(c.getColumnIndex(StudentProvider.PHONE)); } while (c.moveToNext()); Toast.makeText(this, result, Toast.LENGTH_LONG).show(); } |
Conclusion:
This is the basic idea of how to create Custom ContentProvider in your application. We can create our own ContentProvider and use in many applications to share the data. It is one of the important components of Android and it is very popular in Android development.
Output:
Before Add
After Add
Show the Record
After Delete
After Delete when clicking on Show all the Students Button.
Hope you learned something new. Stay tuned with us to get latest updates on Softwares and tutorials.
Visit our home page here to learn Techinical Courses.
Leave a Reply