How to Build a Contact Book Android App - Hive Programmers

avatar

Greetings to my favorite Science community online, StemSocial.

It's @skyehi and I'm super excited to be back to continue my series on Android App development tutorials for beginners. I'm extra excited today because we're going to be doing some extra work.

I'll be sharing a relatively longer blog because the App we're going to be building today is a bit more complex. This is part of our journey to becoming experts in Android App development.

For today's blog, I'm going to teach you how to build an Android Phone book or Contact book App. Every phone whether smart phone or not has a contacts list App where the user can see a list of all the contacts they have on the phone.

Polish_20231207_181657708.pngOriginal Image Source by 200degrees from Pixabay

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Of course we may not be building an entire phone call App like "Truecaller" but we'll definitely build something fairly complex.

In yesterday's blog we built a Barcode Scanner app and for today's blog we're building an entire Contact Book App. I'm so happy we're working on very useful Apps.

Like I said in my previous blog, the more advanced and useful the Apps you're capable of building as a developer, the more successful and demanded you'll become.

Let's get started with our App project for today shall we.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Setting Up Our App Project

Alright guys, the first and obvious thing to do is to open Android Studio IDE and create a new Android Studio Project. If you're a newcomer to my tutorial and you haven't already installed Android Studio, please do because that's the platform we've been using and we will continue to use to develop our Android Apps.

You can download that from their official website. You would also need to download and install Java Development Kit, JDK since that's the language we'll be coding in, and your computer would definitely need to have JDK properly installed to be able to execute Java code.

If you're having troubles installing any of these programs on your PC, please let me know in the comments.

At this point I'll assume everyone has successfully installed Android Studio and JDK.

So we're back to the first step where you open Android Studio, click on "Start a new Android Studio project," and as usual, choose an Empty Activity template.

You can now create the App name and package name of your App. I'll simply call my App, "Stem Contacts"

Also please do not forgot to ensure that Java is the selected programming language instead of Kotlin since we'll be developing our App logic in Java language.

Configure Dependencies

Now that our App project is created, the next thing we're going to do is to implement some dependencies just like we did with the previous tutorial building the Barcode Scanner App.

The dependency we want to add is a recyclerview dependency since that's what we'll be using for the frontend design of our Contacts App.

It will be implemented inside the build.gradle (Module: app) file.

Here's how your code should look like

dependencies {
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
}

After editing the gradle file, click on the green "Sync" button that appears while editing the Gradle. This would download the dependency and add it to the App project.

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Designing our User Interface

Since we're through with adding the right dependencies, we can now start working on the design or frontend of our Contact Book App.

With this particular App, most of the work will be done at the backend. For the design, it's going to be a simple RecyclerView layout which was why it was necessary to add its dependency inside our Gradle file.

The layout design will be created inside the res/layout/activity_main.xml file. The RecyclerView layout will be used to display contacts.

Here's how your code should look like

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Working with Contacts

Alright guys, we're now going to start working on the logic of our App. To build the Contacts Book App we would first need to create a Java class which would represent the contact information. This is what you would call a contact model class.

So please go ahead and create a Java class and name it Contact.java. In that class we'll create two main strings, one for the contact name and the other for the contact number.

Of course in more advanced Apps, we'll be adding more details like, location, Special ringtones, date of adding contacts and more.

But for now let's just create a simple data class for the contact information.

Here's how your code should look like.

public class Contact {
    private String name;
    private String phoneNumber;

    public Contact(String name, String phoneNumber) {
        this.name = name;
        this.phoneNumber = phoneNumber;
    }

    public String getName() {
        return name;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }
}

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Requesting Permission

For our Contacts book App to be able to gain access to the contacts list information of any Android phone and display, we would need to request Read_Contacts permission.

Of course if it's about requesting permission, it would certainly be done inside AndroidManifest.xml file. So guys open the Android Manifest and add the read contacts permission.

Here's how your permission code should look like

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

We can now have access to the contacts data of the Android device. We will also be requesting permission inside the Main logic of our App. This will be a permission request using Java language.

Let's continue our tutorial.

Fetching Contacts

For our Contacts book App to be able to display contacts list of any Android phone, we first need to write the code that would fetch the contacts.

After fetching the contacts, we can continue by creating an Adapter and an Item layout that would display the contacts inside the Recycleview layout we created earlier on.

For now let's focus on retrieving the contacts. The logic for fetching the contacts data will be written inside the MainActivity.java file. With this code we'll be doing two things; requesting and handling contact retrieval

Here's how your code should look like.

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<Contact> contactsList = new ArrayList<>();

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

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                == PackageManager.PERMISSION_GRANTED) {
            fetchContacts();
        } else {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.READ_CONTACTS},
                    1
            );
        }
    }

    private void fetchContacts() {
        Cursor cursor = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,
                null,
                null,
                null
        );

        if (cursor != null) {
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(
                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phoneNumber = cursor.getString(cursor.getColumnIndex(
                        ContactsContract.CommonDataKinds.Phone.NUMBER));
                contactsList.add(new Contact(name, phoneNumber));
            }
            cursor.close();
        }

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(new ContactAdapter(contactsList));
    }

    // Handle permission request result
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == 1 && grantResults.length > 0 &&
                grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            fetchContacts();
        }
    }
}

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Displaying the Contacts by first Creating an Adapter

We're through with fetching or retrieving the contacts data of the phone, we can now work on displaying the information. Like I said earlier, we'll have to do two things for this to work. The first thing is to create an adapter class for our RecyclerView.

So guys, create a new Java class and I think I'll simply name this one ContactAdapter.java . This is where our layout inflation code will be written.

Here's how your Adapter class should look like. If you're a total newbie, I would advise that you stick to the example and constants I gave because one change in any of the words could either prevent your App from running or could cause the App to crush when it launches.

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {

    private List<Contact> contacts;

    public ContactAdapter(List<Contact> contacts) {
        this.contacts = contacts;
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_contact, parent, false);
        return new ContactViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ContactViewHolder holder, int position) {
        Contact contact = contacts.get(position);
        holder.contactName.setText(contact.getName());
        holder.contactPhoneNumber.setText(contact.getPhoneNumber());
    }

    @Override
    public int getItemCount() {
        return contacts.size();
    }

    static class ContactViewHolder extends RecyclerView.ViewHolder {
        TextView contactName;
        TextView contactPhoneNumber;

        ContactViewHolder(View itemView) {
            super(itemView);
            contactName = itemView.findViewById(R.id.contactName);
            contactPhoneNumber = itemView.findViewById(R.id.contactPhoneNumber);
        }
    }
}

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Displaying the Contacts by creating Item Layout

It's time for the second phase of displaying the contacts data. This is going to be more of a design phase.

Since each contact on your phone would have a name and a number, we would need to create an Item layout that would hold both the name and numbers.

Trust me guys it's an easy design layout and all you need to do is to create a layout file for the contact item.
Let's call our layout file res/layout/item_contact.xml

Here's how the item layout code should look like

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/contactName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/contactPhoneNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:textSize="14sp"/>
</LinearLayout>

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Running The App

We're finally done with the most complex App in our tutorial series so far. I hope you were not overwhelmed with the amount of code we had to write.

Coding takes a lot of time and effort and you can see how much work has gone into an App as basic as this one. However, since it's a project we all enjoy, I was happy to go through the process.

It's time to run our finished App. As usual, you can either run the App using your physical Android phone or with an Emulator.

Similar to our previous project, the Barcode Scanner, I would recommend using your physical Android phone. It's because, your contacts will probably be on your phone and not the PC you were coding with.

When the App launches, you should see a beautiful list display of all your contacts. Each contact should have the number and the name you saved the contact as.

Thank you so much for taking the time to read today's blog. I hope you enjoyed this tutorial. We're slowly starting to write longer and more complex codes.

Soon we'll be building professional Apps guys, hang in there and have fun out there.

Have a lovely day and catch you next time on StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000