ContentProvider基础使用

本文展示了如何在Android中实现一个Content Provider来管理书籍和用户数据。通过创建`BookProvider`类,实现了对`book`和`user`表的CRUD操作,并在`AndroidManifest.xml`中配置了权限。同时,给出了使用Content Resolver进行插入、更新、删除和查询数据的示例代码。
摘要由CSDN通过智能技术生成
  1. BookProvider

     package com.example.language.provider;
     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 androidx.annotation.NonNull;
     import androidx.annotation.Nullable;
     import com.example.language.data.ProviderDB;
     
     public class BookProvider extends ContentProvider {
     private static final String TAG = "BookProvider";
     private static final String AUTHORITY = "com.example.language.book.provider";
     private static final int BOOK_URI_CODE = 0;
     private static final int USER_URI_CODE = 1;
     private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
         static {
             uriMatcher.addURI(AUTHORITY, "book", BOOK_URI_CODE);
             uriMatcher.addURI(AUTHORITY, "user", USER_URI_CODE);
         }
     
         private SQLiteDatabase mDb;
         private Context mContext;
     
         @Override
         public boolean onCreate() {
             mContext = getContext();
             initProviderDB();
             return true;
         }
     
         private void initProviderDB() {
             mDb = new ProviderDB(mContext).getWritableDatabase();
         }
     
         @Nullable
         @Override
         public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
             String table = getTableName(uri);
             if(table == null) {
                 throw new IllegalArgumentException("Unsupported URI: " + uri);
             }
     
             return mDb.query(table, projection, selection, selectionArgs, null, null, sortOrder);
         }
     
         @Nullable
         @Override
         public String getType(@NonNull Uri uri) {
             return null;
         }
     
         @Nullable
         @Override
         public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
             String table = getTableName(uri);
             if(table == null) {
                 throw new IllegalArgumentException("Unsupported URI: " + uri);
             }
             mDb.insert(table, null, values);
             mContext.getContentResolver().notifyChange(uri, null);
             return uri;
         }
     
         @Override
         public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
             String table = getTableName(uri);
             if(table == null) {
                 throw new IllegalArgumentException("Unsupported URI: " + uri);
             }
             int count = mDb.delete(table, selection, selectionArgs);
             if(count > 0) {
                 mContext.getContentResolver().notifyChange(uri, null);
             }
             return count;
         }
     
         @Override
         public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
             String table = getTableName(uri);
             if(table == null) {
                 throw new IllegalArgumentException("Unsupported URI: " + uri);
             }
             int row = mDb.update(table, values, selection, selectionArgs);
             if(row > 0) {
                 mContext.getContentResolver().notifyChange(uri, null);
             }
             return row;
         }
     
         private String getTableName(Uri uir) {
             String tableName = null;
             switch (uriMatcher.match(uir)) {
                 case BOOK_URI_CODE:
                     tableName =  ProviderDB.BOOK_TABLE_NAME;
                     break;
                 case USER_URI_CODE:
                     tableName = ProviderDB.USER_TABLE_NAME;
                 break;
                 default:break;
     
             }
             return  tableName;
         }
     }
    

2.AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.language">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ProviderActivity"
            android:label="@string/title_activity_provider"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <provider
            android:name=".provider.BookProvider"
            android:authorities="com.example.language.book.provider" />
    </application>

</manifest>

3.数据库

package com.example.language.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;

public class ProviderDB extends SQLiteOpenHelper {
    private static final String DB_NAME = "book_provider.db";
    public static final String BOOK_TABLE_NAME = "book";
    public static final String USER_TABLE_NAME = "user";
    private static final int DB_VERSION = 1;
    private String CREATE_BOOK_TABLE = "CREATE TABLE IF NOT EXISTS " + BOOK_TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, name Text)";
    private String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS " + USER_TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, name Text, sex Text)";

    public ProviderDB(@Nullable Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK_TABLE);
        db.execSQL(CREATE_USER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

4.使用

package com.example.language;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ProviderActivity extends Activity implements View.OnClickListener {
    private Button mInsert, mUpdate, mDelete, mQuery;
    private TextView mTV;
    private static Uri bookUri = Uri.parse("content://com.example.language.book.provider/book");
    private static final Uri userUri = Uri.parse("content://com.example.language.book.provider/user");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_provider);
        init();
    }

    private void init() {
        mInsert = (Button) findViewById(R.id.insert);
        mUpdate = (Button) findViewById(R.id.update);
        mDelete = (Button) findViewById(R.id.delete);
        mQuery = (Button) findViewById(R.id.query);

        mInsert.setOnClickListener(this);
        mUpdate.setOnClickListener(this);
        mDelete.setOnClickListener(this);
        mQuery.setOnClickListener(this);

        mTV = (TextView)findViewById(R.id.content);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.insert:
                insert();
                break;
            case R.id.update:
                update();
                break;
            case R.id.delete:
                delete();
                break;
            case R.id.query:
                query();
                break;
            default:break;
        }
    }

    private void query() {
        Cursor cursor = getContentResolver().query(bookUri, new String[]{"name"}, null, null, null);
        StringBuilder builder = new StringBuilder();
        assert cursor != null;
        while (cursor.moveToNext()) {
            builder.append(cursor.getString(cursor.getColumnIndex("name")));
        }
        cursor.close();
        mTV.setText(builder.toString());
    }

    private void delete() {
        getContentResolver().delete(bookUri, "name = ?", new String[]{"红与黑"});
    }

    private void update() {
        ContentValues values = new ContentValues();
        values.put("name", "挑战与机遇");
        getContentResolver().update(bookUri, values, "name = ?", new String[]{"战争与和平"});
    }

    private void insert() {
        ContentValues values = new ContentValues();
        values.put("name", "战争与和平");
        getContentResolver().insert(bookUri, values);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值