zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

android contentprovider增删改查(访问其他app的数据)

AndroidApp数据 访问 其他 增删 改查 contentprovider
2023-09-14 09:05:10 时间

一、基本概念:
1.ContentProvider为存储和获取数据提供了统一的接口;
2.使用ContentProvider可以在不同的应用程序之间共享数据;
3.Android为常见的一些数据提供了ContentProvider(包括音频、视频、图片和通讯录等等 )
直接贴下代码:
定义数据库帮助类:

package com.xinrui.smartboard.contentprovider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbOpenHelper extends SQLiteOpenHelper {

    //数据库名称
    private static final String DATA_BASE_NAME = "inputsource.db";

    //数据库版本号
    private static final int DATE_BASE_VERSION = 1;

    //表名-男孩
    public static final String SOURCE_TABLE_NAME = "source";


    //创建表-输入源(两列:主键自增长、姓名)
    private final String CREATE_SOURCE_TABLE = "create table " + SOURCE_TABLE_NAME + "(_id integer primary key autoincrement, inputsource text)";

    public DbOpenHelper(Context context) {
        super(context, DATA_BASE_NAME, null, DATE_BASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_SOURCE_TABLE);//创建信号源表
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //一些数据库升级操作
    }
}

2.contentprovider 内容提供者:

package com.xinrui.smartboard.contentprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class MyFirstContentProvider extends ContentProvider {

    private Context context;

    private SQLiteDatabase sqLiteDatabase;

    public static final String AUTHORITY = "com.xinrui.smartboard.contentprovider.MyFirstContentProvider";

    public static final int SOURCE_URI_CODE = 0;

    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        uriMatcher.addURI(AUTHORITY, DbOpenHelper.SOURCE_TABLE_NAME, SOURCE_URI_CODE);
    }

    /**
     * 获取表名
     * @param uri
     * @return
     */
    private String getTableName(Uri uri) {
        String tableName = null;
        switch (uriMatcher.match(uri)) {
            case SOURCE_URI_CODE:
                tableName = DbOpenHelper.SOURCE_TABLE_NAME;
                break;
        }
        return tableName;
    }



    @Override
    public boolean onCreate() {
        context = getContext();
        initProviderData();
        return false;
    }

    //初始化原始数据
    private void initProviderData() {
        sqLiteDatabase = new DbOpenHelper(context).getWritableDatabase();
        Uri boyUri = Uri.parse("content://com.xinrui.smartboard.contentprovider.MyFirstContentProvider/source");
        Cursor cursor = query(boyUri,null,null,null,null);
        if(cursor!=null) Log.e("MainActivity","count:"+cursor.getCount());
        if(cursor!=null&&cursor.getCount()!=0)return;
        sqLiteDatabase.beginTransaction();
        ContentValues contentValues = new ContentValues();
        contentValues.put("inputsource", "24");
        sqLiteDatabase.insert(DbOpenHelper.SOURCE_TABLE_NAME, null, contentValues);
        sqLiteDatabase.setTransactionSuccessful();
        sqLiteDatabase.endTransaction();
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        String tableName = getTableName(uri);
        if (TextUtils.isEmpty(tableName)) {
            throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        return sqLiteDatabase.query(tableName, projection, selection, selectionArgs, null, null, sortOrder);
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert( Uri uri, ContentValues values) {
        String tableName = getTableName(uri);
        if(TextUtils.isEmpty(tableName)){
            throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        sqLiteDatabase.insert(tableName, null, values);
        context.getContentResolver().notifyChange(uri, null);
        return uri;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        String tableName = getTableName(uri);
        if (TextUtils.isEmpty(tableName)) {
            throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        int count = sqLiteDatabase.delete(tableName, selection, selectionArgs);
        if (count > 0) {
            context.getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values,String selection,String[] selectionArgs) {
        String tableName = getTableName(uri);
        if (TextUtils.isEmpty(tableName)) {
            throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        int row = sqLiteDatabase.update(tableName, values, selection, selectionArgs);
        if (row > 0) {
            context.getContentResolver().notifyChange(uri, null);
        }
        return row;
    }
}

3.注册 contentprovider

 <provider
            android:name=".contentprovider.MyFirstContentProvider"
            android:exported="true"
            android:authorities="com.xinrui.smartboard.contentprovider.MyFirstContentProvider" />

4.更新

private void updateContentProvider(String value){
        Uri boyUri = Uri.parse("content://com.xinrui.smartboard.contentprovider.MyFirstContentProvider/source");
        ContentValues contentValues = new ContentValues();
        contentValues.put("inputsource", value);
        getContentResolver().update(boyUri,contentValues,"_id=1",null);
    }

5.查询

 private String queryContentProvider(){
	    String inputsource = "";
        Uri boyUri = Uri.parse("content://com.xinrui.smartboard.contentprovider.MyFirstContentProvider/source");
        Cursor boyCursor = getContentResolver().query(boyUri, new String[]{"_id", "inputsource"}, null, null, null);
        if (boyCursor != null) {
            if (boyCursor.moveToNext()) {
                //Log.e(TAG, "ID:" + boyCursor.getInt(boyCursor.getColumnIndex("_id")) + "--inputsource:" + boyCursor.getString(boyCursor.getColumnIndex("inputsource")));
				inputsource = boyCursor.getString(boyCursor.getColumnIndex("inputsource"));
            }
            boyCursor.close();
        }
		return inputsource;
    }

6.添加数据

Uri boyUri = Uri.parse("content://com.xinrui.smartboard.contentprovider.MyFirstContentProvider/source");
    ContentValues contentValues = new ContentValues();
    contentValues.put("name", "张三");
    getContentResolver().insert(boyUri, contentValues);

7.删除数据

public void testDelete(){
		
		//另外一个程序的uri
		Uri uri = Uri.parse("content://com.xinrui.smartboard.contentprovider.MyFirstContentProvider/source");
		//获取内容提供者访问对象
		ContentResolver resolver = getContext().getContentResolver();
		String where = "_id=?";
		String[] selectionArgs={"8"};
		int count = resolver.delete(uri, where, selectionArgs);
		Log.i(tag, "删除了"+count);
	}