跨程序访问数据——编写自己的内容提供器

一、提供数据的app:AddressBook

1、编写界面并实现增删改查的功能(使用数据库)(和普通程序相同)

这里我们写得简单一点,和之前的程序没什么两样,就不多说了。

①布局文件activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/address_list"
                android:layout_width="361dp"
                android:layout_height="52dp"
                android:text="联系人"
                android:textSize="30dp"
                android:gravity="center"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp">

                <TextView
                android:id="@+id/name_view"
                android:layout_width="60dp"
                android:layout_height="43dp"
                android:text="姓名:"
                android:textSize="20dp"/>

            <EditText
                android:id="@+id/text_name"
                android:layout_width="190dp"
                android:layout_height="43dp"
                tools:layout_editor_absoluteX="137dp"
                tools:layout_editor_absoluteY="77dp" />

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp">

            <TextView
                android:id="@+id/teacher_view"
                android:layout_width="60dp"
                android:layout_height="43dp"
                android:text="电话:"
                android:textSize="20dp" />
            <EditText
                android:id="@+id/text_tel"
                android:layout_width="190dp"
                android:layout_height="43dp"
                tools:layout_editor_absoluteX="137dp"
                tools:layout_editor_absoluteY="120dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp">

            <Button
                android:id="@+id/query_all"
                android:layout_width="90dp"
                android:layout_height="39dp"
                android:text="全部查询"
                app:layout_constraintStart_toStartOf="parent"
                tools:layout_editor_absoluteY="260dp" />

            <Button
                android:id="@+id/add_btn"
                android:layout_width="90dp"
                android:layout_height="39dp"
                android:text="添加数据"
                android:layout_marginLeft="50dp"
                app:layout_constraintStart_toStartOf="parent"
                tools:layout_editor_absoluteY="260dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp">

            <TextView
                android:id="@+id/id_btn"
                android:layout_width="37dp"
                android:layout_height="37dp"
                android:text="ID:"
                android:textSize="20dp"
                tools:layout_editor_absoluteX="16dp"
                tools:layout_editor_absoluteY="299dp" />

            <EditText
                android:id="@+id/input_id"
                android:layout_width="58dp"
                android:layout_height="42dp"
                tools:layout_editor_absoluteX="79dp"
                tools:layout_editor_absoluteY="304dp" />

            <Button
                android:id="@+id/id_delete"
                android:layout_width="68dp"
                android:layout_height="37dp"
                android:text="ID删除"
                android:layout_marginLeft="10dp"
                tools:layout_editor_absoluteX="152dp"
                tools:layout_editor_absoluteY="299dp" />

            <Button
                android:id="@+id/id_update"
                android:layout_width="68dp"
                android:layout_height="37dp"
                android:text="ID更新"
                android:layout_marginLeft="10dp"
                tools:layout_editor_absoluteX="292dp"
                tools:layout_editor_absoluteY="299dp" />

        </LinearLayout>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp"
            android:layout_marginVertical="35dp">

            <TextView
                android:id="@+id/queryResult"
                android:layout_width="280dp"
                android:layout_height="210dp"
                tools:layout_editor_absoluteX="16dp"
                tools:layout_editor_absoluteY="350dp" />
        </LinearLayout>

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

这个东西呢大概长这样:
在这里插入图片描述

②MyAddressBookHelper.java

主要就是建表

package com.example.yogi.addressbook;

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

public class MyAddressBookHelper extends SQLiteOpenHelper {
    private static final String db_name = "ContactPerson";//自定义的数据库名;
    private static final int version = 1;//版本号,改变则会执行onUpgrade方法?

    public MyAddressBookHelper(Context context) {
        super(context, db_name, null, version);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String  sql ="create table contactPerson(" +
                "id Integer primary key autoincrement," +
                "pName varchar(30)," +
                "tel varchar(20)" +
                ")";
        db.execSQL(sql);
    }

    //数据库版本更新时执行该方法,如果表已存在则先删除再调用onCreate重新创建
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists contactPerson");
        onCreate(db);
    }
}

③MainActivity.java

实现一下按钮功能

package com.example.yogi.addressbook;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
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 MyAddressBookHelper addressHelper;
    private SQLiteDatabase myDB;
    private EditText inputId,inputName,inputTel;
    private Button id_delete,id_update,add_btn,query_all;
    private TextView queryResult;

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

        addressHelper = new MyAddressBookHelper(this);
        myDB = addressHelper.getWritableDatabase();

        id_delete = findViewById(R.id.id_delete);
        id_delete.setOnClickListener(this);
        id_update = findViewById(R.id.id_update);
        id_update.setOnClickListener(this);
        add_btn = findViewById(R.id.add_btn);
        add_btn.setOnClickListener(this);
        query_all = findViewById(R.id.query_all);
        query_all.setOnClickListener(this);

        inputId = findViewById(R.id.input_id);
        inputId.setOnClickListener(this);
        inputName = findViewById(R.id.text_name);
        inputName.setOnClickListener(this);
        inputTel = findViewById(R.id.text_tel);
        inputTel.setOnClickListener(this);

        queryResult = findViewById(R.id.queryResult);
        queryResult.setOnClickListener(this);
    }

    public void onClick(View view){
        switch (view.getId()){
            case R.id.query_all:
            {
                queryAllData();
                break;
            }
            case R.id.add_btn:
            {
                addData();
                break;
            }
            case R.id.id_delete:
            {
                deleteId();
                break;
            }
            case R.id.id_update:
            {
                updateId();
                break;
            }
        }
    }

    private void addData() {
        ContentValues values = new ContentValues();
        //第一个参数应该是表中的列名吧
        values.put("pName",inputName.getText().toString());
        values.put("tel",inputTel.getText().toString());
        myDB.insert("contactPerson",null,values);
    }

    //查询所有
    private void queryAllData(){
        Cursor cursor = myDB.query("contactPerson",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            queryResult.setText("");
            do{
                String personId = String.valueOf(cursor.getInt(cursor.getColumnIndex("id")));
                String personName = cursor.getString(cursor.getColumnIndex("pName"));
                String personTel = cursor.getString(cursor.getColumnIndex("tel"));
                //保存 不然循环一次set一次,前面的就会被覆盖
                String q = queryResult.getText().toString();
                queryResult.setText(q+"\n"+"ID:"+personId+",姓名:"+personName+",联系电话:"+personTel+"\n");
            }while (cursor.moveToNext());
        }
        cursor.close();
    }

    private void updateId() {
        ContentValues values = new ContentValues();
        String upd_id = inputId.getText().toString();
        //更新使用了values.put的列,如果有列没有被values.put,则会保持原样不更新
        values.put("pName",inputName.getText().toString());
        values.put("tel",inputTel.getText().toString());

        myDB.update("contactPerson",values,"id=?",new String[]{upd_id});
    }

    private void deleteId() {
        String del_id = inputId.getText().toString();
        myDB.delete("contactPerson","id=?",new String[]{del_id});
    }

}

2、编写自己的内容提供器,MyProvider.java

① 整体代码
package com.example.yogi.addressbook;

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 MyProvider extends ContentProvider {
    public static final int CONTACT_DIR = 0;
    public static final int CONTACT_ITEM = 1;

    private static UriMatcher uriMatcher;
    private MyAddressBookHelper addrHelper;

    //在静态代码块里创建UriMatcher的实例,并调用addURI()方法,将期望匹配的内容URI格式传递进去
    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        //第一个参数为authority 第二个参数为path 第三个参数为一个自定义代码
        //注意这里的authority看起来是包名,其实应该是以AndroidManifect.xml文件中的android:authorities属性值为准的
        //path为表名时代表整表查询/删除等,为表名/#时代表该表中的某条记录
        uriMatcher.addURI("com.example.yogi.addressbook", "contactPerson", CONTACT_DIR);
        uriMatcher.addURI("com.example.yogi.addressbook", "contactPerson/#", CONTACT_ITEM);
    }

    //实例化MyAddressBookHelper对象并返回true
    @Override
    public boolean onCreate() {
        addrHelper = new MyAddressBookHelper(getContext());//这里是实例化MyAddressBookHelper对象,所以怎么写要看这个类的构造函数
        return true;
    }

    //其实就是再写一遍增删改查,只是通过switch-case使得传进来的uri不同则做不一样的操作(比如查整个表或查某一句)
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder){
        SQLiteDatabase db = addrHelper.getReadableDatabase();
        Cursor cursor = null;
        //通过.match方法对uri进行匹配
        switch (uriMatcher.match(uri)){
            case CONTACT_DIR:
                cursor = db.query("contactPerson", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case CONTACT_ITEM:
                String pId = uri.getPathSegments().get(1);
                //Uri对象的getPathSegments()方法,它会将内容URI权限之后的部分以“/”符号进行分割,并把分割后的结果放人到一个字符串列表中;
                // 那这个列表的第0个位置存放的就是路径,第1个位置存放的就是id了
                cursor = db.query("contactPerson", projection, "id=?", new  String[]{ pId }, null, null, sortOrder);
                break;
            default:
                break;
        }
        return cursor;
    }

    //insert()方法要求返回一个能够表示这条新增数据的URI,
    // 所以我们还需要调用Uri.parse()方法来将一个内容URI解析成Uri对象,当然这个内容URI是以新增数据的id结尾的。
    @Override
    public Uri insert(Uri uri, ContentValues values) {

        SQLiteDatabase db = addrHelper.getWritableDatabase();
        Uri uriReturn = null;
        switch (uriMatcher.match(uri)){
            case CONTACT_DIR: case CONTACT_ITEM:
                long newContact = db.insert("contactPerson", null, values);
                uriReturn = Uri.parse("content://com.example.yogi.addressbook/contactPerson/" + newContact);
                break;
            default:
                break;
        }
        return uriReturn;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        SQLiteDatabase db = addrHelper.getWritableDatabase();
        int updateRows = 0;
        switch (uriMatcher.match(uri)){
            case CONTACT_DIR:
                updateRows = db.update("contactPerson", values, selection, selectionArgs);
                break;
            case CONTACT_ITEM:
                String personId = uri.getPathSegments().get(1);
                updateRows = db.update("contactPerson", values, "id = ?", new String[]{ personId });
                break;
            default:
                break;
        }
        return updateRows;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = addrHelper.getWritableDatabase();
        int deleteRows = 0;
        switch (uriMatcher.match(uri)){
            case CONTACT_DIR:
                deleteRows = db.delete("contactPerson", selection, selectionArgs);
                break;
            case CONTACT_ITEM:
                String personId = uri.getPathSegments().get(1);
                deleteRows = db.delete("contactPerson","id = ?", new String[]{ personId });
                break;
            default:
                break;
        }
        return deleteRows;
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)){
            case CONTACT_DIR:
                return "vnd.android.cursor.dir/vnd.com.example.yogi.addressbook.contactPerson";
            case CONTACT_ITEM:
                return "vnd.android.cursor.item/vnd.com.example.yogi.addressbook.contactPerson";
            default:
                break;
        }
        return null;
    }


}

②关于静态代码块static中的内容说明

内容URI的格式主要有两种,以路径结尾就表示期望访问该表中所有的数据,以id 结尾就表示期望访问该表中拥有相应id的数据。
例:
content://com.example.app.provider/table1
这就表示调用方期望访问的是com.example.app这个应用的tablel表中的数据。
content://com.example.app.provider/table1/1
这就表示调用方期望访问的是com.example.app这个应用的tablel表中id为1的数据。

我们可以使用通配符的方式来分别匹配这两种格式的内容URI,规则如下。
*:表示匹配任意长度的任意字符。
#:表示匹配任意长度的数字。

所以,一个能够匹配任意表的内容URI格式就可以写成:
content://com.example.app.provider/*
而一个能够匹配tablel表中任意一行数据的内容URI格式就可以写成:
content://com.example.app.provider/table1/#

UriMatcher中提供了一个addURI()方法,这个方法接收3个参数,可以分别把authority、path和一个自定义代码传进去。这样,当调用UriMatcher的match()方法时,就可以将一个Uri对象传入,返回值是某个能够匹配这个Uri对象所对应的自定义代码,利用这个代码,我们就可以判断出调用方期望访问的是哪张表中的数据了
注意这里的authority看起来是包名,其实应该是以AndroidManifect.xml文件中的android:authorities属性值为准的。

下面的第二行就代表匹配com.example.yogi.addressbook项目下的contentPerson表
第三行代表匹配com.example.yogi.addressbook项目下的contentPerson表中的某一行

 uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
 uriMatcher.addURI("com.example.yogi.addressbook", "contactPerson", CONTACT_DIR);//authority是包名,path前面是表名?
 uriMatcher.addURI("com.example.yogi.addressbook", "contactPerson/#", CONTACT_ITEM);

增删改查中再通过下面这种方式来区分(以查询为例)是查全部还是查某一行

switch (uriMatcher.match(uri)){
    case CONTACT_DIR:
    ……
    case CONTACT_ITEM:
    ……
}
③关于getType()方法的一点说明

getType()方法是所有的内容提供器都必须提供的一个方法,用于获取Uri对象所对应的MIME类型。
一个内容URI所对应的MIME字符串主要由3部分组成:
a.必须以vnd开头。b.如果内容URI以路径结尾,则vnd后接android.cursor.dir/,如果内容URI以id结尾,则后接android.cursor.item/。c.最后接上vnd.<authority>.<path>

例:
对于content:/com.example.yogi.addressbook/table1这个内容URI,它所对应的MIME类型就可以写成:
vnd.android.cursor.dir/vnd.com.example.yogi.addressbook.table1
对于content://com.example.yogi.addressbook/table1/1这个内容URI,它所对应的MIME类型就可以写成:
vnd.android.cursor.item/vnd.com.example.yogi.addressbook.table1

3.在AndroidManifect.xml文件中注册自己的内容提供器

如果是右键包名-new-other-Content Provider这样创建的
注意勾选Enabled属性(是否启用该内容提供器)和Exported属性(是否允许外部程序访问该内容提供器)
则会自动在AndroidManifect.xml中进行注册,不需要手动写

android:name属性指定了DatabaseProvider的类名
android:authorities属性指定了DatabaseProvider的authority

如果是直接右键new了一个类的话,需要在AndroidManifect.xml中:

<application>
	……
	<provider
	    android:authorities="com.example.yogi.addressbook"
	    android:name=".MyProvider"
	    android:enabled="true"
	    android:exported="true"/>
</application>

二、第二个app,访问上一个app中的数据

1.布局文件,和之前的app一模一样即可(只是为了测试)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/address_list"
                android:layout_width="361dp"
                android:layout_height="52dp"
                android:text="MyProviderTest"
                android:textSize="30dp"
                android:gravity="center"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp">

            <TextView
                android:id="@+id/name_view"
                android:layout_width="60dp"
                android:layout_height="43dp"
                android:text="姓名:"
                android:textSize="20dp"/>

            <EditText
                android:id="@+id/text_name"
                android:layout_width="190dp"
                android:layout_height="43dp"
                tools:layout_editor_absoluteX="137dp"
                tools:layout_editor_absoluteY="77dp" />

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp">

            <TextView
                android:id="@+id/teacher_view"
                android:layout_width="60dp"
                android:layout_height="43dp"
                android:text="电话:"
                android:textSize="20dp" />
            <EditText
                android:id="@+id/text_tel"
                android:layout_width="190dp"
                android:layout_height="43dp"
                tools:layout_editor_absoluteX="137dp"
                tools:layout_editor_absoluteY="120dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp">

            <Button
                android:id="@+id/query_all"
                android:layout_width="90dp"
                android:layout_height="39dp"
                android:text="全部查询"
                app:layout_constraintStart_toStartOf="parent"
                tools:layout_editor_absoluteY="260dp" />

            <Button
                android:id="@+id/add_btn"
                android:layout_width="90dp"
                android:layout_height="39dp"
                android:text="添加数据"
                android:layout_marginLeft="50dp"
                app:layout_constraintStart_toStartOf="parent"
                tools:layout_editor_absoluteY="260dp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp">

            <TextView
                android:id="@+id/id_btn"
                android:layout_width="37dp"
                android:layout_height="37dp"
                android:text="ID:"
                android:textSize="20dp"
                tools:layout_editor_absoluteX="16dp"
                tools:layout_editor_absoluteY="299dp" />

            <EditText
                android:id="@+id/input_id"
                android:layout_width="58dp"
                android:layout_height="42dp"
                tools:layout_editor_absoluteX="79dp"
                tools:layout_editor_absoluteY="304dp" />

            <Button
                android:id="@+id/id_delete"
                android:layout_width="68dp"
                android:layout_height="37dp"
                android:text="ID删除"
                android:layout_marginLeft="10dp"
                tools:layout_editor_absoluteX="152dp"
                tools:layout_editor_absoluteY="299dp" />

            <Button
                android:id="@+id/id_update"
                android:layout_width="68dp"
                android:layout_height="37dp"
                android:text="ID更新"
                android:layout_marginLeft="10dp"
                tools:layout_editor_absoluteX="292dp"
                tools:layout_editor_absoluteY="299dp" />

        </LinearLayout>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginLeft="50dp"
            android:layout_marginVertical="35dp">

            <TextView
                android:id="@+id/queryResult"
                android:layout_width="280dp"
                android:layout_height="210dp"
                tools:layout_editor_absoluteX="16dp"
                tools:layout_editor_absoluteY="350dp" />
        </LinearLayout>

    </LinearLayout>
</android.support.constraint.ConstraintLayout>

2.MainActivity.java,注意对比和之前app的MainActivity的区别

区别主要在不再在这里引入变量xxxHelper和SQLiteDatabase的实例,而是通过getContentResolver()来进行增删改查的操作。
且通过参数uri去区别是整表查询还是某条语句查询。

以添加数据为例:
首先调用了Uri.parse()方法将一个内容URI解析成Uri对象,然后把要添加的数据都存放到ContentValues对象中,接着调用ContentResolver的insert()方法执行添加操作就可以了。
注意insert()方法会返回一个Uri对象,这个对象中包含了新增数据的id,我们可以通过getPathSegments()方法将这个id取出(如果有需要的话,这个简单的测试程序暂时不需要)

package com.example.yogi.myprovidertest;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
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 String newId;
    private EditText inputId,inputName,inputTel;
    private Button id_delete,id_update,add_btn,query_all;
    private TextView queryResult;

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

        id_delete = findViewById(R.id.id_delete);
        id_delete.setOnClickListener(this);
        id_update = findViewById(R.id.id_update);
        id_update.setOnClickListener(this);
        add_btn = findViewById(R.id.add_btn);
        add_btn.setOnClickListener(this);
        query_all = findViewById(R.id.query_all);
        query_all.setOnClickListener(this);

        inputId = findViewById(R.id.input_id);
        inputId.setOnClickListener(this);
        inputName = findViewById(R.id.text_name);
        inputName.setOnClickListener(this);
        inputTel = findViewById(R.id.text_tel);
        inputTel.setOnClickListener(this);

        queryResult = findViewById(R.id.queryResult);
        queryResult.setOnClickListener(this);
    }

    public void onClick(View view){
        switch (view.getId()){
            case R.id.query_all:
            {
                queryAllData();
                break;
            }
            case R.id.add_btn:
            {
                addData();
                break;
            }
            case R.id.id_delete:
            {
                deleteId();
                break;
            }
            case R.id.id_update:
            {
                updateId();
                break;
            }
        }
    }

    private void addData() {
        Uri uri = Uri.parse("content://com.example.yogi.addressbook/contactPerson");//这里的uri是提供数据的uri,而不是自己的
        ContentValues values = new ContentValues();
        //第一个参数应该是表中的列名吧
        values.put("pName",inputName.getText().toString());
        values.put("tel",inputTel.getText().toString());

        //myDB.insert("contactPerson",null,values);
        //不再使用SQLiteDataBase,而是使用getContentResolver()
        Uri newUri = getContentResolver().insert(uri, values);
        //注意insert()方法会返回一个Uri对象,这个对象中包含了新增数据的id,我们可以通过getPathSegments()方法将这个id取出
        //newId = newUri.getPathSegments().get(1);
    }

    //查询所有
    private void queryAllData(){
        Uri uri = Uri.parse("content://com.example.yogi.addressbook/contactPerson");
        //Cursor cursor = myDB.query("contactPerson",null,null,null,null,null,null);
        Cursor cursor = getContentResolver().query(uri,null,null,null,null);
        if(cursor.moveToFirst()){
            queryResult.setText("");
            do{
                String personId = String.valueOf(cursor.getInt(cursor.getColumnIndex("id")));
                String personName = cursor.getString(cursor.getColumnIndex("pName"));
                String personTel = cursor.getString(cursor.getColumnIndex("tel"));
                //保存 不然循环一次set一次,前面的就会被覆盖
                String q = queryResult.getText().toString();
                queryResult.setText(q+"\n"+"ID:"+personId+",姓名:"+personName+",联系电话:"+personTel+"\n");
            }while (cursor.moveToNext());
        }
        cursor.close();
    }

    private void updateId() {
        ContentValues values = new ContentValues();
        String upd_id = inputId.getText().toString();
        Uri uri = Uri.parse("content://com.example.yogi.addressbook/contactPerson/"+upd_id);
        //更新使用了values.put的列,如果有列没有被values.put,则会保持原样不更新
        values.put("pName",inputName.getText().toString());
        values.put("tel",inputTel.getText().toString());

        //myDB.update("contactPerson",values,"id=?",new String[]{upd_id});
        getContentResolver().update(uri,values,null,null);
    }

    private void deleteId() {
        String del_id = inputId.getText().toString();
        Uri uri = Uri.parse("content://com.example.yogi.addressbook/contactPerson/"+del_id);
        //myDB.delete("contactPerson","id=?",new String[]{del_id});
        getContentResolver().delete(uri,null,null);
    }

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值