Beruflich Dokumente
Kultur Dokumente
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.
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.
<?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;
if (mysqli_connect_errno($this->connect)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
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";
mysqli_close($this->db->getDb());
return true;
mysqli_close($this->db->getDb());
return false;
if($inserted == 1){
$json['success'] = 1;
}else{
$json['success'] = 0;
mysqli_close($this->db->getDb());
Page | 4
return $json;
$json = array();
if($canUserLogin){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
return $json;
}
}
?>
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 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'];
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($username,
$hashed_password, $email);
echo json_encode($json_registration);
// User Login
$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
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="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="title_activity_register">RegisterActivity</string>
<string name="welcome">WELCOME</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" >
<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>
</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.
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;
@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);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
enteredUsername = username.getText().toString();
if(enteredUsername.equals("") || enteredPassword.equals("")){
return; }
if(enteredUsername.length() <= 1 || enteredPassword.length() <= 1){
return;
P a g e | 16
}
});
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
startActivity(intent); } });
}
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
@Override
// Handle action bar item clicks here. The action bar will
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
P a g e | 17
return super.onOptionsItemSelected(item);
@Override
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
P a g e | 18
return jsonResult;
@Override
super.onPreExecute();
@Override
super.onPostExecute(result);
return;
if(jsonResult == 0){
return;
if(jsonResult == 1){
intent.putExtra("USERNAME", enteredUsername);
P a g e | 19
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
try {
answer.append(rLine);
} catch (IOException e) {
e.printStackTrace();
return answer;
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.
<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>
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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
P a g e | 23
Intent intent = getIntent();
loggedUser = capitalizeFirstCharacter(loggedUser);
loginUsername.setText(loggedUser);
successMessage.setText(message);
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
@Override
// Handle action bar item clicks here. The action bar will
int id = item.getItemId();
//noinspection SimplifiableIfStatement
P a g e | 24
if (id == R.id.action_settings) {
return true;
return super.onOptionsItemSelected(item);
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;
P a g e | 30
private final String serverUrl = "path to your server";
@Override
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);
signUpButton.setOnClickListener(new View.OnClickListener() {
@Override
enteredUsername = username.getText().toString();
if(enteredUsername.equals("") || enteredPassword.equals("") ||
enteredEmail.equals("")){
return;
return;
P a g e | 31
}
});
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_register, menu);
return true;
@Override
// Handle action bar item clicks here. The action bar will
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
P a g e | 32
}
return super.onOptionsItemSelected(item);
@Override
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
P a g e | 33
} catch (IOException e) {
e.printStackTrace();
return jsonResult;
@Override
super.onPreExecute();
@Override
super.onPostExecute(result);
return;
if(jsonResult == 0){
return;
P a g e | 34
if(jsonResult == 1){
intent.putExtra("USERNAME", enteredUsername);
startActivity(intent);
try {
answer.append(rLine);
} catch (IOException e) {
e.printStackTrace();
return answer;
P a g e | 35
JSONObject resultObject = null;
int returnedResult = 0;
try {
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.
P a g e | 36
Android Login and Registration Php Code 2.02 KB
P a g e | 37