CRUD and optimization of ContentProvider
A note in advance:
ContentProvider steps: create database, write rule matching, configure manifests, use by another application
In fact, ContentProvider is: write the matching rules written by yourself in a matcher, and provide the written matching rules for use, and the rest is the processing of adding, deleting, modifying and checking.
Detailed processing:
In the query in CRUD, there is no cursor.getBoolean method, so it is necessary to process the Boolean value obtained from the database:
msg.setFlag(cursor.getInt(cursor.getColumnIndex("flag")) != 0);
CRUD of ContentProvider
Step 1: Create a class that inherits SQLiteOpenHelper and create a SQLite with SQL statements
public class CommonOpenHelper extends SQLiteOpenHelper { private static CommonOpenHelper helper; public static CommonOpenHelper getInstance(Context context) { if (helper == null) { helper = new CommonOpenHelper(context, "common.db", null, 1); } return helper; } private CommonOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table message(" + "id integer primary key autoincrement, " + "content varchar, " + "date varchar " + ")"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
public class MyMessageProvider extends ContentProvider { //data storage name public final static String DB_MESSAGE = "message"; // put a database CommonOpenHelper helper; SQLiteDatabase db; //whitespace matcher UriMatcher matcher = new UriMatcher (UriMatcher.NO_MATCH); // own matching rules final static int CODE_MESSAGE_INSERT = 0; final static int CODE_MESSAGE_QUERY = 1; final static int CODE_MESSAGE_DELETE = 2; final static int CODE_MESSAGE_UPDATE = 3; //CPU name final static String authority = "com.handsome.nfcc"; final static Uri BASE_URI = Uri.parse("content://com.handsome.nfcc"); //Write the matching rule for the hostname { matcher.addURI(authority, "message/insert", CODE_MESSAGE_INSERT); matcher.addURI(authority, "message/query", CODE_MESSAGE_QUERY); matcher.addURI(authority, "message/delete", CODE_MESSAGE_DELETE); matcher.addURI(authority, "message/update", CODE_MESSAGE_UPDATE); } // URI provided externally public interface URI { Uri CODE_MESSAGE_INSERT = Uri.parse("content://" + authority + "/message/insert"); Uri CODE_MESSAGE_QUERY = Uri.parse("content://" + authority + "/message/query"); Uri CODE_MESSAGE_DELETE = Uri.parse("content://" + authority + "/message/delete"); Uri CODE_MESSAGE_UPDATE = Uri.parse("content://" + authority + "/message/update"); } @Override public boolean onCreate() { helper = CommonOpenHelper.getInstance(getContext()); db = helper.getWritableDatabase(); return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { switch (matcher.match(uri)) { case CODE_MESSAGE_QUERY: Cursor cursor = db.query(DB_MESSAGE, projection, selection, selectionArgs, null, null, sortOrder); //Register content observer to observe data changes cursor.setNotificationUri(getContext().getContentResolver(), BASE_URI); return cursor; default: throw new IllegalArgumentException("unrecognized uri" + uri); } } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { switch (matcher.match(uri)) { case CODE_MESSAGE_INSERT: long rowId = db.insert(DB_MESSAGE, null, values); if (rowId == -1) { //add failed return null; } else { //Send content broadcast getContext().getContentResolver().notifyChange(BASE_URI, null); //Added successfully return ContentUris.withAppendedId(uri, rowId); } default: throw new IllegalArgumentException("unrecognized uri" + uri); } } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { switch (matcher.match(uri)) { case CODE_MESSAGE_DELETE: int number = db.delete(DB_MESSAGE, selection, selectionArgs); //Send content broadcast getContext().getContentResolver().notifyChange(BASE_URI, null); return number; default: throw new IllegalArgumentException("unrecognized uri" + uri); } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { switch (matcher.match(uri)) { case CODE_MESSAGE_UPDATE: int number = db.update(DB_MESSAGE, values, selection, selectionArgs); //Send content broadcast getContext().getContentResolver().notifyChange(BASE_URI, null); return number; default: throw new IllegalArgumentException("unrecognized uri" + uri); } } }
<provider android:name=".Provider.MyMessageProvider" android:authorities="com.handsome.nfcc" />
public class MessageDao { /** * adding data */ public static boolean insert(ContentResolver resolver, Message msg) { ContentValues values = new ContentValues(); values.put("content", msg.getContent()); values.put("date", DateUtils.showDate()); resolver.insert(MyMessageProvider.URI.CODE_MESSAGE_INSERT, values); return true; } /** * delete data */ public static void delete(ContentResolver resolver, int id) { resolver.delete(MyMessageProvider.URI.CODE_MESSAGE_DELETE, "id = " + id, null); } /** * delete all data */ public static void deleteAll(ContentResolver resolver) { resolver.delete(MyMessageProvider.URI.CODE_MESSAGE_DELETE, null, null); } /** * Query data * * @param resolve * @return */ public static List<Message> query(ContentResolver resolver) { List<Message> list = new ArrayList<>(); Cursor cursor = resolver.query(MyMessageProvider.URI.CODE_MESSAGE_QUERY, null, null, null, null); while (cursor.moveToNext()) { Message msg = new Message(); msg.setDate(cursor.getString(cursor.getColumnIndex("date"))); msg.setContent(cursor.getString(cursor.getColumnIndex("content"))); msg.setId(cursor.getInt(cursor.getColumnIndex("id"))); list.add(0, msg); } return list; } }
Optimization of ContentProvider
There are often many databases in a project. At this time, instead of repeatedly writing the ContentProvider code, all databases are placed in a ContentProvider, a method for querying the table name is provided, and the corresponding table is operated.
Step 1: Code optimization of ContentProvider (one set of code applies to multiple databases)
public class MyDataProvider extends ContentProvider { //data storage name public final static String DB_DATA = "data"; public final static String DB_FETCH = "fetch"; public final static String DB_MESSAGE = "message"; // put a database CommonOpenHelper helper; SQLiteDatabase db; UriMatcher matcher = new UriMatcher (UriMatcher.NO_MATCH); // own matching rules final static int CODE_DATA = 0; final static int CODE_FETCH = 1; final static int CODE_MESSAGE = 2; //CPU name final static String authority = "com.handsome.nfc"; final static Uri BASE_URI = Uri.parse("content://com.handsome.nfc"); //Write the matching rule for the hostname { matcher.addURI(authority, "data", CODE_DATA); matcher.addURI(authority, "fetch", CODE_FETCH); matcher.addURI(authority, "message", CODE_MESSAGE); } // URI provided externally public interface URI { Uri DATA_CONTENT_URI = Uri.parse(BASE_URI + "/data"); Uri FETCH_CONTENT_URI = Uri.parse(BASE_URI + "/fetch"); Uri MESSAGE_CONTENT_URI = Uri.parse(BASE_URI + "/message"); } /** * Get database table name * * @param uri * @return */ private String getTableName(Uri uri) { String tableName = null; switch (matcher.match(uri)) { case CODE_DATA: tableName = DB_DATA; break; case CODE_FETCH: tableName = DB_FETCH; break; case CODE_MESSAGE: tableName = DB_MESSAGE; break; default: break; } return tableName; } @Override public boolean onCreate() { helper = CommonOpenHelper.getInstance(getContext()); db = helper.getWritableDatabase(); return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String tableName = getTableName(uri); if (tableName == null) { throw new IllegalArgumentException("非法Uri:" + uri); } Cursor cursor = db.query(tableName, projection, selection, selectionArgs, null, null, sortOrder); //Register content observer to observe data changes cursor.setNotificationUri(getContext().getContentResolver(), BASE_URI); return cursor; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { String tableName = getTableName(uri); if (tableName == null) { throw new IllegalArgumentException("非法Uri:" + uri); } long rowId = db.insert(tableName, null, values); if (rowId == -1) { return null; } else { //Send content broadcast getContext().getContentResolver().notifyChange(BASE_URI, null); return ContentUris.withAppendedId(uri, rowId); } } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { String tableName = getTableName(uri); if (tableName == null) { throw new IllegalArgumentException("非法Uri:" + uri); } int number = db.delete(tableName, selection, selectionArgs); //Send content broadcast getContext().getContentResolver().notifyChange(BASE_URI, null); return number; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { String tableName = getTableName(uri); if (tableName == null) { throw new IllegalArgumentException("非法Uri:" + uri); } int number = db.update(tableName, values, selection, selectionArgs); //Send content broadcast getContext().getContentResolver().notifyChange(BASE_URI, null); return number; } }
Step 2: Use in different databases
Data database query example by name
private static boolean queryDataByName(ContentResolver resolver, String tag_id) { Cursor cursor = resolver.query(MyDataProvider.URI.DATA_CONTENT_URI, null, "tag_id = '" + tag_id + "'", null, null); if (cursor.moveToFirst()) { return true; } return false; }Fetch database insert example
public static boolean insert(ContentResolver resolver, Fetch fetch) { ContentValues values = new ContentValues(); values.put("fetch_num", fetch.getFetch_num()); values.put("username", fetch.getUsername()); values.put("installationId", fetch.getInstallationId()); values.put("created", fetch.getCreated()); values.put("date", System.currentTimeMillis()); resolver.insert(MyDataProvider.URI.FETCH_CONTENT_URI, values); return true; }Message database query example
public static List<Message> query(ContentResolver resolver) { List<Message> list = new ArrayList<>(); Cursor cursor = resolver.query(MyDataProvider.URI.MESSAGE_CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { Message msg = new Message(); msg.setDate(cursor.getString(cursor.getColumnIndex("date"))); msg.setContent(cursor.getString(cursor.getColumnIndex("content"))); msg.setId(cursor.getInt(cursor.getColumnIndex("id"))); list.add(0, msg); } return list; }