Home/Writing your own content provider

Writing your own content provider

Published On: 18 January 2017.By .
  • Mobile

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.

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.

@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.

@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

 

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()

Update existing rows in your provider

@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()

Delete rows from your provider.

 

@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;
}

getType()

@Nullable @Override public String getType(Uri uri) {
  return null;
}

onCreate()

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.

@Override public boolean onCreate() {
  ourHelper = new DBHandler(getContext());
  return true;
}

 

For URI  Table Mapping you can use

String uriCodeToTable(int code) {
  String tableName = "";
  switch (code) {
    case TABLE_ITEM:
      tableName = TABLE_NAME;
      break;
  
  }
  return tableName;
}

Now Final code like this

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

 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

  // 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

// 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 

// 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

We Love Conversations

Say Hello
Go to Top