Username Availability Check Android Application using Java RESTful Webservice

In this post, I will be discussing on how to create Android application to check if the username typed by user is available to choose or not.

When it comes to Username availability check, I always remember Google registration page where it checks for the username availability once you finished typing username and moved to next form control and also it updates the User whether the Username is available to pick or not.

I tried to register with username that already exists, I just captured the screen-print of it.

Take a look at it below:

Google_Username_Availability_Check

Explore Google – Username Availability check from here.

Okay enough theory, let us jump into creating Android application which will perform username availability check similar to Google using RESTful webservice. It would be more useful to you if you quickly take a look at the below video demo which shows how the Application will work.

Video Demo

How it works technically?

uname_checker_app_flow

Steps involved in creating the Android application:

You can download source code from here if you don’t want to create Application from scratch, otherwise please proceed with below listings.

Recommended course for you

Take me to course

Step 1: Create RESTful webservice and deploy it in Application server

I already discussed about creating RESTful webservice to perform username availability check in another post. You can either create it by taking help from the tutorial (Read: How to Create Username Availability Check Webservice using REST?) or download webservice from there and make it up and running in your local application server.

Step 2: Create Android Application Project

  • Create new android project [File >> New >> Android Application Project] with project name UserNameCheck
  • Enter package name as ‘com.prgguru.example’
  • Choose Minimum Required SDK, Target SDK and Compile with. Confused on choosing these options? Take a look at Minimum Required SDK – Target SDK – Compile With post.
  • Click Next button and finally click ‘Finish’ to create project

Step 3: Add library to project

Add below third party library into project’s ‘lib’ folder. You can also download it if you don’t have it with you.

Android Asynchronous Http Client – An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries which is used by Pinterest, Instagram etc.,. Download

Step 4: Design Screen

We are going to have only one activity:

UserNameCheck – Has Edittext field to enter Username, Button to send username to Server and TextView/ImageView to show username availability status.

Create a layout XML under /res/layout folder:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/statusImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" android:layout_marginTop="10dp"/>

    <TextView
        android:id="@+id/unameTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/statusImg"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="15dp"
        android:gravity="center_horizontal"
        android:text="Result will appear here"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/unameEditText"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/unameTextView"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="5dp"
        android:inputType="text"
        android:maxLength="12" />

    <Button
        android:id="@+id/btnSilentMode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/unameTextView"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="5dp"
        android:layout_toRightOf="@+id/unameEditText"
        android:background="@drawable/ic_action_search"
        android:onClick="checkbtn" >
    </Button>

</RelativeLayout>

[pglinkadssmall1]

Step 5: Utility.java – Utitlity Class

We are done with Layout designing, let us jump into Coding.

Create Utility.Java under the package com.prgguru.example and fill it with below code. It has Utility methods to be used in other Activity classes.

package com.prgguru.example;

/**
 * Class which has Utility methods
 * 
 */
public class Utility {
	/**
	 * Checks for Null String object
	 * 
	 * @param txt
	 * @return true for not null and false for null String object
	 */
	public static boolean isNotNull(String txt){
		return txt!=null && txt.trim().length()>0 ? true: false;
	}
}

Step 6: UserNameCheck.java – Application Home Screen Class

Application Main screen which will allow User to enter Username and check if it is available to choose or not. Make sure the IP address has been changed in the AsyncHttp Get method with IP address of your machine:

UserNameCheck.java is well commented, so by reading the comments you will understand. In case, if you still have any question discuss it right away.

package com.prgguru.example;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class UserNameCheck extends Activity {
	
	private EditText editText;
	private TextView textView;
	private ImageView imgView;
	// Progress Dialog Object
	ProgressDialog prgDialog;
	RequestParams params = new RequestParams();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		editText = (EditText) findViewById(R.id.unameEditText);
		textView = (TextView) findViewById(R.id.unameTextView);
		imgView = (ImageView) findViewById(R.id.statusImg);

		prgDialog = new ProgressDialog(this);
		// Set Progress Dialog Text
		prgDialog.setMessage("Please wait...");
		// Set Cancelable as False
		prgDialog.setCancelable(false);
	}

	public void checkbtn(View v) {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
		// When Username is greater than or equal to 5 characters
		if (Utility.isNotNull(editText.getText().toString()) && editText.getText().toString().length() >= 5) {
			// Set Username typed by user in Request Params object
			params.put("username", editText.getText().toString());
			// Invoke REST Web service to check if username typed is available or not
			invokeWS(params);
		} 
		// When Username is not greater than or equal to 5 characters
		else {
			imgView.setBackgroundResource(R.drawable.ic_action_warning);
			textView.setText("Username must be minimum 5 characters");
		}
	}

	public void invokeWS(RequestParams params) {
		// Show Progress Dialog
		prgDialog.show();
		// Make RESTful webservice call using AsyncHttpClient object
		AsyncHttpClient client = new AsyncHttpClient();
		client.get("http://192.168.2.4:9999/usernamecheckws/unamechecker/docheck",params,
			new AsyncHttpResponseHandler() {
				// When the response returned by REST has Http response code '200'
				@Override
				public void onSuccess(String response) {
					// Hide Progress Dialog
					prgDialog.hide();
					try {
						// Extract JSON Object from JSON returned by REST WS
						JSONObject obj = new JSONObject(response);
						// When the JSON response has status boolean value set to true
						if (obj.getBoolean("status")) {
							// Set 'Thumb up' Image as status image
							imgView.setBackgroundResource(R.drawable.ic_action_good);
							// Set Status message
							textView.setText("Username Available to choose");
							Toast.makeText(getApplicationContext(),"WS Inovation Done", Toast.LENGTH_LONG).show();
						}
						// Else display error message set in JSON response
						else {
							imgView.setBackgroundResource(R.drawable.ic_action_warning);
							textView.setText(obj.getString("error_msg"));
							Toast.makeText(getApplicationContext(), "WS Inovation Done",Toast.LENGTH_LONG).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						Toast.makeText(getApplicationContext(),"Error Occured while parsing [Server's JSON response might be invalid]!",Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
				}
				// When the response returned by REST has Http response code other than '200' such as '404', '500' or '403' etc
				@Override
				public void onFailure(int statusCode, Throwable error, String content) {
					// Hide Progress Dialog
					prgDialog.hide();
					// When Http response code is '404'
					if (statusCode == 404) {
						Toast.makeText(getApplicationContext(), "Requested resource not found",Toast.LENGTH_LONG).show();
					}
					// When Http response code is '500'
					else if (statusCode == 500) {
						Toast.makeText(getApplicationContext(), "Something went wrong at server end",Toast.LENGTH_LONG).show();
					}
					// When Http response code other than 404, 500
					else {
						Toast.makeText(getApplicationContext(),	"Unexpected Error occcured! [Most common Error: Device might " +
								"not be connected to Internet or remote server is not up and running], check for other errors as well",
								Toast.LENGTH_LONG).show();
					}
				}
			});
	}
}

RESTful Webservice Response – JSON

Username Availability Check
When Username doesn’t exist in DB, that means User can avail it, the returned JSON will look like:

{
tag: "unamecheck"
status: true
}

When Username does exist in DB, the JSON returned by REST will look like:

{
tag: "unamecheck"
status: false
error_msg: "Someone already has that username. Try another?"
}

Demo

Make sure the RESTful webservice you created is up and running.

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.




Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse).

Download Source Code

*apk in Android  is the installation file similar to exe in windows.

[pglinkadssmall]

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

Share

You are always welcome to provide your comments and feedback from comment box.

[pgwriteforus]

[pgfeedback]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • adarshmadrecha

    New to this website, but really liked all the tutorials.
    They are detailed, explained properly, to the point.

    Keep it up

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares