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

in #utopian-io7 years ago (edited)

What Will I Learn?

  • How to create a contact saving application using 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

Today we are going to be creating a contact saving application using realm database.

Realm is an open source object database management system, initially for mobile (Android/iOS), also available for platforms such as Xamarin or React Native, and otheres, including desktop applications(Windows), and is licensed under the Apache License.

source

Realm plugin installation:

  • Head to your project level gradle file and add the class path dependency:

classpath "io.realm:realm-gradle-plugin:5.1.0"

  • Next, head to your application level gradile file "build.gradle" and add the realm-android plugin to the top of the file

apply plugin:'realm-android'

  • Finally, refresh your gradle dependencies.

Creating the Android Application Layout.

In this application, the user will be expected to enter a first name, last name, email and phone number, hence we will be developing a layout as this:

Screenshot_20180428-120625.png

Below is the code

<EditText
    android:id="@+id/first_name"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:hint="First Name"
    android:inputType="text" />

<EditText
    android:id="@+id/last_name"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:hint="Last Name"
    android:inputType="text" />


Code explanation

Firstly, the layout file has a RelativeLayout as its root layout which has a margin to the right of 5dp and also to the left.

Next, a linear layout is used inwhich two edittext are placed in it and it has an orientation of horizontal which means that its children views will be displayed from left to right and it has an id of nameContainer, this id will help us in placing the remaining edittext right.

For the two edittext to have the same width in the linear layout, they are both set to a width of 0dp and a weight of 1, this makes it possible that they take up equal space.

What you have to take note of is the inputtype which is set to text, this changes the layout of the keyboard and makes it easier for the user to enter his/her details.

Next, we have two more edittext with the first one placed below the nameContainer linear layout with the line android:layout_below="@+id/nameContainer", with an inputtext of email which chnages the user keyboard layout to the email layout and the next edittext has the input type of phone which gives the user a keyboard layout of only digits as phone numbers are only digits.

Lastly, we have a button with the id of save_btn and is horizontally centered with this line android:layout_centerHorizontal="true" ,
and it is placed below the phone edittext and has a margin top of 10dp with a text of save.

Once the user enteres the necessary informations and clicks the save button, we then write the data to the realm database.

Contacts

Realm database deals on objects, so inorder to save the contact details entered by the user, we create a Contact java file with the below code.

public class Contacts extends RealmObject{
private String firstName;
private String phoneNumber;
private String email;
private String lastName;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

}

NB: For this to be used successfully with realm, it must extend from RealmObject.

Then we have four string variables which will denote the details of the contact and then we have setters and getters for each string variable, this will be used when we want to create a realmobject using the Contact class file.

MainActivity.java

In our MainActivity.java file, this is where the bulk of the work is done. Inorder to save the user details, we will need to ensure that the user has entered all the details and none is left blank and to ensure that the user details was really saved, we will be making a toast with the user email that was just saved.

View Injection.

Since we are using the butterknife plugin, we are going to be generating butterknife injections for our four edittext and also an onclick injection for our save button, to do this you will need to head over to your activity java file and place your cursor on your layout file name and hit the alt+ins key on windows, the below image will be shown:

butterknife inject112.PNG

next click on the generate butterknife injection and a new dialog box will be shown, ensure that you select what i have selected as shown in the below image:

.butterknife inject2.PNG

After you have done that, you will see the below changes in your java class file:

@BindView(R.id.first_name)
EditText firstName;
@BindView(R.id.last_name)
EditText lastName;
@BindView(R.id.email)
EditText email;
@BindView(R.id.phone_number)
EditText phoneNumber;

this will be added to your onCreate method just below the binding of your layout file to your java class file:

ButterKnife.bind(this);

and for the onclick injection that we did for our save button, the below code will be added;

@OnClick(R.id.save_btn)
public void onViewClicked() {}

NB: You don't have to inject the view for the button to generate the onClcik method, you can generate the onClick method without injecting the view as we did for the edittext.

Firstly, we need to declear a realm variable which we will be using to make transactions and inorder to use it throughout the java class file, we declear is as a field, just below the injections made by butterknife - Realm realm;

Next, we have to initialize the Realm database in the onCreate method by calling the init method with the context as its arguement:
Realm.init(this);

Next, we also get a Default Instance - realm = Realm.getDefaultInstance();

As stated above, once the user clicks the save button, we want to ensure that the user has entered all the details of the contact that he/she wishes to save. So to do this, in the onClick method of the save button, we will get the text from the four edittext and pass it to a method and then check to ensure that none of them is empty.

String first_name = firstName.getText().toString();
String last_name = lastName.getText().toString();
String Email = email.getText().toString();
String phonenumber = phoneNumber.getText().toString();

We get the text from the editext and initialze it to a string value.

We get the content of the edittext by calling the getText() method together with the toString() method.

i.e String first_name = firstName.getText().toString().

Now, the first name, last name , email and phone Number entered by the user is held in the first_name, last_name, Email, phonenumber string variables respectively.

Next, we check if the user has entered all the detials by using an if statement as below:

if(validRegistration(first_name,last_name,Email,phonenumber))
SaveContacts(first_name,last_name,Email,phonenumber);

the validRegistration() method returns a boolean value which is defined as below:

private boolean validRegistration(String firstName, String lastName, String email, String phoneNumber) {
boolean complete_registration = false;

    if (firstName.isEmpty() || lastName.isEmpty() || email.isEmpty() || phoneNumber.isEmpty())
        showToast("No Field can be empty!!");
    else
        complete_registration = true;

    return complete_registration;
}

Code explanation:

The validRegistration() method takes in two string arguements.

Next we set a boolean variable called complete_registration to false which is what the method will return.

We then check to enusre that none of the string values are empty by calling the isEmpty() method on all four string variables.

If any of them is empty, we simply make a toast to the user saying that no field can be empty as seen on the line showToast("No Field can be empty");

If none of the string variables are empty, we set the complete_registration boolean variable to true and finally we return the complete_registration as the return value of the method.

The showToast() method is a method that simply makes a toast with the string variable passed to it and the method definition is seen below:

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

If the value return from the validRegistration() method is true, we call the SaveContacts() method with the four string variables as arguements to the method.

The SaveContacts() methods definition is seen as below:

private void SaveContacts(String first_name, String last_name, String email, String phonenumber) {
realm.beginTransaction();

    Contacts contacts = realm.createObject(Contacts.class);

    contacts.setEmail(email);
    contacts.setFirstName(first_name);
    contacts.setLastName(last_name);
    contacts.setPhoneNumber(phonenumber);

    realm.commitTransaction();

    setEmptyEditText();

    realm.beginTransaction();

    RealmResults<Contacts> contactResult = realm.where(Contacts.class).equalTo("email",email).findAll();
    showToast(contactResult.get(0).getEmail());

    realm.commitTransaction();
}

To do anything on realm , you have to begin a transaction which can be done by calling the beginTransaction() method on the realm varibale decleared below the butterknife injection - realm.beginTransaction().

Contacts contacts = realm.createObject(Contacts.class);

The above line create a realmObject from the Contacts class and then the contacts variable is then used to set the necessary details of the contact and then we commit the transaction.

NB: For every realm transaction, you have to commit the transaction.

Next, we call the setEmptyEditText(); which sets the four edittext elements to be empty, the method declaration is shown below:

private void setEmptyEditText() {
firstName.setText("");
lastName.setText("");
email.setText("");
phoneNumber.setText("");
}

Next, inorder for us to be sure that the transaction we just made was successful, we begin another realm transaction - realm.beginTransaction();

Inorder for you to get results from the realm database, you must declear a realmResults value as shown below:

RealmResults contactResult = realm.where(Contacts.class).equalTo("email",email).findAll();

The above code checks if there is any contact that it's email mathces the email variable passed.

the "email" indicates the field name and the ,email indicates the variable to which the data must match, the .findAll() ensure that the result returned returns all the result if there is multiple results.

We then make a toast with the contacts email address with the line - showToast(contactResult.get(0).getEmail());

And Finally, we commit the transaction - realm.commitTransaction();

Complete code can be found here - https://github.com/generalkolo/Realm-Contacts

Application execution

Sort:  

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]

Thanks for taking your time to moderate my contribution @portugalcoin

You have a minor misspelling in the following sentence:

Once the user enteres the neccessary informations and clicks the save button, we then write the data to the realm database.
It should be necessary instead of neccessary.

Please enter the correct source link!


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

[utopian-moderator]

@portugalcoin i have corrected it, thanks

Hey @edetebenezer! Thank you for the great work you've done!

We're already looking forward to your next contribution!

Fully Decentralized Rewards

We hope you will take the time to 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

Coin Marketplace

STEEM 0.25
TRX 0.19
JST 0.036
BTC 91660.56
ETH 3295.97
USDT 1.00
SBD 3.83