-
BookProvider
package com.example.language.provider; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.example.language.data.ProviderDB; public class BookProvider extends ContentProvider { private static final String TAG = "BookProvider"; private static final String AUTHORITY = "com.example.language.book.provider"; private static final int BOOK_URI_CODE = 0; private static final int USER_URI_CODE = 1; private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { uriMatcher.addURI(AUTHORITY, "book", BOOK_URI_CODE); uriMatcher.addURI(AUTHORITY, "user", USER_URI_CODE); } private SQLiteDatabase mDb; private Context mContext; @Override public boolean onCreate() { mContext = getContext(); initProviderDB(); return true; } private void initProviderDB() { mDb = new ProviderDB(mContext).getWritableDatabase(); } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { String table = getTableName(uri); if(table == null) { throw new IllegalArgumentException("Unsupported URI: " + uri); } return mDb.query(table, projection, selection, selectionArgs, null, null, sortOrder); } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { String table = getTableName(uri); if(table == null) { throw new IllegalArgumentException("Unsupported URI: " + uri); } mDb.insert(table, null, values); mContext.getContentResolver().notifyChange(uri, null); return uri; } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { String table = getTableName(uri); if(table == null) { throw new IllegalArgumentException("Unsupported URI: " + uri); } int count = mDb.delete(table, selection, selectionArgs); if(count > 0) { mContext.getContentResolver().notifyChange(uri, null); } return count; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { String table = getTableName(uri); if(table == null) { throw new IllegalArgumentException("Unsupported URI: " + uri); } int row = mDb.update(table, values, selection, selectionArgs); if(row > 0) { mContext.getContentResolver().notifyChange(uri, null); } return row; } private String getTableName(Uri uir) { String tableName = null; switch (uriMatcher.match(uir)) { case BOOK_URI_CODE: tableName = ProviderDB.BOOK_TABLE_NAME; break; case USER_URI_CODE: tableName = ProviderDB.USER_TABLE_NAME; break; default:break; } return tableName; } }
2.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.language">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".ProviderActivity"
android:label="@string/title_activity_provider"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name=".provider.BookProvider"
android:authorities="com.example.language.book.provider" />
</application>
</manifest>
3.数据库
package com.example.language.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class ProviderDB extends SQLiteOpenHelper {
private static final String DB_NAME = "book_provider.db";
public static final String BOOK_TABLE_NAME = "book";
public static final String USER_TABLE_NAME = "user";
private static final int DB_VERSION = 1;
private String CREATE_BOOK_TABLE = "CREATE TABLE IF NOT EXISTS " + BOOK_TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, name Text)";
private String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS " + USER_TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, name Text, sex Text)";
public ProviderDB(@Nullable Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK_TABLE);
db.execSQL(CREATE_USER_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
4.使用
package com.example.language;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ProviderActivity extends Activity implements View.OnClickListener {
private Button mInsert, mUpdate, mDelete, mQuery;
private TextView mTV;
private static Uri bookUri = Uri.parse("content://com.example.language.book.provider/book");
private static final Uri userUri = Uri.parse("content://com.example.language.book.provider/user");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider);
init();
}
private void init() {
mInsert = (Button) findViewById(R.id.insert);
mUpdate = (Button) findViewById(R.id.update);
mDelete = (Button) findViewById(R.id.delete);
mQuery = (Button) findViewById(R.id.query);
mInsert.setOnClickListener(this);
mUpdate.setOnClickListener(this);
mDelete.setOnClickListener(this);
mQuery.setOnClickListener(this);
mTV = (TextView)findViewById(R.id.content);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.insert:
insert();
break;
case R.id.update:
update();
break;
case R.id.delete:
delete();
break;
case R.id.query:
query();
break;
default:break;
}
}
private void query() {
Cursor cursor = getContentResolver().query(bookUri, new String[]{"name"}, null, null, null);
StringBuilder builder = new StringBuilder();
assert cursor != null;
while (cursor.moveToNext()) {
builder.append(cursor.getString(cursor.getColumnIndex("name")));
}
cursor.close();
mTV.setText(builder.toString());
}
private void delete() {
getContentResolver().delete(bookUri, "name = ?", new String[]{"红与黑"});
}
private void update() {
ContentValues values = new ContentValues();
values.put("name", "挑战与机遇");
getContentResolver().update(bookUri, values, "name = ?", new String[]{"战争与和平"});
}
private void insert() {
ContentValues values = new ContentValues();
values.put("name", "战争与和平");
getContentResolver().insert(bookUri, values);
}
}