[Android Getting Started to Project Combat -- 6.2] -- How to access the data of other applications?

Table of contents

1. Basic usage of ContentResolver

        How to query?

        How to add a piece of data to the table?

        How to update this newly added data?

        How to delete this data?

2. Read system contacts


        If you want your APP to access the data of other applications, you need to use a content provider. Next, use the existing content provider to read and manipulate the data in the corresponding program.


1. Basic usage of ContentResolver

        If you want to access the data shared in the content provider, you need to use the ContentResolver class, which provides a series of methods for CRUD operations on the data.

        The CRUD method in ContentResolver receives a Uri parameter, which is called content URI, which establishes a unique identifier for the data in the content provider, and mainly consists of two parts: authority and path. authority is used to distinguish different applications, generally using the package name; path is used to distinguish different tables in the same application, for example: there is a table in the database of a certain program: table1, the content at this time The URI is com.example.app.provider/table1, and the standard format is: content://com.example.app.provider/table1.

        After getting the content URI string, parse it into a URI object before it can be passed in as a parameter, the method is as follows:

Uri uri = Uri.parse("content://com.example.app.provider/table1")

        Just call the Uri.parse() method to parse the content URI string into a Uri object.

        Now you can use this Uri object to query the data in the table1 table, the code is as follows:

Cursor cursor = getContentResolver().query(
    uri,
    projection,
    selection,
    selectionArgs,
    sortOrder
);

        The following table provides a detailed explanation of the parameters used:

 

        How to query?

         After querying, it is still a Cursor object. The idea of ​​reading is still to traverse all the rows of Cursor, and then fetch the data of the corresponding column in each row. The code is as follows:

  if(cursor!=null){
        while (cursor.moveToNext()){
            String column1 = cursor.getString(cursor.getColumnIndex("column1"));
            int cloumn2 = cursor.getInt(cursor.getColumnIndex("column2"));
        }
        cursor.close();
    }

 

        How to add a piece of data to the table?

code show as below:

ContentValues values = new ContentValues();
values.put("column1","text");
values.put("column2",1);
getContentResolver().insert(uri,values);

 

        How to update this newly added data?

code show as below:

ContentValues values = new ContentValues();
values.put("column1","");
getContentResolver().update(uri,values,"column1=? and column2 = ?",new String[] {"text","1"});

 

        How to delete this data?

code show as below:

getContentResolver().delete(uri,"column2 = ?",new String[] { "1" });

Let's practice by reading the system contacts.

2. Read system contacts

First manually add a few contacts in the simulator

Then create a new ContactsTest project.

Modify the activity_main.xml code as follows:

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

    <ListView
        android:id="@+id/contacts_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

 Modify the MainActivity code as follows:

        Because READ_CONTACTS is a dangerous permission, the runtime permission is processed first, and the readContacts() method is called to read the contact information after the user authorizes.

        The readContacts() method uses the query() method of ContentResolver, but the Uri passed in is different from the previous one. This is because the ContactsContract.CommonDataKinds.Phone class has been packaged and provides a CONTENT_URI constant, which is parsed out result. Then take out the name and mobile phone number one by one, each of which has a corresponding constant.

public class MainActivity extends AppCompatActivity {

    ArrayAdapter<String> adapter;

    List<String> contactsList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView contactsView = (ListView) findViewById(R.id.contacts_view);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,contactsList);
        contactsView.setAdapter(adapter);
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
        }else{
            readContacts();
        }
    }

    private void readContacts(){
        Cursor cursor = null;
        try {
//            查询联系人数据
            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));
                    contactsList.add(displayName + "\n" + number);
                }
                adapter.notifyDataSetChanged();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(cursor != null){
                cursor.close();
            }
        }
    }

    public void onRequestPermissionResult(int requestCode,String[] permissions,int[] grantResults){
        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    readContacts();
                }else{
                    Toast.makeText(this, "你拒绝了权限申请", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
}

        Finally, you need to declare the permission to read system contacts, modify the AndroidManifest.xml file, the code is as follows:

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

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

...............

The effect is as follows:

 

Guess you like

Origin blog.csdn.net/Tir_zhang/article/details/130346675