android开发中ContentProvider、ContentResolver实现操作

实现这个的方法很简单,我们使用ContentProvider创建一个内容提供者,类似与传统的服务(或网站),ContentResolver是用来控制服务或网站的一个类。下面代码就是ContentResolver用来控制ContentProvider类的增删改查的方法,由于代码太多,所以没有贴出全部代码,代码将会打包上传到网盘。

链接:http://pan.baidu.com/s/1kVbD9x9 密码:vt41

 

//ContentResolver类中读取,按钮事件代码 
class OnClick implements View.OnClickListener{
 private static final String TAG = "OnClickLog";

 private Context mContext;
 private Activity mActivity;
 private View v;
 private EditText book_name,book_money,book_remark;
 private ListView listView;
 private int type;
 private int _id;
 private int position;
 private int res;
 private ContentValues values;
 private int[] toids = {R.id.book_item_id,R.id.book_item_name,R.id.book_item_remark,R.id.book_item_money};
 private String[] strs = {"id","name","remark","money"};

 private ContentResolver resolver;

 private static ArrayList<Map<String,String>> list;
 private static SimpleAdapter adapter;

 public OnClick(Context ctx,int t,int id,int pos){
 mContext = ctx;
 mActivity = (Activity)ctx;
 type = t;
 _id = id;
 position = pos;
 resolver = ctx.getContentResolver();

 book_name = (EditText)mActivity.findViewById(R.id.book_name);
 book_money = (EditText)mActivity.findViewById(R.id.book_money);
 book_remark = (EditText)mActivity.findViewById(R.id.book_remark);

 listView = (ListView)mActivity.findViewById(R.id.book_list);

 }

 @Override
 public void onClick(View v) {
 switch (type){
 case 0://读
 Cursor cursor = resolver.query(Book.Books.ALL_URI,Book.Books.clos,null,null,Book.Books._ID+" desc");
 list = new ArrayList<Map<String,String>>();
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

 while (cursor.moveToNext()){
 Map<String,String> item = new HashMap<String,String>();
 item.put("id",cursor.getString(0));
 item.put("name",cursor.getString(1));
 item.put("money","¥"+cursor.getString(2));
 item.put("remark",cursor.getString(3));
 item.put("add_time",cursor.getString(4));
 Log.i(TAG, "add_time:"+sdf.format(new Date(Long.valueOf(cursor.getString(4)))));
 list.add(item);
 }
 Log.i(TAG,"READ");
 adapter = new SimpleAdapter(mContext,list,R.layout.book_items, strs,toids);
 listView.setAdapter(adapter);
 break;
 case 1://增
 values = new ContentValues();
 values.put("name",book_name.getText().toString());
 values.put("money",book_money.getText().toString());
 values.put("remark",book_remark.getText().toString());
 values.put("add_time", new Date().getTime());

 Uri uri = resolver.insert(Book.Books.ALL_URI,values);
 res = (int)ContentUris.parseId(uri);
 if(res > 0){
 Toast.makeText(mContext,"保存成功!",Toast.LENGTH_LONG).show();
 Map<String,String> item = new HashMap<String,String>();
 item.put("id", String.valueOf(res));
 item.put("name",book_name.getText().toString());
 item.put("money","¥"+book_money.getText().toString());
 item.put("remark",book_remark.getText().toString());
 item.put("add_time", String.valueOf(new Date().getTime()));

 list.add(item);
 adapter.notifyDataSetChanged();

 book_name.setText("");
 book_money.setText("");
 book_remark.setText("");
 }
 Log.i(TAG,uri.toString());
 break;
 case 2://改
 values = new ContentValues();
 values.put("name",book_name.getText().toString());
 values.put("money",book_money.getText().toString());
 values.put("remark", book_remark.getText().toString());
 res = resolver.update(ContentUris.withAppendedId(Book.Books.ONE_URI, _id),values,null,null);
 if(res > 0){
 Toast.makeText(mContext,"保存成功!",Toast.LENGTH_LONG).show();
 book_name.setText("");
 book_money.setText("");
 book_remark.setText("");
 }

 break;
 case 3://删
 res = resolver.delete(ContentUris.withAppendedId(Book.Books.ONE_URI, _id), null, null);
 if(res > 0){
 Toast.makeText(mContext,"删除成功!",Toast.LENGTH_LONG).show();
 book_name.setText("");
 book_money.setText("");
 book_remark.setText("");
 }
 list.remove(position);
 adapter.notifyDataSetChanged();
 break;
 default:
 Log.i(TAG,"Nothing");
 break;
 }


 }
}

 

//ContentProvider类的核心代码 

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;
import android.support.annotation.Nullable;

public class ProviderTest extends ContentProvider {
 private DBHelper dbHelper;
 private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
 private static final int MODE1 = 1;
 private static final int MODE2 = 2;
 private static final String[] clos = {"id","name","money","remark","add_time"};

 static {
 uriMatcher.addURI(Book.AUTHORITY,"/book",MODE1);
 uriMatcher.addURI(Book.AUTHORITY,"/book/#",MODE2);
 }


 @Override
 public boolean onCreate() {
 dbHelper = new DBHelper(this.getContext());
 return false;
 }

 @Nullable
 @Override
 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
 SQLiteDatabase db = dbHelper.getReadableDatabase();

 switch (uriMatcher.match(uri)){
 case MODE1:
 return db.query("book",projection,selection,selectionArgs,null,null,sortOrder);
 case MODE2:
 long id = ContentUris.parseId(uri);
 String where = Book.Books._ID+"="+id;
 if(selection!=null && !"".equals(selection)){
 where = where+" and "+selection;
 }

 return db.query("book",projection,where,selectionArgs,null,null,sortOrder);
 default:
 throw new IllegalArgumentException("Unknown Uri:"+uri);
 }

 }

 @Nullable
 @Override
 public String getType(Uri uri) {
 switch (uriMatcher.match(uri)){
 case MODE1:
 return "vnd.android.cursor.dir/com.test.contentprovider";
 case MODE2:
 return "vnd.android.cursor.item/com.test.contentprovider";
 default:
 throw new IllegalArgumentException("Unknown Uri:"+uri.toString());

 }
 }

 @Nullable
 @Override
 public Uri insert(Uri uri, ContentValues values) {
 SQLiteDatabase db = dbHelper.getReadableDatabase();

 if(uriMatcher.match(uri) == MODE1){
 long id = db.insert("book",Book.Books._ID,values);

 Uri resUri = ContentUris.withAppendedId(uri,id);

 //通知Resolver 数据已经改变
 getContext().getContentResolver().notifyChange(resUri,null);
 return resUri;
 }else{
 throw new IllegalArgumentException("Unknown Uri:"+uri);
 }
 }

 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs) {
 SQLiteDatabase db = dbHelper.getReadableDatabase();
 int num;

 switch (uriMatcher.match(uri)){
 case MODE1:
 //删除全部
 num = db.delete("book",selection,selectionArgs);
 break;
 case MODE2:
 //取出后缀ID
 long _id = ContentUris.parseId(uri);

 //组装where条件
 String where = Book.Books._ID + " = "+_id;
 if(selection != null && !"".equals(selection)){
 where = where +" and "+selection;
 }
 //执行删除
 num = db.delete("book",where,selectionArgs);

 break;
 default:
 throw new IllegalArgumentException("Unknown Uri:"+uri);
 }
 getContext().getContentResolver().notifyChange(uri,null);
 return num;
 }

 @Override
 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
 SQLiteDatabase db = dbHelper.getReadableDatabase();
 int num;
 switch (uriMatcher.match(uri)){
 case MODE1:
 num = db.update("book",values,selection,selectionArgs);
 break;
 case MODE2:
 long _id = ContentUris.parseId(uri);
 String where = Book.Books._ID+"="+_id;

 if(selection!=null && !"".equals(selection)){
 where = where + " and "+selection;
 }

 num = db.update("book",values,where,selectionArgs);

 break;
 default:
 throw new IllegalArgumentException("Unknown Uri:"+uri);
 }
 getContext().getContentResolver().notifyChange(uri,null);
 return num;
 }
}

 

//Books类的公共代码

import android.net.Uri;
import android.provider.BaseColumns;

/**
 * Created by Alan on 2016/05/18 0018.
 */
public class Book {
    public static final String AUTHORITY = "com.test.contentprovider.ProviderTest";

    public static final class Books implements BaseColumns{

        public static final String _ID = "id";
        public static final String NAME = "name";
        public static final String MONEY = "money";
        public static final String REMARK = "remark";
        public static final String ADD_TIME = "add_time";
        public static final String[] clos = {"id","name","money","remark","add_time"};
        public static final Uri ALL_URI = Uri.parse("content://"+AUTHORITY+"/book");
        public static final Uri ONE_URI = Uri.parse("content://"+AUTHORITY+"/book/#");


    }

}

 

 

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |