Android--内容提供者

一台终端设备,有可能要开发两三款应用,有时会共享数据,所以使用ContentProvider是最方便不过的了。

系统中的通讯录等等一些信息,就是基于内容提供者的机制。

下面来实战自己创造一个内容提供器:

1、首先应用已经有数据库里面有表

MyDatabaseHelper.java

package com.study.test.testapplication.database;

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

/**
 * Create by BruceXuheng on 2018/6/5
 * description :
 *      数据库创建类
 *
 **/

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private Context mContext;
    private static int dbVersion = 1;

    private String createBookSql = "create table Book ("
            +"id integer primary key autoincrement,"
            +"author text,"
            +"price text,"
            +"pages integer"
            +")";

    public MyDatabaseHelper(Context context) {
        super(context, "onceDB.db", null, dbVersion);
        mContext = context;
    }


//    创建数据库
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(createBookSql);
        Toast.makeText(mContext, "Create Success", Toast.LENGTH_SHORT).show();
    }

//    更新数据库
    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

        db.execSQL("drop table if exists Book");
        Toast.makeText(mContext, "onUpgrade Success", Toast.LENGTH_SHORT).show();

    }
}

2、创建内容构造器 MyContentProvider.java:
清单文件中写明,authorities参数尤其重要:

<provider
            android:name=".contentprovider.MyContentProvider"
            android:authorities="com.study.test.testapplication.provider"
            android:enabled="true"
            android:exported="true">
        </provider>
package com.study.test.testapplication.contentprovider;

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;
import android.util.Log;

import com.study.test.testapplication.database.MyDatabaseHelper;

public class MyContentProvider extends ContentProvider {

    public static final int BOOK_DIR = 0;
    public static final int BOOK_ITEM = 1;
    public static final String AUTHORITY = "com.study.test.testapplication.provider";
    private static UriMatcher uriMatcher;
    private MyDatabaseHelper mDatabaseHelper;

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(AUTHORITY, "Book", BOOK_DIR);
        uriMatcher.addURI(AUTHORITY, "book/#", BOOK_ITEM);

    }


    public MyContentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
            case BOOK_DIR:
                return "vnd.android.cursor.dir/vnd.com.study.test.testapplication.provider.Book";
        }
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO: Implement this to handle requests to insert a new row.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public boolean onCreate() {
        mDatabaseHelper = new MyDatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
        Log.e("chenxh","经过这里123"+uri);
        Cursor cursor = null;
        switch (uriMatcher.match(uri)) {
            case BOOK_DIR:
                Log.e("chenxh","经过这里");
                cursor = db.query("Book", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            default:
                break;
        }
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // TODO: Implement this to handle requests to update one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

3、如何获取数据呢,
通过cbtn这个控件的点击事件,处理获取数据。

package com.study.test.testapplication.acty;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.study.test.testapplication.R;
import com.study.test.testapplication.database.MyDatabaseHelper;

import java.util.ArrayList;
import java.util.List;

public class StudyContentResolverActy extends AppCompatActivity {

    ArrayAdapter<String> mAdapter;
    List<String> mContactList = new ArrayList<>();
    private ListView mlistView;
    private Button cbtn;
    private MyDatabaseHelper mdbHepler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_study_content_resolver_acty);
        mdbHepler= new MyDatabaseHelper(this);
        mlistView = findViewById(R.id.contacts_view);
        mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mContactList);
        mlistView.setAdapter(mAdapter);
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
        }else{
            getContent();
        }
        cbtn = findViewById(R.id.cr_btn);
        cbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("content://com.study.test.testapplication.provider/Book");
                SQLiteDatabase db = mdbHepler.getReadableDatabase();
                Cursor cursor = getContentResolver().query(uri,null,null,null,null);
                if(cursor != null){
                    while(cursor.moveToNext()){
                        String name = cursor.getString(cursor.getColumnIndex("author"));
                        Log.e("chenxh",name);
                    }
                    cursor.close();
                }else{
                    Toast.makeText(StudyContentResolverActy.this, "cursor is null", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void getContent(){
        Cursor cursor = null;
        cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
        if(cursor != null){
            while(cursor.moveToNext()){
                String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                mContactList.add(displayName + "\n" +number);
                mAdapter.notifyDataSetChanged();

            }

        }
        if(cursor != null){
            cursor.close();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode){
            case 1:
                if(permissions.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    getContent();
                }else{
                    Toast.makeText(StudyContentResolverActy.this, "未授权", Toast.LENGTH_SHORT).show();
                }
                break;

            default:
                break;
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值