zoukankan      html  css  js  c++  java
  • Android基础之内容提供者的实现

    内容提供者可以实现应用间查询数据库的需求

    一.在提供数据库访问的应用设置内容提供者

    public class AccountProvider extends ContentProvider {
        static final int QUERYSUCCESS=0;
    
        private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
        static {
            sURIMatcher.addURI("com.eason.provider","query",0);
        }
    /*
        *selectionArg查询参数
        *selection查询条件
        */
        @Override
        public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder) {
            int code=sURIMatcher.match(uri);
            if(code==QUERYSUCCESS){
                SQLiteDatabase db =new MyOpenHelper(getContext()).getReadableDatabase();
                Cursor cursor=db.query("info",projection,selection,selectionArgs,null,null,null);
                return cursor;
            }else throw new IllegalArgumentException("路径有问题啊兄弟");
        }
    
    }
    • 记得在清单文件中配置组件
    • 在清单文件里provider节点的exported属性设置为true,没有设置将会报错
    • exported属性作用:是否支持其它应用调用当前组件。默认值:如果包含有intent-filter 默认值为true; 没有intent-filter默认值为false.

    二.在访问数据库的应用内实现内容解释者

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            ContentResolver cr=getContentResolver();
            Uri uri=Uri.parse("content://com.eason.provider/query");
            Cursor cursor=cr.query(uri,null,null,null,null);
            if (cursor.getCount()>0&&cursor!=null){
            while(cursor.moveToNext()){
                System.out.println(cursor.getString(1));
                System.out.println(cursor.getString(2));
            }
            }
        }
    • 执行query操作时,设置uri要根据内容提供者中的sURIMatcher.addURI("com.eason.provider","query",0)来写.
  • 相关阅读:
    新手上路:Laravel-控制器基础
    新手上路:Laravel-控制器基础
    新手上路:Laravel-控制器基础
    js限制文本框input只能输入数字
    66条财富语录
    赢在中国 第3讲思维篇
    赢在中国 ---对周宇的分析
    赢在中国 第二季 语录
    《赢在中国》第三季观后感
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
  • 原文地址:https://www.cnblogs.com/adressian/p/10069574.html
Copyright © 2011-2022 走看看