Creating Your Own Content Providers

o create your own content provider in Android, all you need to do is to extend the abstract ContentProvider class and override the various methods defined within it.
Ex:-
For simplicity, the content provider stores the books in a table containing three fields. id title isbn
— —- —-
public class BooksProvider extends ContentProvider
{
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
return 0;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public boolean onCreate() {
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
The methods you need to implement are:
getType(): Returns the MIME type of the data at the given URI.
onCreate(): Called when the provider is being started.
query(): Receives a request from a client. The result is returned as a Cursor object.
insert(): Inserts a new record into the content provider.
delete(): Deletes an existing record from the content provider.
update(): Updates an existing record from the content provider.
Within your content provider, you may choose to store your data however you like: traditional file system, XML, database, or even through web services.
UriMatcher object to parse the content URI that is passed to the content provider through a Content Resolver.
content URI represents a request for all books in the content provider:
content://net.learn2develop.provider.Books/books
In contrast, the following represents a request for a particular book with _id=5:
content://net.learn2develop.provider.MailingList/books/5
SQLiteOpenHelper helper class to help manage your database.
In BooksProvider.java
——————————
package com.contentproviderdemo;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
public class BooksProvider extends ContentProvider
{
public static final String PROVIDER_NAME =“com.contentproviderdemo.provider.Books”;
public static final Uri CONTENT_URI =Uri.parse(“content://”+ PROVIDER_NAME + “/books”);
public static final String _ID = “_id”;
public static final String TITLE = “title”;
public static final String ISBN = “isbn”;
private static final int BOOKS = 1;
private static final int BOOK_ID = 2;
private static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, “books”, BOOKS);
uriMatcher.addURI(PROVIDER_NAME, “books/#”, BOOK_ID);
}
//—for database use—
private SQLiteDatabase booksDB;
private static final String DATABASE_NAME = “Books”;
private static final String DATABASE_TABLE = “titles”;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = “create table ” + DATABASE_TABLE +” (_id integer primary key autoincrement, “+ “title text not null, isbn text not null);”;
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
Log.w(“Content provider database”,“Upgrading database from version ” + oldVersion + ” to ” + newVersion +“, which will destroy all old data”);
db.execSQL(“DROP TABLE IF EXISTS titles”);
onCreate(db);
}
}
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
// arg0 = uri
// arg1 = selection
// arg2 = selectionArgs
int count=0;
switch (uriMatcher.match(arg0)){
case BOOKS: count = booksDB.delete( DATABASE_TABLE, arg1, arg2);
break;
case BOOK_ID:
String id = arg0.getPathSegments().get(1);
count = booksDB.delete(DATABASE_TABLE, _ID + ” = ” + id + (!TextUtils.isEmpty(arg1) ? ” AND (” + arg1 + ‘)’ : “”),arg2);
break;
default: throw new IllegalArgumentException( “Unknown URI ” + arg0);
}
getContext().getContentResolver().notifyChange(arg0, null);
return count;
}
@Override
public String getType(Uri arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
//—add a new book—
long rowID = booksDB.insert(DATABASE_TABLE, “”, values);
//—if added successfully—
if (rowID>0)
{
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException(“Failed to insert row into ” + uri);
}
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
booksDB = dbHelper.getWritableDatabase();
return (booksDB == null)? false:true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
sqlBuilder.setTables(DATABASE_TABLE);
if (uriMatcher.match(uri) == BOOK_ID)
//—if getting a particular book—
sqlBuilder.appendWhere(_ID + ” = ” + uri.getPathSegments().get(1));
if (sortOrder==null || sortOrder==”")
sortOrder = TITLE;
Cursor c = sqlBuilder.query( booksDB, projection, selection, selectionArgs, null, null, sortOrder);
//—register to watch a content URI for changes—
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
{
int count = 0;
switch (uriMatcher.match(uri)){
case BOOKS:
count = booksDB.update(DATABASE_TABLE, values, selection, selectionArgs);
break;
case BOOK_ID:
count = booksDB.update(DATABASE_TABLE, values, _ID + ” = ” + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(selection) ? ” AND (” +selection + ‘)’ : “”), selectionArgs);
break;
default: throw new IllegalArgumentException( “Unknown URI ” + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}
In main.java
—————-
package com.contentproviderdemo;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
public class contentproviderdemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentValues values = new ContentValues();
values.put(BooksProvider.TITLE, “C# 2008 Programmer’s Reference”);
values.put(BooksProvider.ISBN, “0470285818″);
Uri uri = getContentResolver().insert(BooksProvider.CONTENT_URI, values);
//—add another book—
values.clear();
values.put(BooksProvider.TITLE, “Programming Sudoku”);
values.put(BooksProvider.ISBN, “1590596625″);
uri = getContentResolver().insert(BooksProvider.CONTENT_URI, values);
Toast.makeText(this, “Haiii”, Toast.LENGTH_LONG).show();
Uri allTitles = Uri.parse(“content://com.contentproviderdemo.provider.Books/books”);
Cursor c = managedQuery(allTitles, null, null, null, “title desc”);
if (c.moveToFirst()) {
do{
Toast.makeText(this,c.getString(c.getColumnIndex( BooksProvider._ID)) + “, ” +
c.getString(c.getColumnIndex(BooksProvider.TITLE)) + “, ” + c.getString(c.getColumnIndex(
BooksProvider.ISBN)), Toast.LENGTH_LONG).show();
} while (c.moveToNext());
}
//for Edit the values
ContentValues editedValues = new ContentValues();
editedValues.put(BooksProvider.TITLE,
“Programming Sudoku (Apress)”);
getContentResolver().update( Uri.parse( “content://net.learn2develop.provider.Books/books/2″),
editedValues,null, null);
//For delete
ContentValues deletedValues = new ContentValues();
deletedValues.put(BooksProvider.TITLE,
“Programming Sudoku (Apress)”);
getContentResolver().delete( Uri.parse( “content://net.learn2develop.provider.Books/books/2″),
null, null);
}
}
In Adroidmanifest.xml
——————————-
<provider android:name=”BooksProvider” android:authorities=”com.contentproviderdemo.provider.Books” />

Comments

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams