Chapter 7 of First Line Code (Read System Contacts)

Keywords: Android xml SQLite encoding

1. Handle layout file: activity_main.xml: Create a simple ListView to hold contact data

<?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"
    android:orientation="vertical"
    tools:context="com.example.aaron_gan.contactstest.MainActivity">

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

    </ListView>

</LinearLayout>
2. Modify the code in MainActivity.java as follows:

public class MainActivity extends AppCompatActivity {

    ArrayAdapter<String> adapter;		//Create an adapter of string type
    List<String> contactsList = new ArrayList<>();	//Create a list of character number norm groups

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView contactsView = (ListView) findViewById(R.id.contacts_view);	//Instantiate ListView
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contactsList);
		//Instantiate the adapter, where three parameters are received (context, id of subitem layout (here is the layout file built into the android system, which has only one TextView) and the data to be adapted)
        contactsView.setAdapter(adapter);	//Pass the constructed adapter object through the setAdapter () method to ListView
		//Processing code for run-time permissions
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
        }else{
            readContacts();
        }
    }
	//Read contact data
    private void readContacts(){
        Cursor cursor = null;
        try{
            //Query Contact Data
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
            if (cursor != null){
                while(cursor.moveToNext()){//Get the contact name
                    String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    //Get the contact number
                    String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    contactsList.add(displayName+"\n"+number);
                }
                f;
            }

        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if(cursor != null){
                cursor.close();
            }
        }
    }
	//Processing the results of authorization
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    readContacts();
                }else {
                    Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
}

3. Focus on the method of reading contact data:

We use the query() method of ContentResolver to query the contact data of the system, but the incoming Uri parameter is not parsed as mentioned in the previous section. This is because the ContactsContract.CommonDataKinds.Phone class has helped us encapsulate, providing a constant of CONTENT_URI. The constants are consistent with the results of Uri.parse (). Then we traverse the Cursor object and take out the contacts and cell phone numbers one by one. They correspond to each other.

ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
ContactsContract.CommonDataKinds.Phone.NUMBER

Finally, through the add method of the List Normal Array, the spliced data is added into the array, and added into the data source of ListView. Finally, the Cursor object needs to be closed by calling the close () method.

4. Here's a little bit of knowledge about Cursor classes in SQLite:

Children's shoes that have used the SQLite database should be familiar with Cursor and deepen their understanding and understanding of using Cursor in Android.

About Cursor

Before you understand and use Android Cursor, you have to know a few things about Cursor:

Cursor is a collection of rows. Use moveToFirst() to locate the first line. You must know the name of each column. You must know the data type for each column. Cursor is a random data source. All data is obtained by subscription.
Important approaches to Cursor:

· close() - Close the cursor and release resources
· CopStringToBuffer (int column index, CharArray Buffer buffer) -- Retrieves the text of the requested column in the buffer and stores it
· getColumnCount() - Returns the total number of columns
· getColumn Index (String Column Name) -- Returns the name of the specified column if - 1 does not exist
· getColumnIndexOrThrow (String column nName) -- Returns the specified column name from scratch and throws an Illegal ArgumentException if it does not exist.
· getColumnName (int column nIndex) -- Returns column names from a given index
· getColumnNames() -- Returns the column name of an array of strings
· getCount() - Returns the number of rows in Cursor
· moveToFirst() - Move the cursor to the first line
· moveToLast() - Move the cursor to the last line
· moveToNext() - Move the cursor to the next line
· Move ToPosition (int position) - Move the cursor to an absolute position
· moveToPrevious() - Move the cursor to the previous line





Posted by eddy666 on Fri, 12 Jul 2019 18:25:57 -0700