Android programming uses the content provider approach of of ContentProvider for storage

  • 2020-12-10 00:51:17
  • OfStack

This article illustrated how Android programming uses the content provider approach for storage. To share for your reference, the details are as follows:

Content providers (ContentProvider) role is largely foreign share data, if the data through the foreign share the content providers, so other applications can query to the data from the content providers, and can update the data, deleting data, add data, if the file mode of operation of foreign share data, data access can be brought about because of the different methods of storage data access cannot get series 1, different ways of storage file foreign share their visit ApI 1 sample, if the content provider foreign share data will series 1 data access method. API of Series 1 is used to access the shared data.

Create content provider steps

1. Creating a content provider requires inheritance from android.content.ContentProvider

2. Configure in the manifest file:

< ! --android:name: Specifies the class name of the content provider, android:authorities: calls the content.. Name, whatever you want to call it >
< provider android:name=".PersonProvider" android:authorities="cn.test.providers.personprovider"/ >

Main methods of the ContentProvider class

public boolean onCreate()

This method is called when ContentProvider is created, and when Android boots up, ContentProvider is created the first time another application accesses it.
public Uriinsert(Uri uri, ContentValues values)

This method is used for external applications to add data to ContentProvider.
public int delete(Uri uri, String selection,String[] selectionArgs)

This method is used for external applications to delete data from ContentProvider.
public int update(Uri uri, ContentValues values, Stringselection, String[] selectionArgs)

This method is used for external applications to update the data in ContentProvider.
public Cursorquery(Uri uri, String[]projection, String selection, String[] selectionArgs, String sortOrder)

This method is used for external applications to retrieve data from ContentProvider.

Example:

The content provider class, the realization data add, delete, change check


public class PersonProvider extends ContentProvider {
  // Create a tool class implementation Uri matching 
  private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
  private static final int PERSONS = 1;
  private static final int PERSON = 2;
  static{
    MATCHER.addURI("cn.test.providers.personprovider", "person", PERSONS);
    MATCHER.addURI("cn.test.providers.personprovider", "person/#", PERSON);
  }
  private DBOpenHelper dbOpenHelper = null;
  @Override
  public boolean onCreate() {
    dbOpenHelper = new DBOpenHelper(getContext());
    return true;
  }
  @Override
  public Cursor query(Uri uri, String[] projection, String selection,
      String[] selectionArgs, String sortOrder) {
    SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
    switch (MATCHER.match(uri)) {
    case PERSONS: //  To obtain person All the data in the table   /person
      return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
    case PERSON: //  To obtain person Specified in the table id The data of  /person/20
      long id = ContentUris.parseId(uri);
      String where = "personid="+ id;
      if(selection!=null && !"".equals(selection.trim())){
        where += " and "+ selection;
      }
      return db.query("person", projection, where, selectionArgs, null, null, sortOrder);
    default:
      throw new IllegalArgumentException("Unknown Uri:"+ uri);
    }
  }
  @Override
  public String getType(Uri uri) {
    // TODO Auto-generated method stub
    return null;
  }
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    // Gets an instance of a database operation 
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    switch (MATCHER.match(uri)) {
    case PERSONS:
      // Perform the add, returning the line number, which equals the primary key if the primary key field is self-growing id
      long rowid = db.insert("person", "name", values);
      // It's put together uri
      Uri insertUri = ContentUris.withAppendedId(uri, rowid);
      // Issue notification of data changes (person The data in the table changes )
      getContext().getContentResolver().notifyChange(uri, null);
      return insertUri;
    default:
      // Can't identify uri
      throw new IllegalArgumentException("Unknown Uri:"+ uri);
    }
  }
  @Override
  public int delete(Uri uri, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    // Number of rows affected 
    int num = 0;
    switch (MATCHER.match(uri)) {
    case PERSONS: //  delete person All the data in the table   /person
      num = db.delete("person", selection, selectionArgs);
      break;
    case PERSON: //  delete person Specified in the table id The data of  /person/20
      long id = ContentUris.parseId(uri);
      String where = "personid="+ id;
      if(selection!=null && !"".equals(selection.trim())){
        where += " and "+ selection;
      }
      num = db.delete("person", where, selectionArgs);
      break;
    default:
      throw new IllegalArgumentException("Unknown Uri:"+ uri);
    }
    return num;
  }
  @Override
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    int num = 0;
    switch (MATCHER.match(uri)) {
    case PERSONS: //  update person All the data in the table   /person
      num = db.update("person", values, selection, selectionArgs);
      break;
    case PERSON: //  update person Specified in the table id The data of  /person/20
      long id = ContentUris.parseId(uri);
      String where = "personid="+ id;
      if(selection!=null && !"".equals(selection.trim())){
        where += " and "+ selection;
      }
      num = db.update("person", values, where, selectionArgs);
      break;
    default:
      throw new IllegalArgumentException("Unknown Uri:"+ uri);
    }
    return num;
  }
}

Access in other projects:


public class AccessContentProiderTest extends AndroidTestCase {
  public void testInsert() throws Throwable{
    ContentResolver resolver = getContext().getContentResolver();
    Uri uri = Uri.parse("content://cn.test.providers.personprovider/person");
    ContentValues values = new ContentValues();
    values.put("name", "lili");
    values.put("phone", "110");
    values.put("amount", "3000000000");
    resolver.insert(uri, values);
  }
  public void testDelete() throws Throwable{
    ContentResolver resolver = getContext().getContentResolver();
    Uri uri = Uri.parse("content://cn.test.providers.personprovider/person");
    int num =resolver.delete(uri, null, null);
  }
  public void testUpdate() throws Throwable{
    ContentResolver resolver = getContext().getContentResolver();
    Uri uri = Uri.parse("content://cn.test.providers.personprovider/person/65");
    ContentValues values = new ContentValues();
    values.put("amount", 500);
    resolver.update(uri, values, null, null);
  }
  public void testQuery() throws Throwable{
    ContentResolver resolver = getContext().getContentResolver();
    Uri uri = Uri.parse("content://cn.test.providers.personprovider/person/65");
    Cursor cursor = resolver.query(uri, null, null, null, "personid asc");
    while(cursor.moveToNext()){
      String name = cursor.getString(cursor.getColumnIndex("name"));
      Log.i("AccessContentProviderTest", name);
    }
  }
}

I hope this article is helpful for Android programming.


Related articles: