android中数据存储的contentprovider的使用方法
元数据接口
package com.example.contentproviderprojecrt;
import android.net.Uri;
import android.provider.BaseColumns;
public interface MLDNbatabaseMetaData {
//外部访问,content地址://com.example.contentproviderproject
public static final String AUTHORITY="com.example.contentproviderproject";
//数据库的名称
public static final String DATABASE_NAME="mldn.db";
//数据库的版本
public static final int VERSION=1;
//member表的元素定义,直接继承与_ID和_COUNT静态变量
public static interface MemberTableMetaData extends BaseColumns{
//数据表的名称
public static final String TABLE_NAME="member";
//外部访问的URI地址
public static final Uri CONTENT_URI=Uri.parse("content://"+
AUTHORITY+"/"+TABLE_NAME);
//取得member表中的所有数据
public static final String CONTACT_LIST="vnd.android.cursor.dir/vnd.contentproviderproject.member";
//取得一个member信息
public static final String CONTACT_ITEM="vnd.android.cursor.item/vnd.contentproviderproject.member";
//字段名称
public static final String MEMBER_NAME="name";
public static final String MEMBER_AGE="age";
public static final String MEMBER_BIRTHDAY="birthday";
//显示时候的排序字段
public static final String SORT_ORDER="_id DESC";
}
}
定义数据库操作类助手
package com.example.contentproviderprojecrt;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDatabaseHelper extends SQLiteOpenHelper {
public MyDatabaseHelper(Context context) {
//创建数据库
super(context, MLDNbatabaseMetaData.DATABASE_NAME, null, MLDNbatabaseMetaData.VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建表
String sql="CREATE TABLE "+MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME+" ("
+MLDNbatabaseMetaData.MemberTableMetaData._ID+" INTEGER PRIMARY KEY,"
+MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_NAME+" VARCHAR(50) NOT NULL,"
+MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_AGE+" INTEGER NOT NULL,"
+MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_BIRTHDAY+" DATE NOT NULL"
+")";
db.execSQL(sql);//执行SQL语句
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//更新表
String sql="DROP TABLE IF EXISTS "+MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME;
db.execSQL(sql);//执行SQL语句
this.onCreate(db);//更新数据库
}
}
定义表操作contentProvider类
package com.example.contentproviderprojecrt;
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.net.Uri;
public class MemberContentProvider extends ContentProvider {
private static UriMatcher uriMatcher=null; //定义UriMatcher对象
private static final int GET_MEMBER_LIST=1; //查询全部的常量标记
private static final int GET_MEMBER_ITEM=2; //根据ID查询的常量标记
private MyDatabaseHelper helper=null; //数据库操作类对象
static{
uriMatcher=new UriMatcher(uriMatcher.NO_MATCH); //实例化UriMatcher
uriMatcher.addURI(MLDNbatabaseMetaData.AUTHORITY,
MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, GET_MEMBER_LIST);//增加匹配项
uriMatcher.addURI(MLDNbatabaseMetaData.AUTHORITY,
MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME+"/#", GET_MEMBER_ITEM);//增加匹配项
}
//删除数据操作
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db=this.helper.getWritableDatabase(); //以写的方式打开
int result=0;//操作结果
switch(uriMatcher.match(uri)){//匹配传入的Uri
case GET_MEMBER_LIST:
result=db.delete(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, selection, selectionArgs);
break;
case GET_MEMBER_ITEM:
long id=ContentUris.parseId(uri);
String where="_id="+id;
result=db.delete(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, where, selectionArgs);
break;
default:
throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);
}
return result;
}
@Override
public String getType(Uri uri) {
switch(uriMatcher.match(uri)){//匹配传入的Uri
case GET_MEMBER_LIST:
return MLDNbatabaseMetaData.MemberTableMetaData.CONTACT_LIST;
case GET_MEMBER_ITEM:
return MLDNbatabaseMetaData.MemberTableMetaData.CONTACT_ITEM;
default:
throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);//抛出异常
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db=this.helper.getWritableDatabase();//以写的方式打开
long id=0; //增加之后的ID
switch(uriMatcher.match(uri)){//匹配传入的Uri
case GET_MEMBER_LIST:
id=db.insert(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME,
MLDNbatabaseMetaData.MemberTableMetaData._ID, values);
String uriPath=uri.toString();//取出地址
String path=uriPath+"/"+id; //建立新的URI地址
return Uri.parse(path);
case GET_MEMBER_ITEM:
return null;
default:
throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);
}
}
@Override
public boolean onCreate() {
this.helper=new MyDatabaseHelper(super.getContext()); //实例化DatabaseHelper
return true; //操作成功
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase db=this.helper.getReadableDatabase();//以读的方式打开
switch(uriMatcher.match(uri)){ //匹配传入的Uri
case GET_MEMBER_LIST:
return db.query(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME,
projection, selection, selectionArgs, null, null, sortOrder);
case GET_MEMBER_ITEM:
long id=ContentUris.parseId(uri);
String where="_id="+id;
return db.query(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, projection, where, selectionArgs, null, null, sortOrder);
default:
throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);
}
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db=this.helper.getWritableDatabase();//以写的方式打开
int result=0; //操作结果
switch(uriMatcher.match(uri)){//匹配传入的Uri
case GET_MEMBER_LIST:
result=db.update(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, values, null, null);
break;
case GET_MEMBER_ITEM:
long id=ContentUris.parseId(uri);
String where="_id="+id;
result=db.update(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, values, where, selectionArgs);
break;
default:
throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);
}
return result;
}
}
Acitivity程序
package com.example.contentproviderprojecrt;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button insertBut=null;
private Button updateBut=null;
private Button deleteBut=null;
private Button queryBut=null;
private ListView memberList=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.insertBut=(Button)super.findViewById(R.id.insertBut);//获取按钮
this.insertBut.setOnClickListener(new InsertOnClickListener());//设置按钮单击事件
this.updateBut=(Button)super.findViewById(R.id.updateBut);//获取按钮
this.updateBut.setOnClickListener(new UpdateOnClickListener());//设置按钮单击事件
this.deleteBut=(Button)super.findViewById(R.id.deleteBut);//获取按钮
this.deleteBut.setOnClickListener(new DeleteOnClickListener());//设置按钮单击事件
this.queryBut=(Button)super.findViewById(R.id.queryBut);//获取按钮
this.queryBut.setOnClickListener(new QueryOnClickListener());//设置按钮单击事件
this.memberList=(ListView)super.findViewById(R.id.memberList);//获取ListView
}
private class QueryOnClickListener implements OnClickListener{//查询按钮事件
@Override
public void onClick(View v) {
Cursor result=MainActivity.this.textQuery(null);//查询的结果集
List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();//用于设置SimpleAdapter
for(result.moveToFirst();!result.isAfterLast();result.moveToNext()){//循环取出数据
Map<String,Object> map=new HashMap<String, Object>();
map.put("_id", result.getInt(0));
map.put("name", result.getString(1));
map.put("age", result.getInt(2));
map.put("birthday", result.getString(3));
list.add(map); //保存取出的数据
}
MainActivity.this.memberList.setAdapter(new SimpleAdapter(
MainActivity.this, //将数据包装
list, //数据集合
R.layout.member,//显示的布局文件
new String[]{"_id","name","age","birthday"}, //匹配的Map key
new int[]{R.id._id,R.id.name,R.id.age,R.id.birthday})); //布局文件里面对应的ID
}
}
private class DeleteOnClickListener implements OnClickListener{//删除按钮事件
@Override
public void onClick(View v) {
long result=0;//返回删除了多少条数据
result=MainActivity.this.textDelete(String.valueOf(2));
Toast.makeText(MainActivity.this, "result="+result, Toast.LENGTH_LONG).show();
}
}
private class UpdateOnClickListener implements OnClickListener{//更新按钮事件
@Override
public void onClick(View v) {
long result=0;//返回更新了多少条数据
result=MainActivity.this.textUpdate("1", "李元静", 18, "1998-01-01");
Toast.makeText(MainActivity.this, "result="+result, Toast.LENGTH_LONG).show();
}
}
private class InsertOnClickListener implements OnClickListener{//增加按钮事件
@Override
public void onClick(View v) {
long id=0;//保存接受ID
id=MainActivity.this.textInsert("李元静", 21, new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
Toast.makeText(MainActivity.this, "id="+id, Toast.LENGTH_LONG).show();
}
}
private Cursor textQuery(String _id){
if(_id==null || "".equals(_id)){//查询全部数据
return super.getContentResolver().query(
MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI
, null, null, null,
MLDNbatabaseMetaData.MemberTableMetaData.SORT_ORDER);
}else{//查询指定ID数据
return super.getContentResolver().query(
Uri.withAppendedPath(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, _id)
, null, null, null,
MLDNbatabaseMetaData.MemberTableMetaData.SORT_ORDER);
}
}
private long textDelete(String _id){
ContentResolver contentSesolver=super.getContentResolver();//定义取得ContentResolver对象
int result=0;
if(_id==null || "".equals(_id)){//删除全部数据
result=contentSesolver.delete(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, null, null);
}else{//删除指定数据
result=contentSesolver.delete(Uri.withAppendedPath(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, _id), null, null);
}
return result;
}
private long textInsert(String name,int age,String birthday){
ContentResolver contentSesolver=null;//定义ContentResolver
contentSesolver=super.getContentResolver();//取得contentSesolver
ContentValues values=new ContentValues();//设置内容
values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_NAME, name);
values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_AGE, age);
values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_BIRTHDAY, birthday);
Uri resultUri=contentSesolver.insert(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, values);
return ContentUris.parseId(resultUri);//解析ID返回
}
private long textUpdate(String _id,String name,int age,String birthday){
long result=0;
ContentResolver contentSesolver=null; //定义ContentResolver
contentSesolver=super.getContentResolver();//取得contentSesolver
ContentValues values=new ContentValues();//设置内容
values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_NAME, name);
values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_AGE, age);
values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_BIRTHDAY, birthday);
if(_id==null || "".equals(_id)){//更新全部
result=contentSesolver.update(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, values, null, null);
}else{//更新制定数据
result=contentSesolver.update(
Uri.withAppendedPath(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI,
_id), values, null, null);
}
Uri resultUri=contentSesolver.insert(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, values);
return result;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Layout:activity_mail.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/insertBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加数据"/>
<Button
android:id="@+id/updateBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改数据"/>
<Button
android:id="@+id/deleteBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="删除数据"/>
<Button
android:id="@+id/queryBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查询数据"/>
</LinearLayout>
<ListView
android:id="@+id/memberList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
member.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow >
<TextView
android:id="@+id/_id"
android:layout_width="30px"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/name"
android:layout_width="100px"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/age"
android:layout_width="30px"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/birthday"
android:layout_width="150px"
android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
版权声明:本文为博主原创文章,未经博主允许不得转载。