#Android SQLite数据结合ContentProvider实现数据的一个增删改查操作
使用ContentProvider控制数据库,可以实现程序本身数据的增删改查,也可让别的程序对本程序的数据库进行增删改查操作,只需要在AndroidManifest中改属性exported,是true还是false就可以了。
本文也提供一个示例程序,这个示例程序是一个新项目中需要用到的,并且封装比较好,逻辑清晰,对于后期添加多个数据库表格管理起来很方便。
效果图:
该示例没有输入操作,简单实现了增删改查操作,具体的实现和控制看代码即可。
###1、DBOpenHelper类
package com.liwenzhi.asr.sqlitedemo.provider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.liwenzhi.asr.sqlitedemo.table.PeopleInfoTable;
import com.liwenzhi.asr.sqlitedemo.util.LogUtil;
//控制数据库的创建和删除的类
public class DBOpenHelper extends SQLiteOpenHelper {
//这里数据库路径是默认的路径,如果需要也是可以放在SD卡下的,只需要将下面的数据库名称改为“sdcard/demo/file.db”
//但是要注意,如果存储在sd卡下是需要手机的读取权限的,如果放在包名下是不需要手机读写权限的
private static final String DATABASE_NAME = "file.db"; //默认路径(/data/data/package/...)+数据库名称
private static final int DATABASE_VERSION = 1;//数据库版本
private final String TAG = "DBOpenHelper";
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
LogUtil.i(TAG, "DBOpenHelper:DATABASE_NAME=" + DATABASE_NAME + ",DATABASE_VERSION=" + DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
LogUtil.i(TAG, "DBOpenHelper onCreate");
db.execSQL(PeopleInfoTable.CREATE_PEOPLE_INFO_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
LogUtil.e(TAG, "DBOpenHelper onUpgrade:oldVersion=" + oldVersion + ",newVersion=" + newVersion);
db.execSQL("DROP TABLE IF EXISTS " + PeopleInfoTable.TABLE_NAME); //删除表格
onCreate(db); //重新创建表格
}
}
###2、SqliteProvider类
package com.liwenzhi.asr.sqlitedemo.provider;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import com.liwenzhi.asr.sqlitedemo.table.PeopleInfoTable;
import com.liwenzhi.asr.sqlitedemo.util.LogUtil;
//真正实现控制数据库增删改查的代码类
public class SqliteProvider extends ContentProvider {
private DBOpenHelper dbOpenHelper;
private static final UriMatcher MATCHER;
private String TAG = "SqliteProvider-->";
private final Object mLock = new Object();
//Uri info
//authority
public static final String PEOPLE_INFO_AUTHORITY = "com.demo.FileProvider";
public static final Uri AUTHORITY_URI = Uri.parse("content://" + PEOPLE_INFO_AUTHORITY);
//code
private static final int PEOPLE_INFO_CODE = 1;
static {
MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
MATCHER.addURI(PEOPLE_INFO_AUTHORITY, PeopleInfoTable.TABLE_NAME, PEOPLE_INFO_CODE);
}
@Override
public boolean onCreate() {
Log.d(TAG, " onCreate ");
this.dbOpenHelper = new DBOpenHelper(this.getContext());
return true;
}
@Override
public String getType(Uri uri) {
return null;
}
/**
* 查询数据库的数据
*
* @param uri
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Log.d(TAG, " query ");
try {
synchronized (mLock) {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
switch (MATCHER.match(uri)) {
case PEOPLE_INFO_CODE:
return db.query(PeopleInfoTable.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
} catch (SQLException e) {
LogUtil.e(TAG, "query error:" + e.getMessage());
return null;
}
}
/**
* 插入数据
*
* @param uri
* @param values
* @return
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
Log.d(TAG, " insert ");
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
switch (MATCHER.match(uri)) {
case PEOPLE_INFO_CODE:
// 特别说一下第二个参数是当name字段为空时,将自动插入一个NULL。
long rowid = db.insert(PeopleInfoTable.TABLE_NAME, null, values);
Uri insertUri = ContentUris.withAppendedId(uri, rowid);// 得到代表新增记录的Uri
this.getContext().getContentResolver().notifyChange(uri, null);
return insertUri;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
/**
* 删除数据
*
* @param uri
* @param selection
* @param selectionArgs
* @return
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
int count = 0;
switch (MATCHER.match(uri)) {
case PEOPLE_INFO_CODE:
count = db.delete(PeopleInfoTable.TABLE_NAME, selection, selectionArgs);
return count;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
/**
* 修改数据
*
* @param uri
* @param values
* @param selection
* @param selectionArgs
* @return
*/
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
int count = 0;
switch (MATCHER.match(uri)) {
case PEOPLE_INFO_CODE:
count = db.update(PeopleInfoTable.TABLE_NAME, values, selection, selectionArgs);
return count;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
}
###3、PeopleInfo类
package com.liwenzhi.asr.sqlitedemo.bean;
/**
* 人物信息
*/
public class PeopleInfo {
private int id;
private String name;
private int age;
private int height;
private float weight;
private String remark;
public PeopleInfo() {
}
public PeopleInfo(String name, int age, int height, float weight, String remark) {
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
this.remark = remark;
}
public PeopleInfo(int id, String name, int age, int height, float weight, String remark) {
this.id = id;
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
this.remark = remark;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "PeopleInfo{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", height=" + height +
", weight=" + weight +
", remark='" + remark + '\'' +
'}';
}
}
###4、PeopleInfoTable类
package com.liwenzhi.asr.sqlitedemo.table;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import com.liwenzhi.asr.sqlitedemo.bean.PeopleInfo;
import com.liwenzhi.asr.sqlitedemo.provider.SqliteProvider;
/**
* 管理单个表格的类,
*定义了对应的字符串
*创建表格的语句
*设置对象和获取对象的语句
*/
public class PeopleInfoTable {
//表名称
public static final String TABLE_NAME = "filePath";
//表格的基本信息的字符串
public static final String ID = "_id";
public static final String NAME = "name";
public static final String AGE = "age";
public static final String HEIGHT = "height";
public static final String WEIGHT = "weight";
public static final String REMARK = "remark";
//创建个人信息表格的字符串命令 ,四个属性自增主键id,姓名,年龄,身高,体重,备注
public static final String CREATE_PEOPLE_INFO_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " TEXT," + AGE + " INTEGER, " + HEIGHT + " INTEGER, " +
WEIGHT + " FLOAT, " + REMARK + " TEXT)";
//需要进行操作的uri对象
private static final Uri CONTENT_URI = Uri.withAppendedPath(SqliteProvider.AUTHORITY_URI, TABLE_NAME);
//返回PeopleInfo表格操作的uri地址对象
public static Uri getContentUri() {
return CONTENT_URI;
}
public static ContentValues putValues(PeopleInfo info) {
ContentValues values = new ContentValues();
values.put(NAME, info.getName());
values.put(AGE, info.getAge());
values.put(HEIGHT, info.getHeight());
values.put(WEIGHT, info.getWeight());
values.put(REMARK, info.getRemark());
return values;
}
public static PeopleInfo getValues(Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(ID));
String name = cursor.getString(cursor.getColumnIndex(NAME));
int age = cursor.getInt(cursor.getColumnIndex(AGE));
int height = cursor.getInt(cursor.getColumnIndex(HEIGHT));
float weight = cursor.getFloat(cursor.getColumnIndex(WEIGHT));
String remark = cursor.getString(cursor.getColumnIndex(REMARK));
PeopleInfo peopleInfo = new PeopleInfo(id, name, age, height, weight, remark);
return peopleInfo;
}
}
###5、DataManager类
package com.liwenzhi.asr.sqlitedemo.manager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.liwenzhi.asr.sqlitedemo.bean.PeopleInfo;
import com.liwenzhi.asr.sqlitedemo.table.PeopleInfoTable;
import java.util.ArrayList;
import java.util.List;
/**
* 数据管理类
*管理所有数据库表格的增删改查操作
*/
public class DataManager {
static final String TAG = "DataManager";
public static void addPeople(Context context, PeopleInfo info) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = PeopleInfoTable.getContentUri();
ContentValues values = PeopleInfoTable.putValues(info);
contentResolver.insert(uri, values);
}
public static void updatePeople(Context context, String name, PeopleInfo info) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = PeopleInfoTable.getContentUri();
ContentValues values = new ContentValues();
values.put(PeopleInfoTable.AGE, info.getAge());
values.put(PeopleInfoTable.HEIGHT, info.getHeight());
values.put(PeopleInfoTable.WEIGHT, info.getWeight());
values.put(PeopleInfoTable.REMARK, info.getRemark());
values.put(PeopleInfoTable.NAME, info.getName());
contentResolver.update(uri, values, PeopleInfoTable.NAME + "=?", new String[]{name});
}
public static void deletePeople(Context context, String name) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = PeopleInfoTable.getContentUri();
contentResolver.delete(uri, PeopleInfoTable.NAME + "=?", new String[]{name});
}
public static PeopleInfo getOnePeople(Context context, String userName) {
PeopleInfo peopleInfo = null;
Uri uri = PeopleInfoTable.getContentUri();
Cursor cursor = context.getContentResolver().query(uri, null, PeopleInfoTable.NAME + "=?", new String[]{userName}, null);
if (cursor != null) {
if (cursor.moveToNext()) {
peopleInfo = PeopleInfoTable.getValues(cursor);
}
cursor.close();
}
return peopleInfo;
}
public static List getAllPeoples(Context context) {
List list = new ArrayList<>();
Uri uri = PeopleInfoTable.getContentUri();
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
PeopleInfo info = PeopleInfoTable.getValues(cursor);
list.add(info);
}
cursor.close();
}
return list;
}
}
###6、MainActivity类
package com.liwenzhi.asr.sqlitedemo.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.liwenzhi.asr.sqlitedemo.R;
import com.liwenzhi.asr.sqlitedemo.adapter.PeopleInfoAdapter;
import com.liwenzhi.asr.sqlitedemo.bean.PeopleInfo;
import com.liwenzhi.asr.sqlitedemo.manager.DataManager;
import java.util.ArrayList;
import java.util.List;
/**
* 该示例是SQLite数据结合ContentProvider实现数据的一个增删改查操作的示例代码
* 该示例的特点是代码清晰,扩展性好
* 简单规范如下:
* 1、数据库用到的数据类,放在bean包下
* 2、每张数据的表格都在table下创建一个对应的类,并且定义该表格对应的字符串数据和设置ContentValues和获取类对象
* 3、DataManager是控制所有数据进行增删改查操作的类,不管是一个数据的一个表格还是多个表格的数据操作
* 4、SqliteProvider是实际的增删改查操作语句
* 5、后面每次添加表格只要添加bean类、Table类、SqliteProvider中添加对应的过滤和操作,DataManager添加对应的控制代码就可以了
*/
public class MainActivity extends AppCompatActivity {
private ListView listView;
private PeopleInfoAdapter adapter;
private List list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}
private void initView() {
listView = findViewById(R.id.listView);
}
private void initData() {
adapter = new PeopleInfoAdapter(this, list);
listView.setAdapter(adapter);
}
//增加数据
public void insertData(View view) {
PeopleInfo peopleInfo = new PeopleInfo("李文志", 18, 170, 61, "reamark:huawei");
DataManager.addPeople(this, peopleInfo);
}
//删除数据
public void deleteData(View view) {
DataManager.deletePeople(this, "李文志");
}
//修改数据
public void updateData(View view) {
PeopleInfo peopleInfo = new PeopleInfo("李文志", 19, 170, 61, "reamark:huawei");
DataManager.updatePeople(this, "李文志", peopleInfo);
}
//查询数据
public void selectData(View view) {
list.clear();
List peopleInfos = DataManager.getAllPeoples(this);
list.addAll(peopleInfos);
adapter.notifyDataSetChanged();
}
//查询单个数据
public void selectOneData(View view) {
PeopleInfo peopleInfo = DataManager.getOnePeople(this, "李文志");
Toast.makeText(this, peopleInfo + "", Toast.LENGTH_SHORT).show();
}
}
####运行上面代码,点击添加数据,在点击查询数据,显示:
####点击查询单个数据:
代码如果需要可以下载查看:
https://download.csdn.net/download/wenzhi20102321/10756729
适当修改代码,就可以用到项目中了。
#共勉:态度决定人生的高度。