Android Content Provider + SQLite experiment

Posted by senthilnayagam on Sat, 25 Dec 2021 16:40:04 +0100

Experiment 12 SQL + content Provider experiment

1, Experimental purpose

Be familiar with the use of Content Provider;

2, Experimental content

1. Implement the calling of ContentProvider and ContentResolver through URI;
2. Realize the functions of ContentProvider on database SQLite: add, delete, modify and query;
3. The table structure of the database is designed by ourselves;

3, Experimental requirements

1. Configure the running environment of SQLite database
2. Be familiar with the specific operations and processes of content provider for adding, deleting, modifying and querying SQLite database
3. Fully understand the use principle and mode of SQLite database

reference resources:
https://blog.csdn.net/alovelypeach/article/details/112250226
The original blogger (alovelypach) did not mention the application manifest file AndroidManifest.xml, which led to the copy code not running normally. This paper will improve the experimental content of the original blogger


4, Experimental process

① Create project

② Writing layout files

③ Write MainActivity class

The experiment needs to read the address book. If the permission to read the address book is not given, the application will not run normally
Need to use

ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED

Determine whether you have permission to read the address book
If you do not have permission, use

ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);

The Android request permission dialog box pops up.
Start ContentActivity with permission and proceed to the next step
The code is as follows:

public void toOne(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
            Toast.makeText(this,"Permission to read address book is not allowed!",Toast.LENGTH_SHORT).show();
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
        {
            Intent intent = new Intent(MainActivity.this,ContentActivity.class);
            startActivity(intent);
        }
    }

The effects are as follows:

④ Write ContentActivity class

To get the NUMBER in the address book, you need to get lookup first_ Key, and then according to LOOKUP_KEY to contactscontract CommonDataKinds. Query NUMBER in phone

Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},ContactsContract.Data.LOOKUP_KEY+"=?", new String[]{lookUp_Key},null);

Get the address book name and number code as follows:

public String getAllPhoneNumbers(String lookUp_Key){
        StringBuilder allPhoneNo = new StringBuilder();
        String[] proj2 = {ContactsContract.CommonDataKinds.Phone.NUMBER};
        String selection = ContactsContract.Data.LOOKUP_KEY+"=?";
        String[] selectionArgs = {lookUp_Key};
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,proj2,selection,selectionArgs,null);
        while(cursor.moveToNext()){
            allPhoneNo.append(cursor.getString(0)).append(" ");
        }
        return allPhoneNo.toString();
    }

    private CharSequence getQueryData() {

        StringBuilder stringBuilder = new StringBuilder();
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,null,null,null);

        String name = ContactsContract.Contacts.DISPLAY_NAME;
        String key = ContactsContract.Contacts.LOOKUP_KEY;
        int displayNameIndex = cursor.getColumnIndex(name);
        int KeyIndex = cursor.getColumnIndex(key);
        for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
            String displayName = cursor.getString(displayNameIndex);
            String Key = cursor.getString(KeyIndex);
            String displayPhone = getAllPhoneNumbers(Key);
            stringBuilder.append(displayName).append(" ").append(displayPhone).append("\n");
        }
        cursor.close();
        return stringBuilder.toString();
    }


⑤ Write SQLActivity, PersionProvider, PersonDBOpenHelper classes

The code for inserting the address book into the database is as follows:

public void btnCreate(View view) {

        PersonDBOpenHelper helper = new PersonDBOpenHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        resolver = getContentResolver();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
            Toast.makeText(this,"Permission to read address book is not allowed!",Toast.LENGTH_SHORT).show();
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
        {
            Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,null,null,null);
            String name = ContactsContract.Contacts.DISPLAY_NAME;
            String key = ContactsContract.Contacts.LOOKUP_KEY;
            int displayNameIndex = cursor.getColumnIndex(name);
            int KeyIndex = cursor.getColumnIndex(key);
            for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
                String displayName = cursor.getString(displayNameIndex);
                String Key = cursor.getString(KeyIndex);
                String displayPhone = getAllPhoneNumbers(Key);
                values = new ContentValues();
                values.put("name",displayName);
                values.put("phone",displayPhone);
                db.insert("info",null,values);
            }
            cursor.close();
            db.close();
            btnQueryAll(view);
            Toast.makeText(this,"Insert succeeded!",Toast.LENGTH_SHORT).show();

        }
    }

use

db.execSQL("create table info(_id integer primary key autoincrement,name varchar(50),phone varchar(20),UNIQUE(phone))");

Create with_ SQLite database of id, name and phone fields, where_ id is the primary key, self incremented, and phone cannot be duplicated.

⑥ Modify the application manifest file androidmanifest xml

Need to join

<uses-permission android:name="android.permission.READ_CONTACTS" />

Claim that you need permission to read the address book
Need to join

<provider
    android:authorities="com.example.test05_contentprovider.PersonProvider"
    android:name="PersonProvider"
    android:exported="false" />

To include content providers
Android: the writing method of authorities is the package name of Provider + the class name of Provider

5, Complete source code

activity_main.xml

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

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

</LinearLayout>

contentlayout.xml

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ContentActivity">

    <TextView
        android:id="@+id/hint"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hint"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/callName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

</LinearLayout>

sqllayout.xml

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SQLActivity">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:hint="@string/id" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:hint="@string/name" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:hint="@string/phone" />

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

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

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

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

    <Button
        android:id="@+id/addContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/addContent"
        android:onClick="btnCreate" />

    <Button
        android:id="@+id/queryAll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/queryAll"
        android:onClick="btnQueryAll" />

    <EditText
        android:id="@+id/eT"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="15dp"
        android:layout_weight="1"
        android:gravity="start|top"
        android:inputType="textMultiLine" />

</LinearLayout>

strings.xml

<resources>
    <string name="app_name">test05_contentprovider</string>
    <string name="id">id</string>
    <string name="name">full name</string>
    <string name="phone">number</string>
    <string name="add">increase</string>
    <string name="delete">delete</string>
    <string name="update">modify</string>
    <string name="query">query</string>
    <string name="addContent">Insert address book data</string>
    <string name="queryAll">View all data</string>
    <string name="toOne">Access address book</string>
    <string name="toTwo">database</string>
    <string name="hint">Read contact name and number:</string>
</resources>

MainActivity.java

package com.example.test05_contentprovider;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    public void toOne(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
            Toast.makeText(this,"Permission to read address book is not allowed!",Toast.LENGTH_SHORT).show();
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
        {
            Intent intent = new Intent(MainActivity.this,ContentActivity.class);
            startActivity(intent);
        }
    }

    public void toTwo(View view) {
        Intent intent = new Intent(MainActivity.this,SQLActivity.class);
        startActivity(intent);
    }
}

ContentActivity.java

package com.example.test05_contentprovider;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class ContentActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contentlayout);
        TextView textView = (TextView) findViewById(R.id.callName);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
            textView.setText("Permission to read address book is not allowed!");
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
        {
            textView.setText(getQueryData());
        }
    }

    public String getAllPhoneNumbers(String lookUp_Key){
        StringBuilder allPhoneNo = new StringBuilder();
        String[] proj2 = {ContactsContract.CommonDataKinds.Phone.NUMBER};
        String selection = ContactsContract.Data.LOOKUP_KEY+"=?";
        String[] selectionArgs = {lookUp_Key};
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,proj2,selection,selectionArgs,null);
        while(cursor.moveToNext()){
            allPhoneNo.append(cursor.getString(0)).append(" ");
        }
        return allPhoneNo.toString();
    }

    private CharSequence getQueryData() {

        StringBuilder stringBuilder = new StringBuilder();
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,null,null,null);

        String name = ContactsContract.Contacts.DISPLAY_NAME;
        String key = ContactsContract.Contacts.LOOKUP_KEY;
        int displayNameIndex = cursor.getColumnIndex(name);
        int KeyIndex = cursor.getColumnIndex(key);
        for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
            String displayName = cursor.getString(displayNameIndex);
            String Key = cursor.getString(KeyIndex);
            String displayPhone = getAllPhoneNumbers(Key);
            stringBuilder.append(displayName).append(" ").append(displayPhone).append("\n");
        }
        cursor.close();
        return stringBuilder.toString();
    }


}

SQLActivity.java

package com.example.test05_contentprovider;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
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.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SQLActivity extends Activity {
    private final Uri uri = Uri.parse("content://com.example.test05_contentprovider.PersonProvider/info");
    private ContentValues values;
    private ContentResolver resolver;
    private EditText et_id;
    private EditText et_name;
    private EditText et_phone;
    private EditText et_queryAll;

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

        et_id = (EditText) findViewById(R.id.editText1);
        et_name = (EditText) findViewById(R.id.editText2);
        et_phone = (EditText) findViewById(R.id.editText3);
        et_queryAll = (EditText) findViewById(R.id.eT);
    }

    public String getAllPhoneNumbers(String lookUp_Key){
        StringBuilder allPhoneNo = new StringBuilder();
        String[] proj2 = {ContactsContract.CommonDataKinds.Phone.NUMBER};
        String selection = ContactsContract.Data.LOOKUP_KEY+"=?";
        String[] selectionArgs = {lookUp_Key};
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,proj2,selection,selectionArgs,null);
        while(cursor.moveToNext()){
            allPhoneNo.append(cursor.getString(0)).append(" ");
        }
        return allPhoneNo.toString();
    }

    public void btnCreate(View view) {

        PersonDBOpenHelper helper = new PersonDBOpenHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        resolver = getContentResolver();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
            Toast.makeText(this,"Permission to read address book is not allowed!",Toast.LENGTH_SHORT).show();
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
        {
            Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,null,null,null);
            String name = ContactsContract.Contacts.DISPLAY_NAME;
            String key = ContactsContract.Contacts.LOOKUP_KEY;
            int displayNameIndex = cursor.getColumnIndex(name);
            int KeyIndex = cursor.getColumnIndex(key);
            for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
                String displayName = cursor.getString(displayNameIndex);
                String Key = cursor.getString(KeyIndex);
                String displayPhone = getAllPhoneNumbers(Key);
                values = new ContentValues();
                values.put("name",displayName);
                values.put("phone",displayPhone);
                db.insert("info",null,values);
            }
            cursor.close();
            db.close();
            btnQueryAll(view);
            Toast.makeText(this,"Insert succeeded!",Toast.LENGTH_SHORT).show();

        }
    }

    public void btnAdd(View view) {
        resolver = getContentResolver();
        values = new ContentValues();
        if (et_name.length() != 0 && et_phone.length() != 0){
            values.put("name",et_name.getText().toString());
            values.put("phone",et_phone.getText().toString());
            Uri newUri = resolver.insert(uri,values);
            Toast.makeText(this,"Increase success",Toast.LENGTH_SHORT).show();
            btnQueryAll(view);
        } else {
            et_name.setHint("Please enter the name to be added here");
            et_phone.setHint("Please enter the number to be added here");
        }
    }

    public void btnQuery(View view) {
        resolver = getContentResolver();
        if (et_name.length() != 0){
            Cursor cursor = resolver.query(uri,new String[]{"_id","name","phone"},"name=?",new String[]{et_name.getText().toString()},null);
            if (cursor.getCount() != 0){
                cursor.moveToFirst();
                et_id.setText(cursor.getString(0));
                et_name.setText(cursor.getString(1));
                et_phone.setText(cursor.getString(2));
                cursor.close();
            }
            else {
                Toast.makeText(this,"No results found!",Toast.LENGTH_SHORT).show();
            }
        }
        else {
            et_name.setHint("Please enter the name to query here");
            et_phone.setHint("number");
        }
    }

    public void btnQueryAll(View view) {
        resolver = getContentResolver();

        List<Map<String,String>> data = new ArrayList<Map<String,String>>();
        Cursor cursor = resolver.query(uri,new String[]{"_id","name","phone"},null,null,null);
        while (cursor.moveToNext()){
            Map<String,String> map = new HashMap<String,String>();
            map.put("_id",cursor.getString(0));
            map.put("name",cursor.getString(1));
            map.put("phone",cursor.getString(2));
            data.add(map);
        }
        cursor.close();
        et_queryAll.setText(new String(data.toString()));
    }

    public void btnUpdate(View view) {
        resolver = getContentResolver();
        values = new ContentValues();
        if (et_name.length() != 0 && et_phone.length() != 0){
            values.put("phone",et_phone.getText().toString());
            int updateCount = resolver.update(uri,values,"name=?",new String[]{et_name.getText().toString()});
            Toast.makeText(this,"Successfully updated" + updateCount + "Records",Toast.LENGTH_SHORT).show();
            btnQueryAll(view);
        } else {
                et_name.setHint("Please enter the name to be modified here");
                et_phone.setHint("Please enter the modified number here");
        }
    }

    public void btnDelete(View view) {
        resolver = getContentResolver();
        if (et_name.length() != 0){
            int deleteCount = resolver.delete(uri,"name=?",new String[]{et_name.getText().toString()});
            Toast.makeText(this,"Successfully deleted" + deleteCount + "Records",Toast.LENGTH_SHORT).show();
            btnQueryAll(view);
        } else {
            et_name.setHint("Please enter the name to be deleted here");
            et_phone.setHint("number");
        }
    }
}

PersionProvider.java

package com.example.test05_contentprovider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
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;

public class PersonProvider extends ContentProvider {

    private static UriMatcher mUriMatcher = new UriMatcher(-1);

    private static final int SUCCESS = 1;

    private PersonDBOpenHelper helper;

    static {
        mUriMatcher.addURI("com.example.test05_contentprovider.PersonProvider","info",SUCCESS);
    }

    @Override
    public boolean onCreate() {
        helper = new PersonDBOpenHelper(getContext());
        return false;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        int code = mUriMatcher.match(uri);
        if (code == SUCCESS) {
            SQLiteDatabase db = helper.getReadableDatabase();
            long rowId = db.insert("info",null,values);
            if (rowId>0) {
                Uri insertedUri = ContentUris.withAppendedId(uri,rowId);

                getContext().getContentResolver().notifyChange(insertedUri,null);
                return insertedUri;
            }
            db.close();
            return uri;
        }else {
            try {
                throw new IllegalAccessException("Failed to insert. The path is incorrect!");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
        int code = mUriMatcher.match(uri);
        if (code == SUCCESS) {
            SQLiteDatabase db = helper.getReadableDatabase();
            return db.query("info",strings,s,strings1,null,null,s1);
        }else {
            try {
                throw new IllegalAccessException("Query failed, the path is incorrect!");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

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

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {

        int code = mUriMatcher.match(uri);
        if (code == SUCCESS) {
            SQLiteDatabase db = helper.getReadableDatabase();
            int count = db.update("info",contentValues,s,strings);
            if (count>0) {
                getContext().getContentResolver().notifyChange(uri,null);
            }
            db.close();
            return count;
        }else {
            try {
                throw new IllegalAccessException("Update failed, the path is incorrect!");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
        int code = mUriMatcher.match(uri);
        if (code == SUCCESS) {
            SQLiteDatabase db = helper.getReadableDatabase();
            int count = db.delete("info",s,strings);
            if (count>0) {
                getContext().getContentResolver().notifyChange(uri,null);
            }
            db.close();
            return count;
        }else {
            try {
                throw new IllegalAccessException("Failed to delete. The path is incorrect!");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return code;
    }
}

PersonDBOpenHelper.java

package com.example.test05_contentprovider;

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

public class PersonDBOpenHelper extends SQLiteOpenHelper {

    public PersonDBOpenHelper(Context context) {
        super(context,"person.db",null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table info(_id integer primary key autoincrement,name varchar(50),phone varchar(20),UNIQUE(phone))");
    }

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

    }
}

AndroidManifest.xml

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

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <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/Theme.Test05_contentprovider">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <provider
            android:authorities="com.example.test05_contentprovider.PersonProvider"
            android:name="PersonProvider"
            android:exported="false" />
    </application>

</manifest>

6, Final effect

You need content in the phone or the phone book in the simulator

Open the application and click "access address book" to ask for permission to read the address book

After permission, click again to successfully read the name and phone number of the address book.

Click "database" and "insert address book data" to insert the address book data into the database and display all data at the same time.

Enter data in the name and number box, click "add" (id will increase automatically without input), and the added record will be displayed after adding successfully

Enter the name you want to delete in the name box, click "delete", and the deleted result will be displayed


Enter the name to be modified in the name box, enter the modified number in the number box, click "modify", and the modified result will be displayed

Enter the name in the name box and click "query" to display the id and number

If no content is entered in the name or number input box, click add, delete, modify or query, and the corresponding prompt information will be displayed in the input box

Topics: Java Android Database SQLite android-studio