Sie sind auf Seite 1von 37

ANDROID LOGIN AND REGISTRATION WITH PHP AND MYSQL

In this android tutorial we are going to learn how to implement android login and
registration with Php and Mysql database. This is going to be a long tutorial and
will involve Php and Mysql.

If you do not know much about Php and Mysql, kindly read it up w3school.com.
Before we start with the detailed instruction, it is important to know that we will
first of all download and install a web server in our system. I am going to use
WAMP server but feel free to use whatever web server you are familiar with.

The detail instruction on how to install WAMP can be found on their website.

With the web server installed, start your web server and go to PhpMyAdmin. We
will create a new database called androidlogin. In our created database, we will
create a single table called users. The below script is used to create our users
table.

CREATE TABLE IF NOT EXISTS 'users' (


'id' int(20) NOT NULL AUTO_INCREMENT,
'username' varchar(70) NOT NULL,
'password' varchar(40) NOT NULL,
'email' varchar(50) NOT NULL,
'created_at' datetime NOT NULL,
'updated_at' datetime DEFAULT NULL,
PRIMARY KEY ('id'),
UNIQUE KEY 'email' ('email')
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

The next step is to create our Php project structure. I will make use of Aptana for
Php and Mysql development but feel free to use whatever IDE you like the best.

Page | 1
Create a folder called android_user_api inside the www folder of your web server.
Inside this folder, create another folder called include. The include folder will
house our configuration file for database connection.

Create a file called index.php in your project root directory. All the request that
will hit our server will go through this index file.

In our include folder, create three files called config.php, db.php and user.php.

The image below illustrate how our Php application structure will look like.

What the web app will do?


1. Send and accept GET/ POST request.
2. With request parameters, the database will be queried for insertion or
retrieval of data.
3. All response data will be returned in JSON format.
The server response will be in Json format. If you have not done anything like
parsing Json in android I will suggest you first read my post on How to Parse
JSON in Android Example.
Open the Php database config file called config.php and paste the following code
on it.

<?php
define("DB_HOST", "localhost");
define("DB_USER", "android");
define("DB_PASSWORD", "android");
define("DB_NAME", "androidlogin");
?>

This is the database connection details. Please make sure you change this
information in accordance with your database server. In the code above we are
just defining the database connection properties.

Page | 2
With this in place, we will establish a database connection with our Php
application. This is done in the db.php file. Open the file and paste the following
code below.

<?php

include_once 'config.php';

class DbConnect{

private $connect;

public function __construct(){

$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,


DB_NAME);

if (mysqli_connect_errno($this->connect)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}

public function getDb(){


return $this->connect;
}
}
?>

The config file was included in the beginning of the page. The getDB function
returns an instance of our database connection.

Now that we have our database connection, create a user.php file that will
contain the login and user registration code. This file will include the db.php file.
Copy and paste the following code in the file.

<?php

include_once 'db.php';

class User{

private $db;

Page | 3
private $db_table = "users";

public function __construct(){


$this->db = new DbConnect();
}

public function isLoginExist($username, $password){

$query = "select * from " . $this->db_table . " where username = '$username'


AND password = '$password' Limit 1";

$result = mysqli_query($this->db->getDb(), $query);

if(mysqli_num_rows($result) > 0){

mysqli_close($this->db->getDb());

return true;

mysqli_close($this->db->getDb());

return false;

public function createNewRegisterUser($username, $password, $email){

$query = "insert into users (username, password, email, created_at, updated_at)


values ('$username', '$password', '$email', NOW(), NOW())";

$inserted = mysqli_query($this->db->getDb(), $query);

if($inserted == 1){

$json['success'] = 1;

}else{

$json['success'] = 0;

mysqli_close($this->db->getDb());

Page | 4
return $json;

public function loginUsers($username, $password){

$json = array();

$canUserLogin = $this->isLoginExist($username, $password);

if($canUserLogin){

$json['success'] = 1;

}else{
$json['success'] = 0;
}
return $json;
}
}
?>

The loginUsers and createNewRegisterUser functions of this class are responsible


for authenticating user log in and registration. With our include files done, we will
move ahead to our index.php file.

As said before, all request to our server will hit on this file. We will check and get
the data append to the query string. If we only get the username and password,
we will assume that the user wants to login otherwise the user wants to register a
new account.

The user.php is included in the index.php. The loginUsers and


createNewRegisterUser functions are called depending on what the user is
intending to do.

The returned code is the converted to Json object and echo out. The code for the
index.php file is shown below.

<?php

require_once 'include/user.php';

$username = "";

Page | 5
$password = "";

$email = "";

if(isset($_POST['username'])){

$username = $_POST['username'];

if(isset($_POST['password'])){

$password = $_POST['password'];

if(isset($_POST['email'])){

$email = $_POST['email'];

// Instance of a User class

$userObject = new User();

// Registration of new user

if(!empty($username) && !empty($password) && !empty($email)){

$hashed_password = md5($password);

$json_registration = $userObject->createNewRegisterUser($username,
$hashed_password, $email);

echo json_encode($json_registration);

// User Login

if(!empty($username) && !empty($password) && empty($email)){

$hashed_password = md5($password);

Page | 6
$json_array = $userObject->loginUsers($username, $hashed_password);

echo json_encode($json_array);
}
?>

The responses Json object is very simple. If the user was able to login or register
a new account, the following Json code will be returned {success:1} otherwise
this will be returned {success:0}

With the web application completed, we will move over to create our android
application.

In order to parse JSON object from a remote server source, we are going to need
internet access for our application.

It is important to note that when you are working with internet or accessing data
from a remote source in android, you will need to add internet permission in your
android manifest file.

<uses-permission android:name="android.permission.INTERNET"/>

We are going to use android API for HTTP request. Once we get the Json output as
an InputStream, we will convert it to a string. The string object will be pass as a
parameter to an instance of JsonObject class.

We will also use an AsyncTask class to make server calls in a background Thread.
This is important so that will not end up blocking the main UI Thread.

Before we start, the first thing I will do is to list the environment and tools I used
in this android tutorial but feel free to use whatever environment or tools you are
familiar with.

Windows 7
Android Studio
Samsung Galaxy Fame Lite
Min SDK 14
Target SDK 19
To create a new android application project, following the steps as stipulated
below.

Go to File menu
Page | 7
Click on New menu
Click on Android Application
Enter Project name: AndroidLoginAndRegistration
Package: com.inducesmile.androidloginandregistration
Keep other default selections.
Continue to click on next button until Finish button is active, then click
on Finish Button
Once you are done with creating your project, make sure you change the
package name if you did not use the same package.

MAIN LAYOUT

We will start by adding an TextView, EditText and Button controls in our


activity_main.xml layout file. If you are using Eclipse or Android Studio, you can
switch to the design view and drag and drop this Views inside your layout file.

You can also copy and paste the following code below into this file if you dont
want to do it yourself.

<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"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

android:background="#08253c"

tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

Page | 8
android:text="@string/username"

android:id="@+id/username"

android:textColor="#ffffff"

android:textSize="16sp"

android:layout_marginTop="20dp"

android:layout_marginLeft="10dp"

android:layout_marginStart="10dp"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginRight="20dp"

android:layout_marginEnd="20dp"

android:id="@+id/username_field"

android:layout_below="@+id/username"

android:layout_alignLeft="@+id/username"

android:background="#ffffff"

android:layout_alignStart="@+id/username" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/password"

Page | 9
android:id="@+id/password"

android:textColor="#ffffff"

android:textSize="16sp"

android:layout_below="@+id/username_field"

android:layout_alignLeft="@+id/username_field"

android:layout_alignStart="@+id/username_field"

android:layout_marginTop="30dp" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="textPassword"

android:ems="10"

android:id="@+id/password_field"

android:layout_marginRight="20dp"

android:layout_marginEnd="20dp"

android:background="#ffffff"

android:layout_below="@+id/password"

android:layout_alignLeft="@+id/password"

android:layout_alignStart="@+id/password" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/login"

P a g e | 10
android:id="@+id/login"

android:layout_below="@+id/password_field"

android:layout_centerHorizontal="true"

android:layout_marginTop="52dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/registration_instruction"

android:layout_marginTop="20dp"

android:layout_marginRight="10dp"

android:layout_marginEnd="10dp"

android:textSize="16sp"

android:textColor="#ffffff"

android:id="@+id/textView"

android:layout_below="@+id/login"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/register_button"

android:id="@+id/register_button"

android:layout_below="@+id/textView"

P a g e | 11
android:layout_centerHorizontal="true"

android:layout_marginTop="42dp" />

</RelativeLayout>

The text content of our View components are stored in the strings.xml file. The
contain of the file is shown below

<resources>

<string name="app_name">AndroidLoginAndRegistration</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

<string name="username">Username</string>

<string name="password">Password</string>

<string name="email">Email</string>

<string name="login">Login</string>

<string name="title_activity_login">LoginActivity</string>

<string name="registration_instruction">I do not have a username and


password details. Click the button below to register</string>

<string name="register_button">Register Now</string>

<string name="title_activity_register">RegisterActivity</string>

<string name="welcome">WELCOME</string>

<string name="is_login">You have been successfully login </string>

<string name="sign_up">Sign Up Now</string>

</resources>

Since we made a single line of change in our Manifest.xml file, the complete code
is shown below
P a g e | 12
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="inducesmile.com.androidloginandregistration" >

<uses-permission android:name="android.permission.INTERNET" />

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity

android:name=".LoginActivity"

android:label="@string/title_activity_login" >

</activity>

<activity

android:name=".RegisterActivity"

P a g e | 13
android:label="@string/title_activity_register" >

</activity>

</application>

</manifest>

MAINACTIVITY.JAVA
In our MainActivity.java file, the instances of our Button and EditText controls
were obtained. User validation is implemented to make sure that user add the
expected data in the edit fields.

An AsyncTask inner class was used for server communication. The request and
response to the server happens in the doInBackground method of the AsyncTask
class and the response result is returned to the onPostExecute method.

The code for the MainActivity.java is shown below.

package inducesmile.com.androidloginandregistration;

import android.content.Intent;

import android.os.AsyncTask;

import android.os.Bundle;

import android.support.v7.app.ActionBarActivity;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

P a g e | 14
import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.params.BasicHttpParams;

import org.apache.http.params.HttpConnectionParams;

import org.apache.http.params.HttpParams;

import org.json.JSONException;

import org.json.JSONObject;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

public class MainActivity extends ActionBarActivity {

protected EditText username;

private EditText password;

protected String enteredUsername;

private final String serverUrl = "path to your server";

@Override

P a g e | 15
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

username = (EditText)findViewById(R.id.username_field);

password = (EditText)findViewById(R.id.password_field);

Button loginButton = (Button)findViewById(R.id.login);

Button registerButton = (Button)findViewById(R.id.register_button);

loginButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

enteredUsername = username.getText().toString();

String enteredPassword = password.getText().toString();

if(enteredUsername.equals("") || enteredPassword.equals("")){

Toast.makeText(MainActivity.this, "Username or password must be filled",


Toast.LENGTH_LONG).show();

return; }
if(enteredUsername.length() <= 1 || enteredPassword.length() <= 1){

Toast.makeText(MainActivity.this, "Username or password length must be greater


than one", Toast.LENGTH_LONG).show();

return;

// request authentication with remote server4

AsyncDataClass asyncRequestObject = new AsyncDataClass();

asyncRequestObject.execute(serverUrl, enteredUsername, enteredPassword);

P a g e | 16
}

});

registerButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Intent intent = new Intent(MainActivity.this, RegisterActivity.class);

startActivity(intent); } });
}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

P a g e | 17
return super.onOptionsItemSelected(item);

private class AsyncDataClass extends AsyncTask<String, Void, String> {

@Override

protected String doInBackground(String... params) {

HttpParams httpParameters = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);

HttpConnectionParams.setSoTimeout(httpParameters, 5000);

HttpClient httpClient = new DefaultHttpClient(httpParameters);

HttpPost httpPost = new HttpPost(params[0]);

String jsonResult = "";

try {

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

nameValuePairs.add(new BasicNameValuePair("username", params[1]));

nameValuePairs.add(new BasicNameValuePair("password", params[2]));

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpClient.execute(httpPost);

jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

P a g e | 18
return jsonResult;

@Override

protected void onPreExecute() {

super.onPreExecute();

@Override

protected void onPostExecute(String result) {

super.onPostExecute(result);

System.out.println("Resulted Value: " + result);

if(result.equals("") || result == null){

Toast.makeText(MainActivity.this, "Server connection failed",


Toast.LENGTH_LONG).show();

return;

int jsonResult = returnParsedJsonObject(result);

if(jsonResult == 0){

Toast.makeText(MainActivity.this, "Invalid username or password",


Toast.LENGTH_LONG).show();

return;

if(jsonResult == 1){

Intent intent = new Intent(MainActivity.this, LoginActivity.class);

intent.putExtra("USERNAME", enteredUsername);

P a g e | 19
intent.putExtra("MESSAGE", "You have been successfully login");

startActivity(intent);

private StringBuilder inputStreamToString(InputStream is) {

String rLine = "";

StringBuilder answer = new StringBuilder();

BufferedReader br = new BufferedReader(new InputStreamReader(is));

try {

while ((rLine = br.readLine()) != null) {

answer.append(rLine);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return answer;

private int returnParsedJsonObject(String result){

JSONObject resultObject = null;

int returnedResult = 0;

try {

P a g e | 20
resultObject = new JSONObject(result);

returnedResult = resultObject.getInt("success");

} catch (JSONException e) {

e.printStackTrace();

return returnedResult;

If the server response is successful, the user is automatically log into the
application otherwise the user will be notify of an error through android Toast.
The landing page for user login and registration is LoginActivity.java. The user is
redirected to this pass with the username stored in android bundle.

The layout for the activity_login.xml is shown below

<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"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

android:background="#08253c"

tools:context="inducesmile.com.androidloginandregistration.LoginActivity">

P a g e | 21
<TextView

android:id="@+id/welcome"

android:text="@string/welcome"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textColor="#f0c80c"

android:textSize="30sp"

android:textStyle="bold"

android:layout_marginTop="157dp"/>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/username"

android:id="@+id/login_user"

android:textColor="#ffffff"

android:textSize="40sp"

android:textStyle="bold"

android:layout_below="@+id/welcome"

android:layout_centerHorizontal="true"

android:layout_marginTop="25dp" />

<TextView

P a g e | 22
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/is_login"

android:id="@+id/message"

android:textColor="#ffffff"

android:layout_marginTop="44dp"

android:layout_below="@+id/login_user"

android:layout_centerHorizontal="true" />

</RelativeLayout>

In LoginActivity.java, the stored data in android bundle is retrieved and it is


appended to TextView controls. The code for LoginActivity.java is shown below.

package inducesmile.com.androidloginandregistration;

import android.content.Intent;

import android.os.Bundle;

import android.support.v7.app.ActionBarActivity;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.TextView;

public class LoginActivity extends ActionBarActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_login);

P a g e | 23
Intent intent = getIntent();

Bundle intentBundle = intent.getExtras();

String loggedUser = intentBundle.getString("USERNAME");

loggedUser = capitalizeFirstCharacter(loggedUser);

String message = intentBundle.getString("MESSAGE");

TextView loginUsername = (TextView)findViewById(R.id.login_user);

TextView successMessage = (TextView)findViewById(R.id.message);

loginUsername.setText(loggedUser);

successMessage.setText(message);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_login, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

P a g e | 24
if (id == R.id.action_settings) {

return true;

return super.onOptionsItemSelected(item);

private String capitalizeFirstCharacter(String textInput){

String input = textInput.toLowerCase();

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

return output;

activity_register.xml
I will not explain much about RegisterActivity.java since it is similar to the
MainActivty.java. The layout and code are shown below

<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"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

android:background="#08253c"

P a g e | 25
tools:context="inducesmile.com.androidloginandregistration.RegisterActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/username"

android:id="@+id/username"

android:textColor="#ffffff"

android:textSize="16sp"

android:layout_marginTop="20dp"

android:layout_marginLeft="10dp"

android:layout_marginStart="10dp"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginRight="20dp"

android:layout_marginEnd="20dp"

android:id="@+id/username_field"

android:layout_below="@+id/username"

android:layout_alignLeft="@+id/username"

android:background="#ffffff"

android:layout_alignStart="@+id/username" />

P a g e | 26
<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/password"

android:id="@+id/password"

android:textColor="#ffffff"

android:textSize="16sp"

android:layout_below="@+id/username_field"

android:layout_alignLeft="@+id/username_field"

android:layout_alignStart="@+id/username_field"

android:layout_marginTop="30dp" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="textPassword"

android:ems="10"

android:id="@+id/password_field"

android:layout_marginRight="20dp"

android:layout_marginEnd="20dp"

android:background="#ffffff"

android:layout_below="@+id/password"

android:layout_alignLeft="@+id/password"

android:layout_alignStart="@+id/password" />

P a g e | 27
<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/email"

android:id="@+id/textView3"

android:textColor="#ffffff"

android:textSize="16sp"

android:layout_below="@+id/password_field"

android:layout_alignLeft="@+id/password_field"

android:layout_alignStart="@+id/password_field"

android:layout_marginTop="30dp" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="textEmailAddress"

android:ems="10"

android:id="@+id/email_field"

android:layout_marginRight="20dp"

android:layout_marginEnd="20dp"

android:background="#ffffff"

android:layout_below="@+id/textView3"

android:layout_alignLeft="@+id/textView3"

android:layout_alignStart="@+id/textView3" />

P a g e | 28
<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/sign_up"

android:id="@+id/sign_up"

android:layout_below="@+id/email_field"

android:layout_centerHorizontal="true"

android:layout_marginTop="50dp" />

</RelativeLayout>

RegisterActivity.java

package inducesmile.com.androidloginandregistration;

import android.content.Intent;

import android.os.AsyncTask;

import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import org.apache.http.HttpResponse;

P a g e | 29
import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.params.BasicHttpParams;

import org.apache.http.params.HttpConnectionParams;

import org.apache.http.params.HttpParams;

import org.json.JSONException;

import org.json.JSONObject;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

public class RegisterActivity extends ActionBarActivity {

protected EditText username;

private EditText password;

private EditText email;

protected String enteredUsername;

P a g e | 30
private final String serverUrl = "path to your server";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_register);

username = (EditText)findViewById(R.id.username_field);

password = (EditText)findViewById(R.id.password_field);

email = (EditText)findViewById(R.id.email_field);

Button signUpButton = (Button)findViewById(R.id.sign_up);

signUpButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

enteredUsername = username.getText().toString();

String enteredPassword = password.getText().toString();

String enteredEmail = email.getText().toString();

if(enteredUsername.equals("") || enteredPassword.equals("") ||
enteredEmail.equals("")){

Toast.makeText(RegisterActivity.this, "Username or password or email must be


filled", Toast.LENGTH_LONG).show();

return;

if(enteredUsername.length() <= 1 || enteredPassword.length() <= 1){

Toast.makeText(RegisterActivity.this, "Username or password length must be


greater than one", Toast.LENGTH_LONG).show();

return;

P a g e | 31
}

// request authentication with remote server4

AsyncDataClass asyncRequestObject = new AsyncDataClass();

asyncRequestObject.execute(serverUrl, enteredUsername, enteredPassword,


enteredEmail);

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_register, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

P a g e | 32
}

return super.onOptionsItemSelected(item);

private class AsyncDataClass extends AsyncTask<String, Void, String> {

@Override

protected String doInBackground(String... params) {

HttpParams httpParameters = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);

HttpConnectionParams.setSoTimeout(httpParameters, 5000);

HttpClient httpClient = new DefaultHttpClient(httpParameters);

HttpPost httpPost = new HttpPost(params[0]);

String jsonResult = "";

try {

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

nameValuePairs.add(new BasicNameValuePair("username", params[1]));

nameValuePairs.add(new BasicNameValuePair("password", params[2]));

nameValuePairs.add(new BasicNameValuePair("email", params[3]));

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpClient.execute(httpPost);

jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

System.out.println("Returned Json object " + jsonResult.toString());

} catch (ClientProtocolException e) {

e.printStackTrace();

P a g e | 33
} catch (IOException e) {

e.printStackTrace();

return jsonResult;

@Override

protected void onPreExecute() {

super.onPreExecute();

@Override

protected void onPostExecute(String result) {

super.onPostExecute(result);

System.out.println("Resulted Value: " + result);

if(result.equals("") || result == null){

Toast.makeText(RegisterActivity.this, "Server connection failed",


Toast.LENGTH_LONG).show();

return;

int jsonResult = returnParsedJsonObject(result);

if(jsonResult == 0){

Toast.makeText(RegisterActivity.this, "Invalid username or password or email",


Toast.LENGTH_LONG).show();

return;

P a g e | 34
if(jsonResult == 1){

Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);

intent.putExtra("USERNAME", enteredUsername);

intent.putExtra("MESSAGE", "You have been successfully Registered");

startActivity(intent);

private StringBuilder inputStreamToString(InputStream is) {

String rLine = "";

StringBuilder answer = new StringBuilder();

BufferedReader br = new BufferedReader(new InputStreamReader(is));

try {

while ((rLine = br.readLine()) != null) {

answer.append(rLine);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return answer;

private int returnParsedJsonObject(String result){

P a g e | 35
JSONObject resultObject = null;

int returnedResult = 0;

try {

resultObject = new JSONObject(result);

returnedResult = resultObject.getInt("success");

} catch (JSONException e) {

e.printStackTrace();

return returnedResult;
}

Save the file and run your project. If everything works for you, this image will
appear on your test device.

You can download the code for this tutorial below. If you are having hard time
downloading the tutorials, kindly contact me.

Android Login and Registration Java Code 4.69 MB

P a g e | 36
Android Login and Registration Php Code 2.02 KB

P a g e | 37