Home / Android /

Android libphonenumber Example

Today I want to show you a simple example code on how to use a very useful library called libphonenumber, a phone number handling library from Google. It can validate the correct number format for your country. In this example we’re using PH (Philippines) as country code. It is optimized for running on smartphones, and is used by the Android framework since 4.0 (Ice Cream Sandwich). Phone number validation is essential for your app so that you can get useful and sound phone numbers from your loyal users. Any verification code, messages or greetings that you want to send them will have lower chances of being missed.

Android libphonenumber Example

Example of a valid cellphone number.

You can download the code here:

DOWNLOAD SOURCE CODE

Online demo here.

Step 1

Download the latest JAR file here. As of this writing, I got libphonenumber-5.2v1.5.jar

Step 2

Copy the JAR file in the libs folder of your project.

libphonenumber

Step 3

Add the JAR on your project. Go to Properties > Java Build Path > Libraries Tab > Click Add Jars.. Button > Browse the JAR file on you libs and click OK. This is what it should look like:

projproperties

Step 4

Our sample XML layout file (activity_main.xml) will have the following code:

<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” >
    <EditText
       android:id=“@+id/phoneNumberEditText”
       android:layout_width=“match_parent”
       android:layout_height=“wrap_content”
       android:layout_alignParentLeft=“true”
       android:layout_alignParentTop=“true”
       android:ems=“10″
       android:inputType=“phone” >

        <requestFocus />
    </EditText>

    <Button
       android:id=“@+id/validateButton”
       android:layout_width=“wrap_content”
       android:layout_height=“wrap_content”
       android:layout_alignParentLeft=“true”
       android:layout_below=“@+id/phoneNumberEditText”
       android:text=“Validate Phone Number” />

</RelativeLayout>

Step 5

Our main activity will have the following code:

package com.example.libphonenumber;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

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

        try {
            // so that we can get the inputted phone number
            final EditText et = (EditText) findViewById(R.id.phoneNumberEditText);

            View.OnClickListener handler = new View.OnClickListener() {
                public void onClick(View v) {
                    
                    switch (v.getId()) {

                    // clicking the validate button
                    case R.id.validateButton:

                        // get the inputted phone number
                        String phoneNumber = et.getText().toString();
                        
                        // On our country, people are used to typing 7 (landline) or 11 (cellphone) digit numbers
                        // To make it 7 digit numbers valid, I have to prepend “02″
                        if (phoneNumber.length() == 7) {
                            phoneNumber = “02″ + phoneNumber;
                        }

                        // Use the library’s functions
                        PhoneNumberUtil phoneUtil = PhoneNumberUtil
                                .getInstance();
                        PhoneNumber phNumberProto = null;

                        try {

                            // I set the default region to PH (Philippines)
                            // You can find your country code here http://www.iso.org/iso/country_names_and_code_elements
                            phNumberProto = phoneUtil.parse(phoneNumber, “PH”);

                        } catch (NumberParseException e) {
                            // if there’s any error
                            System.err
                                    .println(“NumberParseException was thrown: “
                                            + e.toString());
                        }

                        // check if the number is valid
                        boolean isValid = phoneUtil
                                .isValidNumber(phNumberProto);

                        if (isValid) {

                            // get the valid number’s international format
                            String internationalFormat = phoneUtil.format(
                                    phNumberProto,
                                    PhoneNumberFormat.INTERNATIONAL);

                            Toast.makeText(
                                    getBaseContext(),
                                    “Phone number VALID: “ + internationalFormat,
                                    Toast.LENGTH_SHORT).show();

                        } else {

                            // prompt the user when the number is invalid
                            Toast.makeText(
                                    getBaseContext(),
                                    “Phone number is INVALID: “ + phoneNumber,
                                    Toast.LENGTH_SHORT).show();

                        }

                        break;

                    }
                }
            };

            // we will set the listeners
            findViewById(R.id.validateButton).setOnClickListener(handler);

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Sample Output: (I felt like my phone is too small so I tested it on my tablet haha!)

An example of a valid land line number.

An example of a valid land line number.

Example of an invalid land line number.

Example of an invalid land line number.

Example of an invalid cellphone number.

Example of an invalid cellphone number.

That’s it! Happy New Year guys! :)

Loading comments...