Creating a Contact Saving Android Application with Realm Database - PART 3

in #utopian-io7 years ago (edited)

What Will I Learn?

  • How to create a contact saving application
  • Updating the contact details in the realm database.

Requirements

  • Java knowledge
  • IDE for developing android applications(Android Studio or IntelliJ)
  • An Android Emulator or device for testing

Difficulty

  • Intermediate

Tutorial Contents

In todays tutorial, we will learn how to update contact details in our realm contact application.

Changes done to previous code file

MainActivity.java

@OnClick({R.id.addContact, R.id.readContact, R.id.updateContact, R.id.deleteContact})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            ...
            case R.id.updateContact:
                startActivity(new Intent(this,updateContact.class));
                break;
            ...
        }
    }

The changes done to this code is located in our onclick method injected by butterknife to handle the click of our buttons on our landing page.

Hence when the user clicks the update button, we start a new acivity with the java class file updateContact.class with an explicit intent - startActivity(new Intent(this,updateContact.class));

With that being done, create a new activity class file and call the java class file updateContact.class and for this tutorial, the activity layout file will be activity_update_contact.xml

The concept of the update contact details is thus:

  • The user will have to enter the email address of the contact whose details he/she wants to update.
  • If there exist such contact, his/her details will be displayed inorder for the user to update the details.
  • The update button is clicked and the contact details is updated.

In order to achieve our above goals, we firstly will create a layout which will have an edittext and a button, the edittext for entering of the contact's email address and the search button for clicking to search for the contact.

Once the contact is found in our database, the contact details will be populated in a relative view whose visibility will be set to gone from the xml file and once the contact details is updated and the update button clicked, provided there is no error then we update the user details, set the relative layout visibility to gone again and then close the update contact avtivity.

Layout

The below layout is built:

  • The layout where the user will enter the contact's email to be updated.

IMG_20180501_132817.jpg

The layout which will hold the contact details once such user is found,
NB: Its visibility will be set to gone as seen in the code - android:visibility="gone"

IMG_20180501_132845.jpg

Code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="com.semanientreprise.realmcontacts.updateContact">

    <LinearLayout
        android:id="@+id/searchContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/search_emailAddress"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:hint="Enter Users Email Address"
            android:inputType="textEmailAddress" />

        <Button
            android:id="@+id/search_btn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="Search" />

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/searchResultContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/searchContainer"
        android:layout_marginTop="50dp"
        android:visibility="gone"
        >

        <LinearLayout
            android:id="@+id/search_nameContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <android.support.design.widget.TextInputLayout
                android:id="@+id/search_first_name"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="First Name"
                    android:inputType="text" />

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:id="@+id/search_last_name"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Last Name"
                    android:inputType="text" />

            </android.support.design.widget.TextInputLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_below="@+id/search_nameContainer"
            >

            <android.support.design.widget.TextInputLayout
                android:id="@+id/search_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/search_nameContainer"
                android:layout_weight="1">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Email"
                    android:inputType="textEmailAddress" />

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:id="@+id/search_phone_number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Phone Number"
                    android:inputType="phone" />

            </android.support.design.widget.TextInputLayout>

            <Button
                android:id="@+id/update_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="10dp"
                android:text="Update" />

        </LinearLayout>

    </RelativeLayout>

</RelativeLayout>


Code explanation.

For the TextInputLayout elements, they are used here to give the edittext a floating label when the user enters something in this edittext as seen in the picture below:

IMG_20180501_132924.jpg

Please refer to our previous tutorials, as nothing new has been done in the layout file.

Next, we head over to our java class file - updateContact.java

Inorder for us to be able to control the visibility of the relative layout with the id - searchResultContainer which is the layout responsible for housing the user details once found in the database, we must also inject it using butterknife amongst others.

Butterknife injections

@BindView(R.id.search_emailAddress)
EditText searchEmailAddress;
@BindView(R.id.search_first_name)
EditText searchFirstName;
@BindView(R.id.search_last_name)
EditText searchLastName;
@BindView(R.id.search_nameContainer)
LinearLayout searchNameContainer;
@BindView(R.id.search_email)
EditText searchEmail;
@BindView(R.id.search_phone_number)
EditText searchPhoneNumber;
@BindView(R.id.searchResultContainer)
RelativeLayout searchResultContainer;

Next, we declear a realm variable - Realm and a Contact variable -contact` which will be used for realm operations throughout this activity and used to hold a single detail.


Realm realm;
private Contacts contact;


As seen in our previous tutorials, we initialize realm and also get a default instance in our onCreate method as shown:


Realm.init(this);
realm = Realm.getDefaultInstance();

If you have rightly injected the onClick method for both buttons, the search and the update button in your java class file then we make the following edit to the two methods.


@OnClick({R.id.search_btn, R.id.update_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_btn:
                String search_email = searchEmailAddress.getText().toString();
                if (!search_email.isEmpty())
                    searchForContact(search_email);
                else
                    showToast("Please enter user email address");
                break;
        }
    }

Code Explanation

When the search button is clicked, we firstly get the email the user entered and store it in a String variable - search_email.

Next we check to ensure that the email entered is not empty but if empty, we display a toast message to the user saying - Please enter user email address.

If the email is not empty then call we call the searchForContact() method with the user email as the argument.

searchForContact() METHOD


private void searchForContact(String search_email) {
        realm.beginTransaction();

        contact = realm.where(Contacts.class).equalTo("email", search_email).findFirst();

        realm.commitTransaction();

        if (contact == null)
            showToast("No contact with such email found");
        else
            setUpContactForEditing(contact.getEmail(), contact.getFirstName(), contact.getLastName(), contact.getPhoneNumber());

    }

Firstly, we begin a transaction - realm.beginTransaction();.

contact = realm.where(Contacts.class).equalTo("email", search_email).findFirst();

The above line checks the Contact database and checks the email field is there exist any row of data that equals the entered email by the user by using the .equalTo("email",search_email) , next we use the .findFirst() method to get the first occurance.

Next we commit the transaction realm.commitTransaction();.

Next we check if the return contact is null, meaning no such contact exist and if thats the case we display a toast with the message - "No contact with such email found".

And if a user exist with the email, we call the setUpContactForEditing() method with the details of the contact - email, first name, last name, phone number .

setUpContactForEditing()


private void setUpContactForEditing(String email, String firstName, String lastName, String phoneNumber) {

        searchFirstName.setText(firstName);
        searchLastName.setText(lastName);
        searchEmail.setText(email);
        searchPhoneNumber.setText(phoneNumber);

        searchResultContainer.setVisibility(View.VISIBLE);
    }

This method sets the details of the user into the four edittext so that changes can be made and update done.

Once the user details is updated and the update button clicked, the below switch case is fired.

UPDATE BUTTON


case R.id.update_btn:
                String new_email = searchEmail.getText().toString();
                String new_firstName = searchFirstName.getText().toString();
                String new_lastName = searchLastName.getText().toString();
                String new_phoneNumber = searchPhoneNumber.getText().toString();

                updateContactDetails(new_email,new_firstName,new_lastName,new_phoneNumber);
                break;

We get the new details of the contact and set it to string variables and then we call the updateContactDetails() method.

updateContactDetails()


private void updateContactDetails(String new_email, String new_firstName, String new_lastName, String new_phoneNumber) {
        realm.beginTransaction();

        contact.setFirstName(new_firstName);
        contact.setLastName(new_lastName);
        contact.setEmail(new_email);
        contact.setPhoneNumber(new_phoneNumber);

        realm.commitTransaction();

        showToast("One Contact Updated");

        finish();
    }

Firstly, we begin the transaction on the realm variable - realm.beginTransaction();.

The contact variale being set here is the same contact that we got when searching the realm database and here is where the update of the contact detials is being done and once we are done setting the new details of the contact, we call the commit transaction command - realm.commitTransaction();.

Finally, we display a toast to the user saying - "One Contact Updated" and we call the finish() method which closes the current activity.

showToast() METHOD


private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

Application execution

Sort:  

Hey @edetebenezer

We're already looking forward to your next contribution!

Decentralised Rewards

Share your expertise and knowledge by rating contributions made by others on Utopian.io to help us reward the best contributions together.

Utopian Witness!

Vote for Utopian Witness! We are made of developers, system administrators, entrepreneurs, artists, content creators, thinkers. We embrace every nationality, mindset and belief.

Want to chat? Join us on Discord https://discord.me/utopian-io

Thank you for the contribution It has been approved.


Need help? Write a ticket on https://support.utopian.io.
Chat with us on Discord.

[utopian-moderator]

@portugalcoin thanks for taking the time to moderate my post. 👍