Creating a Contact Saving Android Application with Realm Database - PART 3
utopian-io·@edetebenezer·
0.000 HBDCreating a Contact Saving Android Application with Realm Database - PART 3
#### 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.  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" `  ### 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:  *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 https://youtu.be/GQ4M6y2m3eg ### Complete application code can be found here - https://github.com/generalkolo/Realm-Contacts/ #### Curriculum - [Creating a Contact Saving Android Application with Realm Database - PART 1](https://steemit.com/utopian-io/@edetebenezer/creating-a-contact-saving-android-application-with-realm-database-part-1) - [Creating a Contact Saving Android Application with Realm Database - PART 2](https://steemit.com/utopian-io/@edetebenezer/creating-a-contact-saving-android-application-with-realm-database-part-2)
👍 edetebenezer, zcool, aafeng, shreetbn, official-hord, curx, zapncrap, cifer, jtomes123, utopian-1up, dyancuex, helo, mahdiyari, ronimm, simonluisi, thinkkniht, jesdn16, stoodkev, luisrod, ansonoxy, eastmael, espoem, moorkedi, kimaben, kslo, nathalie13, not-a-bird, bitopia, evilest-fiend, navx, family.app, varja, maphics, sebastiengllmt, phgnomo, zlatkamrs, amosbastian, goddywise4-eu, layanmarissa, proffgodswill, sweeverdev, kodeblacc, jerybanfield, rhotimee, kekegist, patatesyiyen, deejee, rsteem, isabella394, lemony-cricket, yeswanth, exploreand, petvalbra, photohunter1, photohunter3, photohunter4, photohunter5, livsky, roj, fai.zul, nightdragon, opulence, donjyde, crispycoinboys, bluestorm, pepememes, minersean, cryptophunk, ilyastarar, flauwy, jfuenmayor96, instantania.cat, harshallele, xtramedium, maneki-neko, gotgame, silasvogt, steaknsteem, eleonardo, zohaib715, checkthisout, handfree42, ilovekrys, not-a-cat, carsonroscoe, mountainjewel, xplore, solomon507, onin91, emailbox19149, videosteemit, cheesom, organicgardener, saifannur-mzy, orlandumike, hmctrasher, tailslide, andiepumpgun, aderemi01, sampath94, killbill73, amirdesaingrafis, aliyu-s, muratti, maribelanzola, pixelproperty, carlitojoshua, nonsqtr, muammarnst, jayo, knot, greenville, ahmad097, lsanek, lykia, realness, musicbot, anime.lovers, flugbot, ernoldlvb, kryptogermany, gydronium, clevershovel, masterofdisaster, godsngh1, truthtrader, jaber-hossain70, niouton, editorspicks, cryptocopy, artsyunicorn, ongolodesire, lemcriq, downtempo, studytext, ewuoso, esme-svh, biplob12, odesanya, camillius, kaell, toninux, fabiocola, soydandan, salahudeen, wealth4good, liveran, odibezeking, jdc, craigahamilton, animefanrd, devilonwheels, abbyrich, solpaman, ankapolo, steemassistant, bargolis, phasma, carloniere, steemitcanarias, saksham, phogyan, techmojo, idlebright, adhew, shenoy, jrmiller87, kaking, gwapoaller, cauac, iqbaladan, devart, azwarrangkuti, utopian-io,