内容提供者------数据库

 

  • 在应用1的内部定义一个内容提供者 
    • URI:统一资源标示符 也表示一个路径 这个路径可以自己定义 
    • URL:统一资源定位符 www.baidu.com 
  • 在内容提供者内部定义一个urimatcher 并且定义一个静态代码块添加匹配规则
    private static final String TAG = "AccountProvider";
    private MyOpenHelper myOpenHelper;
    private static final UriMatcher surimatcher = new UriMatcher(UriMatcher.NO_MATCH);
    private static final int QUERYSUCCESS = 10;
    private static final int INSERTSUCCESS = 20;
    private static final int DELETESUCCESS = 30;
    private static final int UPDATESUCCESS = 40;

    static {
        surimatcher.addURI("ngyb.ltz", "query", QUERYSUCCESS);
        surimatcher.addURI("ngyb.ltz", "insert", INSERTSUCCESS);
        surimatcher.addURI("ngyb.ltz", "delete", DELETESUCCESS);
        surimatcher.addURI("ngyb.ltz", "update", UPDATESUCCESS);
    }
  • 把增删改查方法暴漏出去
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        int code = surimatcher.match(uri);
        if (code == QUERYSUCCESS) {
            SQLiteDatabase db = myOpenHelper.getReadableDatabase();
            Cursor cursor = db.query("info", projection, selection, selectionArgs, null, null, null);
            getContext().getContentResolver().notifyChange(uri, null);
            Log.e(TAG, "query: ");
            return cursor;
        } else {
            throw new IllegalArgumentException("哥们地址错了");
        }
//        return null;
    }
  • 其他应用程序提供内容解析者操作数据库
                Uri uri = Uri.parse("content://ngyb.ltz/insert");
                ContentValues values = new ContentValues();
                values.put("name", "小成");
                values.put("phone", "15935416849");
                values.put("money", 5201314);
                Uri uril = getContentResolver().insert(uri, values);
                Toast.makeText(this, "插入成功", Toast.LENGTH_SHORT).show();

猜你喜欢

转载自www.cnblogs.com/nangongyibin/p/10233686.html