Share your database through ContentProviders
rutura edited this page Apr 17, 2017
·
1 revision
- This example shows how to share contents of your app database with other apps using ContentProviders.
- Make sure you have the database in place.See ShareDbHelper
- Create your ContentProvider subclass:
- Decide on the uri of your content provider.Something like the following should do:
* "content://com.blikoon.app590.friendprovider/friends"
- In your ContentProvider override the necessary methods:
- onCreate()
- getType()
- query()
- insert()
- update()
- delete()
- See FriendProvider.java for details.These methods are called through your ContentProvider CONTENT_URI.
- The ContentProvider must be declared in the manifest file
* <provider
android:name=".FriendProvider"
android:authorities="com.blikoon.app590.friendprovider">
</provider>
Nothe that "com.blikoon.app590.friendprovider" matches what we have in the CONTENT_URI
- Use LoaderManager to Asynchronously perform queries to the database though the contentProvider.The database query indirectly happens here
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = new String[]{FriendProvider.Columns._ID,
FriendProvider.Columns.FIRST};
return new CursorLoader(this, FriendProvider.CONTENT_URI,
projection, null, null, null);
}
- Use SimpleCursorAdapter to dynamically map the results of the query to the UI list view:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoaderManager().initLoader(LOADER_LIST, null, this);
mAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
null,
new String[]{FriendProvider.Columns.FIRST},
new int[]{android.R.id.text1},
0);
ListView list = new ListView(this);
list.setOnItemClickListener(this);
list.setAdapter(mAdapter);
setContentView(list);
}
...
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
- More on ContentProviders:
- More on Loaders:
- Relevant files:
- https://github.com/blikoon/Ubufundi/blob/master/App5.9.0/app/src/main/java/com/blikoon/app590/FriendProvider.java
- https://github.com/blikoon/Ubufundi/blob/master/App5.9.0/app/src/main/java/com/blikoon/app590/MainActivity.java
- https://github.com/blikoon/Ubufundi/blob/master/App5.9.0/app/src/main/AndroidManifest.xml
- Direct link to app: