欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【Android基础】ContentProvider简例

程序员文章站 2022-04-19 10:33:25
布局文件

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="id,just for delete or update"/>

    <EditText
        android:id="@+id/url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="url,for add or update"/>

    <Button
        android:id="@+id/add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add"/>

    <Button
        android:id="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete"/>

    <Button
        android:id="@+id/query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Query"/>

    <Button
        android:id="@+id/update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="update"/>

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

清单文件

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

    <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">
        <provider
            android:name=".UrlContentProvider"
            android:authorities="com.example.mycontentprovider"
            android:enabled="true"
            android:exported="true"></provider>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

DatabaseHelper 类

package com.example.contentprovidertest;

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

import androidx.annotation.Nullable;

public class UrlDatabaseHelper extends SQLiteOpenHelper {
    //数据库文件名
    static final String DATABASE_NAME = "url.db";
    //数据库表名
    static final String TABLE_NAME = "url";
    //数据库版本号
    private static final int DATABASE_VERSION = 1;

    public UrlDatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    //创建表
    //表中含有_id和url
    private void createTable(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT," + "url TEXT)");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        createTable(db);
    }

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

    }
}

ContentProvider 类

package com.example.contentprovidertest;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class UrlContentProvider extends ContentProvider {

    //与AndroidManifest.xml文件中authorities相同
    protected static final String AUTHORITY = "com.example.mycontentprovider";
    //创建UriMatcher对象
    private static UriMatcher uriMatcher;
    //匹配成功后的匹配码
    private static final int MATCH_CODE = 100;

    //Content uri of this provider
    //组成:"content://" + AUTHORITY + “/” + addURI中第二个参数
    public static final Uri uri = Uri.parse("content://com.example.mycontentprovider/");

    private UrlDatabaseHelper mOpenHelper;

    //创建静态代码块
    static {
        //实例化UriMatcher对象
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        //可以实现匹配URI的功能
        //参数1:authority 参数2:路径 参数3:URI与给定组件匹配成功后的匹配码
        uriMatcher.addURI(AUTHORITY, null, MATCH_CODE);
    }

    @Override
    public boolean onCreate() {
        // Implement this to initialize your content provider on startup.
        //创建DatabaseHelper对象
        mOpenHelper = new UrlDatabaseHelper(getContext());
        return true;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        //得到SQLiteDatabase对象
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int rows = -1;
        switch (uriMatcher.match(uri)){
            case MATCH_CODE:
                rows = db.delete(UrlDatabaseHelper.TABLE_NAME,selection,selectionArgs);
                break;
        }
        return rows;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        //得到SQLiteDatabase对象
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        switch (uriMatcher.match(uri)){
            case MATCH_CODE:
                db.insert(UrlDatabaseHelper.TABLE_NAME,null,values);
                break;
        }
        return uri;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        //得到SQLiteDatabase对象
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        Cursor cursor = null;
        switch (uriMatcher.match(uri)){
            case MATCH_CODE:
                cursor = db.query(UrlDatabaseHelper.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
                break;
        }
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        //得到SQLiteDatabase对象
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int rows = -1;
        switch (uriMatcher.match(uri)){
            case MATCH_CODE:
                rows = db.update(UrlDatabaseHelper.TABLE_NAME,values,selection,selectionArgs);
                break;
        }
        return rows;
    }

    @Override
    public String getType(Uri uri) {
        // Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

增删查改操作

package com.example.contentprovidertest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText mIDEditText;
    private EditText mUrlEditText;
    private Button mButtonAdd;
    private Button mButtonDelete;
    private Button mButtonQuery;
    private Button mButtonupdate;
    private TextView mResult;

    private ContentResolver mContentResolver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        init();

        mContentResolver = getContentResolver();

        mButtonAdd.setOnClickListener(this);
        mButtonDelete.setOnClickListener(this);
        mButtonQuery.setOnClickListener(this);
        mButtonupdate.setOnClickListener(this);
    }

    private void init() {
        mIDEditText = findViewById(R.id.id);
        mUrlEditText = findViewById(R.id.url);
        mButtonAdd = findViewById(R.id.add);
        mButtonDelete = findViewById(R.id.delete);
        mButtonQuery = findViewById(R.id.query);
        mButtonupdate = findViewById(R.id.update);
        mResult = findViewById(R.id.result);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.add:
                String url = mUrlEditText.getText().toString();
                ContentValues contentValues = new ContentValues();
                contentValues.put("url",url);
                mContentResolver.insert(UrlContentProvider.uri,contentValues);
                break;
            case R.id.delete:
                String id = mIDEditText.getText().toString();
                String whereClause = "_id" + "=?";
                String[] whereArgs = new String[]{id};
                mContentResolver.delete(UrlContentProvider.uri,whereClause,whereArgs);
                break;
            case R.id.update:
                String urlUpdate = mUrlEditText.getText().toString();
                ContentValues CV = new ContentValues();
                CV.put("url",urlUpdate);
                String idUpdate = mIDEditText.getText().toString();
                String whereClauseUpdate = "_id" + "=?";
                String[] whereArgsUpdate = new String[]{idUpdate};
                mContentResolver.update(UrlContentProvider.uri,CV,whereClauseUpdate,whereArgsUpdate);
                break;
            case R.id.query:
                StringBuffer stringBuffer = new StringBuffer();
                Cursor cursor = mContentResolver.query(UrlContentProvider.uri,null,null,null,null);
                cursor.moveToFirst();
                do {
                    String urlQuery = cursor.getString(cursor.getColumnIndex("url"));
                    stringBuffer.append(urlQuery);
                    stringBuffer.append("///");
                } while(cursor.moveToNext());
                mResult.setText(stringBuffer);
                break;
        }
    }
}

本文地址:https://blog.csdn.net/m0_46211029/article/details/107176771