Pick contacts from Android Contacts using runtime permission check

Hey Guys! In this post, we will see how to pick a contact from android's contacts app and then show it inside our app. As you might already know, the permission needed for reading contacts, i.e,  Manifest.permission.READ_CONTACTS is  categorised under dangerous permission. So for such category of permissions, it is made mandatory that we request the permission once more at runtime, even though the permission is already added in AndroidManifest.xml. Enough of the details, we will jump into the code right away.

Before we begin just keep in mind that i will be using (data binding/view binding) in this app

Next, fire open your android studio and create a new project with an "Empty Activity" template.

As discussed, enable data binding by heading over to your app level build.gradle and adding the following within android {..}

dataBinding {
    enabled = true}

Now that we are all set with binding, we will see how to setup our layout file. So within your layout folder, find your activity's layout(named as activity_main.xml if you kept the activity name as default during project setup) . Now make the following changes to it
You can see that i have converted the above layout to a data binding layout by wrapping the root layout with a "<layout>" tag. 
Also, you may choose some images to be set to your AppCompatImageButton, you can either get the one i used by downloading the source code below, or grab some free images from google. Now you will be able to reference the views defined in this layout, directly by using their id without using findviewbyid method. Also, you need to add two edittexts - one for contact name and another one for contact phone. Also create a button to pick the contact from your device contact app.

Now update your MainActivity.java file as shown below


As shown above, you can initialise data binding library by using 
binding= DataBindingUtil.setContentView(this,R.layout.activity_main); and then use it to reference views like binding.nameEdtbinding.phoneEdtbinding.pickContact etc

As shown above, you can check for runtime permissions when the button is clicked, then if the permission is already granted take the user to the contacts picking screen, otherwise show the permission dialog. If the user grants the contacts read permission through this dialog, take him to the contacts picking screen, otherwise if he rejects, then prevent him/her from picking the contact.

Now that you are all set, if you try running the project you will see a similar output as shown below.

Picking contacts after checking runtime permission


Checkout full project source code here

No comments:

Post a Comment