第一步数据库的建立
public class MyDatabaseHelp extends SQLiteOpenHelper {
private static final String DB_NAME = "person.db";
private static final int version = 1;
public MyDatabaseHelp(@Nullable Context context) {
super(context,DB_NAME,null,version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table person(" +
"id integer primary key," +
"name varchar(20) not null," +
"age Integer," +
"birthday date)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
创建ContentProvider
public class MyContentProvider extends ContentProvider {
private MyDatabaseHelp dbHelp;
private SQLiteDatabase db;
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public String getType(Uri uri) {
// TODO: Implement this to handle requests for the MIME type of the data
// at the given URI.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public Uri insert(Uri uri, ContentValues values) {
Log.e("zhy","数据插入 Uri == " + uri + " contentValues == " + values);
long person = db.insert("person", null, values);
Log.e("zhy","数据 id == " + person);
Uri uri1 = ContentUris.withAppendedId(uri, person);
return uri1;
}
@Override
public boolean onCreate() {
dbHelp = new MyDatabaseHelp(getContext());
db = dbHelp.getWritableDatabase();
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Log.e("zhy","数据查询");
Cursor cursor = db.query("person", null, null, null, null, null, null);
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO: Implement this to handle requests to update one or more rows.
throw new UnsupportedOperationException("Not yet implemented");
}
使用ContentResolver 进行增删改查
switch (v.getId()) {
case R.id.btn_insert:
ContentValues contentValues = new ContentValues();
contentValues.put("name","haige");
contentValues.put("age","13");
resolver.insert(uri,contentValues);
break;
case R.id.btn_query:
Cursor query = resolver.query(uri, null, null, null, null);
Log.e("zhy","数据数量 == " + query.getCount());
while(query.moveToNext()) {
//for (int i = 0;i < query.getColumnCount();i++) {
Log.e("zhy","数据 == " + query.getString(1));
//}
}
query.close();
break;
}