例子:利用ContentProvider 对 SQLite 数据库进行增删改查操作,见下图:
项目结构:
MyDatabaseOpenHelper.java 定义SQLite数据库
public class MyDatabaseOpenHelper extends SQLiteOpenHelper {
//database name
private static final String DB_NAME = "jereTest.db";
//database version
private static final int DB_VERSION = 1;
//table name
public static final String TABLE_USER = "user";
public static final String TABLE_SCORE = "score";
//user table columns
public static final String USER_ID = "_id";
public static final String USER_NAME = "name";
public static final String USER_AGE = "age";
public static final String USER_HEIGHT = "height";
public static final String USER_ADDRESS = "address";
public static final String[] USER_ALL_COLUMNS = new String[] {
USER_ID,
USER_NAME,
USER_AGE,
USER_HEIGHT,
USER_ADDRESS
};
//score table columns
public static final String SCORE_ID = "_id";
public static final String SCORE_STUDENT_NAME = "name";
public static final String SCORE_MATH = "math";
public static final String SCORE_CHINESE = "chinese";
public static final String SCORE_ENGLISH = "english";
public static final String SCORE_SCIENCE = "science";
public static final String[] SCORE_ALL_COLUMNS = new String[] {
SCORE_ID,
SCORE_STUDENT_NAME,
SCORE_MATH,
SCORE_CHINESE,
SCORE_ENGLISH,
SCORE_SCIENCE
};
//create user table sql
private static final String CREATE_USER_TABLE = "create table " + TABLE_USER + "(" + USER_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + USER_NAME + " TEXT, " + USER_AGE + " INT, "
+ USER_HEIGHT + " INT, " + USER_ADDRESS + " TEXT);";
//create work table sq;
private static final String CREATE_SCORE_TABLE = "create table " + TABLE_SCORE + "("
+ SCORE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SCORE_STUDENT_NAME + " TEXT, " + SCORE_MATH + " INT, " + SCORE_CHINESE
+ " INT, " + SCORE_ENGLISH + " INT, " + SCORE_SCIENCE + " INT);";
public MyDatabaseOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_SCORE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE);
onCreate(db);
}
}
MyContentProvider定义我们的ContentProvider
package com.jere.android_contentprovider_learning;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* @author jere
*/
public class MyContentProvider extends ContentProvider {
private static final String AUTHORITY = "com.jere.android_contentprovider_learning";
public static final Uri USER_TABLE_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + MyDatabaseOpenHelper.TABLE_USER);
public static final Uri SCORE_TABLE_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + MyDatabaseOpenHelper.TABLE_SCORE);
public static final int USER_TABLE_CODE = 1;
public static final int SCORE_TABLE_CODE = 2;
private static final UriMatcher uriMatch = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatch.addURI(AUTHORITY, MyDatabaseOpenHelper.TABLE_USER, USER_TABLE_CODE);
uriMatch.addURI(AUTHORITY, MyDatabaseOpenHelper.TABLE_SCORE, SCORE_TABLE_CODE);
}
private SQLiteDatabase sqLiteDatabase;
/**
* 创建 ContentProvider
*
* @return 如果成功加载provider会返回true, 否则返回false
*/
@Override
public boolean onCreate() {
MyDatabaseOpenHelper myDatabaseOpenHelper = new MyDatabaseOpenHelper(getContext());
sqLiteDatabase = myDatabaseOpenHelper.getWritableDatabase();
return sqLiteDatabase != null;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
Cursor cursor = null;
switch (uriMatch.match(uri)) {
case USER_TABLE_CODE:
cursor = sqLiteDatabase.query(MyDatabaseOpenHelper.TABLE_USER,
MyDatabaseOpenHelper.USER_ALL_COLUMNS,
selection,
selectionArgs,
sortOrder,
null, null);
break;
case SCORE_TABLE_CODE:
cursor = sqLiteDatabase.query(MyDatabaseOpenHelper.TABLE_SCORE,
MyDatabaseOpenHelper.SCORE_ALL_COLUMNS,
selection,
selectionArgs,
sortOrder,
null, null);
break;
default:
throw new IllegalArgumentException("unKnow uri : " + uri);
}
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
String tableName = getTableNameByUri(uri);
long rowId = sqLiteDatabase.insert(tableName, "" , values);
if (rowId > 0) {
Uri uri1 = ContentUris.withAppendedId(USER_TABLE_CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(uri1, null);
return uri1;
}
throw new SQLiteException("failed to add a record into: " + uri);
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
int count = 0;
switch (uriMatch.match(uri)) {
case USER_TABLE_CODE:
count = sqLiteDatabase.delete(MyDatabaseOpenHelper.TABLE_USER, selection, selectionArgs);
break;
case SCORE_TABLE_CODE:
count = sqLiteDatabase.delete(MyDatabaseOpenHelper.TABLE_SCORE, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("unknow uri: " + uri);
}
return count;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values,
@Nullable String selection, @Nullable String[] selectionArgs) {
int count = 0;
switch (uriMatch.match(uri)) {
case USER_TABLE_CODE:
count = sqLiteDatabase.update(MyDatabaseOpenHelper.TABLE_USER, values, selection, selectionArgs);
break;
case SCORE_TABLE_CODE:
count = sqLiteDatabase.update(MyDatabaseOpenHelper.TABLE_SCORE, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("unknow uri: " + uri);
}
return count;
}
private String getTableNameByUri(Uri uri) {
String tableName;
switch (uriMatch.match(uri)) {
case USER_TABLE_CODE:
tableName = MyDatabaseOpenHelper.TABLE_USER;
break;
case SCORE_TABLE_CODE:
tableName = MyDatabaseOpenHelper.TABLE_SCORE;
break;
default:
throw new IllegalArgumentException("unknow uri: " + uri);
}
return tableName;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initLayout();
}
private void initLayout() {
Button insertBtn = findViewById(R.id.insert_btn);
Button updateBtn = findViewById(R.id.update_btn);
Button deleteBtn = findViewById(R.id.delete_btn);
Button queryBtn = findViewById(R.id.query_btn);
Button insertScoreBtn = findViewById(R.id.insert_score_btn);
Button queryScoreBtn = findViewById(R.id.query_score_btn);
insertBtn.setOnClickListener(this);
updateBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
queryBtn.setOnClickListener(this);
insertScoreBtn.setOnClickListener(this);
queryScoreBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.insert_btn:
ContentValues values = new ContentValues();
values.put(MyDatabaseOpenHelper.USER_NAME, "JereChen");
values.put(MyDatabaseOpenHelper.USER_AGE, "24");
values.put(MyDatabaseOpenHelper.USER_HEIGHT, "150");
values.put(MyDatabaseOpenHelper.USER_ADDRESS, "China HZ");
getContentResolver().insert(MyContentProvider.USER_TABLE_CONTENT_URI, values);
break;
case R.id.update_btn:
ContentValues updateValue = new ContentValues();
updateValue.put(MyDatabaseOpenHelper.USER_NAME, "Jere");
updateValue.put(MyDatabaseOpenHelper.USER_AGE, "10000000");
getContentResolver().update(MyContentProvider.USER_TABLE_CONTENT_URI,
updateValue,
MyDatabaseOpenHelper.USER_NAME + "=? ",
new String[]{"JereChen"});
break;
case R.id.delete_btn:
getContentResolver().delete(MyContentProvider.USER_TABLE_CONTENT_URI,
MyDatabaseOpenHelper.USER_NAME + "=? ",
new String[]{"Jere"});
break;
case R.id.query_btn:
Cursor cursor = getContentResolver().query(MyContentProvider.USER_TABLE_CONTENT_URI,
MyDatabaseOpenHelper.USER_ALL_COLUMNS,
null, null, null);
StringBuilder sb = new StringBuilder();
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(MyDatabaseOpenHelper.USER_NAME));
int age = cursor.getInt(cursor.getColumnIndex(MyDatabaseOpenHelper.USER_AGE));
int height = cursor.getInt(cursor.getColumnIndex(MyDatabaseOpenHelper.USER_HEIGHT));
String address = cursor.getString(cursor.getColumnIndex(MyDatabaseOpenHelper.USER_ADDRESS));
sb.append("name:").append(name).append(" ")
.append("age:").append(age).append(" ")
.append("height:").append(height).append(" ")
.append("address:").append(address).append(" ")
.append("\n");
}
cursor.close();
}
TextView userTableTv = findViewById(R.id.user_table_tv);
userTableTv.setText(sb.toString());
break;
case R.id.insert_score_btn:
ContentValues scoreValues = new ContentValues();
scoreValues.put(MyDatabaseOpenHelper.SCORE_STUDENT_NAME, "JereChen");
scoreValues.put(MyDatabaseOpenHelper.SCORE_MATH, 100);
scoreValues.put(MyDatabaseOpenHelper.SCORE_ENGLISH, 80);
scoreValues.put(MyDatabaseOpenHelper.SCORE_CHINESE, 60);
scoreValues.put(MyDatabaseOpenHelper.SCORE_SCIENCE, 100);
getContentResolver().insert(MyContentProvider.SCORE_TABLE_CONTENT_URI, scoreValues);
break;
case R.id.query_score_btn:
Cursor queryScoreCursor = getContentResolver().query(MyContentProvider.SCORE_TABLE_CONTENT_URI,
MyDatabaseOpenHelper.SCORE_ALL_COLUMNS,
MyDatabaseOpenHelper.SCORE_STUDENT_NAME + "=? ",
new String[] {"JereChen"},
null);
StringBuilder scoreSb = new StringBuilder();
if (queryScoreCursor != null) {
while(queryScoreCursor.moveToNext()) {
String name = queryScoreCursor.getString(queryScoreCursor.getColumnIndex(MyDatabaseOpenHelper.SCORE_STUDENT_NAME));
int math = queryScoreCursor.getInt(queryScoreCursor.getColumnIndex(MyDatabaseOpenHelper.SCORE_MATH));
int english = queryScoreCursor.getInt(queryScoreCursor.getColumnIndex(MyDatabaseOpenHelper.SCORE_ENGLISH));
int chinese = queryScoreCursor.getInt(queryScoreCursor.getColumnIndex(MyDatabaseOpenHelper.SCORE_CHINESE));
int science = queryScoreCursor.getInt(queryScoreCursor.getColumnIndex(MyDatabaseOpenHelper.SCORE_SCIENCE));
scoreSb.append("name:").append(name).append(" ")
.append("math:").append(math).append(" ")
.append("english:").append(english).append(" ")
.append("chinese:").append(chinese).append(" ")
.append("science:").append(science).append(" ")
.append("\n");
}
queryScoreCursor.close();
}
TextView scoreTableTv = findViewById(R.id.score_table_tv);
scoreTableTv.setText(scoreSb.toString());
break;
default:
break;
}
}
}
完整例子见 -> https://github.com/JereChen11/Android_ContentProvider_Learning