Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create an Android user login system using MySQL

In this article we will see how to create an Android application user login system, which gets authenticated on the server, by calling a PHP scripts that queries to MySQL database.

You may have seen different android applications that have the login functionality, and registration. These applications, basically use the database on online server. The user inputs his username and password (in case of login) and presses the login button. The android application calls a URL: http://www.example.com/login.php. On calling the URL , a PHP script runs, that receives the data that has been sent from the android app, with the method called POST(it can also be GET, but login, and registration where we care about data we use the POST method).

After that PHP script runs query to the database and compares the username and password with already existed username and password in the database. If the result is true, it will output its data with a value of true in json format. Json stands for JavaScript object notation, which is format of data, used to send and retrieve data on the internet.

Once the returned data is true, the user application will then move to the next activity that is to be shown to the user. In case the user login information is invalid we may print a message to the user that the data is invalid.

Content of the article:

  • Creation of database
  • Writing PHP script for server side validation.
  • Android login.java class.
  • Android JASONParser.java
  • Android login.xml
  • Android manifest.xml
  • Creating hello world mainActivity.java


Creation of database:

To create a database online, we will use 000webhost.com, where we will need to create an account. There we need to do two tasks.

Making PHP Script:

We will need to place a login file in the public-html directory. For now the file will be empty. We will discuss that in upcoming portion of the article.

Creating database:

Secondly we need to create a database, once we are in the cpanel. We can simply click on the Phpmyadmin section and create a database with any name.

After creating a database, we will also need to create our first database table with name of login.

The login table must contain the following fields.

  • ID: int (11) auto incremented
  • Username :varchar(255)
  • Password:varchar(255)

Now you will need to collect, the servername, the database name, the password, username, that you have used for making the account. These fields will be required for making the PHP script that will be used for login.php

Writing PHP script for server side validation:

Now we will write a PHP script that when called by our android app, will run a query on the database on the server, validate our login information, and provide us with a Success value (of either 1 or 0 where 1 is for true and 0 is for false) and message (for invalid and successfully login notification).

The data that user will input in the edittextfields of our android app will be received at php script in the form of method called, POST. That can be seen in the code below.

Now once the PHP script is written, our file path would be www.yourdomain.com/login.php. Keep this in mind, the same URL will be used in the login.java class for validation at the server side by sending the username and password.

Listing 1: login.php


<?php
  mysql_connect("mysql8.000webhost.com","a5224389_elift","trustingeeks.com");
  $db= mysql_select_db("a5224389_elift");
  $password=$_POST["password"];
  $username=$_POST["username"];
   
  if (!empty($_POST)) {
  if (empty($_POST['username']) || empty($_POST['password'])) {
  // Create some data that will be the JSON response 
          $response["success"] = 0;
          $response["message"] = "One or both of the fields are empty .";
          
          //die is used to kill the page, will not let the code below to be executed. It will also
          //display the parameter, that is the json data which our android application will parse to be //shown to the users
          die(json_encode($response));
      }
  $query = " SELECT * FROM login WHERE username = '$username'and password='$password'";
      
     $sql1=mysql_query($query);
  $row = mysql_fetch_array($sql1);
  if (!empty($row)) {
       $response["success"] = 1;
          $response["message"] = "You have been sucessfully login";
         die(json_encode($response));
  }
  else{
   
  $response["success"] = 0;
          $response["message"] = "invalid username or password ";
  die(json_encode($response));
  }
      
   
   
  }
  else{
   
  $response["success"] = 0;
          $response["message"] = " One or both of the fields are empty ";
  die(json_encode($response));
  }
   
  mysql_close();
  ?>

Lets look at the first few lines of the code that are used for making connection to the database, mysql_connect("mysql8.000webhost.com","a5224389_elift","trustingeeks.com"); $db= mysql_select_db("a5224389_elift"); mysql_connect() function takes three arguments, where first argument is hostname, second argument is username and the third argument is password.

Then we use mysql_select_db() and pass one argument, which is the name of the database, that we created at 000webhost.com.

The next few lines of code, will receive the data with post method, and store the data in some appropriate variables.

$password=$_POST["password"];

$username=$_POST["username"];

Now we use if and else statement for validation. Basically we use one if and else, within, if clause we use nested if and else clauses, lets first have a look at only if and nested if else clauses that we have used , which can be seen in the code, below!

We start by checking either the $_POST method have received, some values, that means the user need to input some values in the field such as username, and password. So to check we make use of the empty() function in PHP , that will return true is the $_post is empty, but we need it to have some values, so buy putting the negation, sign, the script inside the if() clause will if the $_POST method is not empty!

if (!empty($_POST)) {

Once that is checked, we need to check, both username, and password field to have some values. So the following line code is used. If any of the field is empty the script will jump to else, and if both the fields are empty! The script inside if clause will run! That will kill the page, and send the response to the android application, with the message, that one or both of the fields are empty!

if (empty($_POST['username']) || empty($_POST['password'])) {

// Create some data that will be the JSON response

$response["success"] = 0;

$response["message"] = "One or both of the fields are empty! .";

//die is used to kill the page, will not let the code below to be executed. It will also

//display the parameter, that is the json data which our android application will parse to be //shown to the users

die(json_encode($response));

}

Now if the data inputted is present in both the fields, the query will be run! And compared with username and password in the database fields.

$query = " SELECT * FROM login WHERE username = '$username'and password='$password'";

$sql1=mysql_query($query);

$sql1 contains the result from the mysql query that is $query.

$row = mysql_fetch_array($sql1);

The data is fetched as row, using mysql_fetch_array() functon.

if (!empty($row)) {

If the $row is not empty we have the result, this means the values are correct for the field of username and password. There for $response[“success”] takes values of 1. With a message of successfully log in!

$response["success"] = 1;

$response["message"] = "You have been successfully logged";

die(json_encode($response));

}

In case we have no data from the query we need to inform the user that either the password or the username is incorrect.

else{

$response["success"] = 0;

$response["message"] = "invalid username or password ";

die(json_encode($response));

}

}


This file must be placed in the public_html direcotry of the file manger at the hosting server! Now let’s create our login.java and login.xml files in our android project.

Android login.java :

The login.java,class main functionality is that, it will be our main activity , as mentioned in the manifest.xml file can be seen below. Here we will fill our two values: username and password. And then click on the login button. As soon we click on the login button, our android application will call the method from the inner class called AttemptLogin that extends AsyncTask .

Now you may have the question in your mind, what is AsyncTask , Why do we need this?

Asynctask is a class that is used for long running process from few 100 milliseconds to few seconds. These tasks may include connection to the database, login, etc.

Asynctask is used, in order to take load out of the main thread on which our application is running, before the current version of android we could directly use the main activity thread to connect to the server, and perform simple small few seconds task. But from the recent updates of android it has been made compulsory to use Asynctask for tasks that are long running.

What happens if we do not use Asynctask here?

Our application without aynctask will freeze for some time until the task is not completed, that means we will be notified by ANR.

You can find more information about asynctask and service at www.developer.android.com

For task that may take more time we can make use of Services in android.

Listing 2: login.java


package com.mrbool.app;
  import java.util.ArrayList;
  import java.util.List;
  import org.apache.http.NameValuePair;
  import org.apache.http.message.BasicNameValuePair;
  import org.json.JSONException;
  import org.json.JSONObject; 
  import android.app.Activity;
  import android.app.ProgressDialog;
  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.Toast; 
  public class Login extends Activity implements OnClickListener{
         private EditText user, pass;
        private Button bLogin, 
          // Progress Dialog
      private ProgressDialog pDialog;
       // JSON parser class
      JSONParser jsonParser = new JSONParser();
      private static final String LOGIN_URL = "http://yourdomain.com/login.php";
      private static final String TAG_SUCCESS = "success";
      private static final String TAG_MESSAGE = "message";
         @Override
        protected void onCreate(Bundle savedInstanceState) {       
              super.onCreate(savedInstanceState);
              setContentView(R.layout.login);      
              user = (EditText)findViewById(R.id.username);
              pass = (EditText)findViewById(R.id.password);          
              bLogin = (Button)findViewById(R.id.login);
              bLogin.setOnClickListener(this);
                    }
   
        @Override
        public void onClick(View v) {
              // TODO Auto-generated method stub
              switch (v.getId()) {
              case R.id.login:
                          new AttemptLogin().execute();
              // here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case.
              default:
                    break;
              }
        }
   
        class AttemptLogin extends AsyncTask<String, String, String> {
               /**
           * Before starting background thread Show Progress Dialog
           * */
              boolean failure = false;
   
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              pDialog = new ProgressDialog(Login.this);
              pDialog.setMessage("Attempting for login...");
              pDialog.setIndeterminate(false);
              pDialog.setCancelable(true);
              pDialog.show();
          }
   
              @Override
              protected String doInBackground(String... args) {
                    // TODO Auto-generated method stub
                     // here Check for success tag
              int success;
              String username = user.getText().toString();
              String password = pass.getText().toString();
              try {
                  
                  List<NameValuePair> params = new ArrayList<NameValuePair>();
                  params.add(new BasicNameValuePair("username", username));
                  params.add(new BasicNameValuePair("password", password));
   
                  Log.d("request!", "starting");
                  
                  JSONObject json = jsonParser.makeHttpRequest(
                         LOGIN_URL, "POST", params);
   
                  // checking  log for json response
                  Log.d("Login attempt", json.toString());
   
                  // success tag for json
                  success = json.getInt(TAG_SUCCESS);
                  if (success == 1) {
                    Log.d("Successfully Login!", json.toString());
                  
                    Intent ii = new Intent(Login.this,OtherActivty.class);
                    finish();
  // this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
                          startActivity(ii);
                    return json.getString(TAG_MESSAGE);
                  }else{
                    
                    return json.getString(TAG_MESSAGE);
   
                  }
              } catch (JSONException e) {
                  e.printStackTrace();
              }
   
              return null;
              }
              /**
           * Once the background process is done we need to  Dismiss the progress dialog asap
           * **/
          protected void onPostExecute(String message) {
             
              pDialog.dismiss();
              if (message != null){
                    Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();
              }
          }
        } 
  }
  

In the above code, we declare, two edit text fields, and on button, with an object of JSONParser class. The login.java class extends activity class with an implementation to OnClickListener interface, which will be triggered when onclickbutton event occurs.

Besides this we make use of inner class AttempLogin that extends AsyncTask class. That is used to uplift the load from the main thread of android application.

class AttemptLogin extends AsyncTask<String, String, String>

It basically has three functions!

  • protected String doInBackground(String... args)
  • protected void onPostExecute(String message)
  • protected void onPreExecute()


We also use the ProgressDialog pDialogthat keeps the user informed about the activity.

You might have noticed, one thing here that we are using is the class JSONParser.

JSONObject json = jsonParser.makeHttpRequest(

LOGIN_URL, "POST", params);


Through this, we call the method (makehttpRequest), of JSONObject, make request, and post the data to the server, and get the response back in json format, that is then parsed and utilized by the notification, in the form of toast.

Listing 3: JSONParser.java

package com.mrbool.app;
  import org.apache.http.HttpEntity;
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStream;
  import org.apache.http.HttpResponse;
  import java.io.InputStreamReader;
  import java.io.UnsupportedEncodingException;
  import java.util.List;
  import org.apache.http.NameValuePair;
  import org.apache.http.client.ClientProtocolException;
  import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.HttpGet;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.client.utils.URLEncodedUtils;
  import org.apache.http.impl.client.DefaultHttpClient;
  import org.json.JSONException;
  import org.json.JSONObject;
  import android.util.Log;
  public class JSONParser {
        static InputStream is = null;
      static JSONObject jsonObj ;
      static String json = "";
   
      // default no argument constructor for jsonpaser class
      public JSONParser() {
   
      }
      
      
      public JSONObject getJSONFromUrl(final String url) {
   
          // Making HTTP request
          try {
              
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost httpPost = new HttpPost(url);
   
              // Executing POST request & storing the response from server  locally.
              HttpResponse httpResponse = httpClient.execute(httpPost);
              
  HttpEntity httpEntity = httpResponse.getEntity();
              
              is = httpEntity.getContent();
   
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
   
          try {
              
              
              // Create a BufferedReader
           BufferedReader reader = new BufferedReader(new InputStreamReader(
                      is, "iso-8859-1"), 8);
              // Declaring string builder 
              StringBuilder str = new StringBuilder();
              //  string to store the JSON object.
              String strLine = null;
              
              // Building while we have string !equal null.
              while ((strLine = reader.readLine()) != null) {
                  str.append(strLine + "\n");
              }
              
              // Close inputstream.
              is.close();
              // string builder data conversion  to string.
              json = str.toString();
          } catch (Exception e) {
              Log.e("Error", " something wrong with converting result " + e.toString());
          }
   
          // Try block used for pasrseing String to a json object
          try {
              jsonObj = new JSONObject(json);
          } catch (JSONException e) {
              Log.e("json Parsering", "" + e.toString());
          }
   
          // Returning json Object.
          return jsonObj;
   
      }
      
   
      
      public JSONObject makeHttpRequest(String url, String method,
              List<NameValuePair> params) {
   
          // Make HTTP request
          try {
   
              // checking request method
              if(method == "POST"){
                 
                  // now defaultHttpClient object
                  DefaultHttpClient httpClient = new DefaultHttpClient();
                  HttpPost httpPost = new HttpPost(url);
                  httpPost.setEntity(new UrlEncodedFormEntity(params));
   
                  HttpResponse httpResponse = httpClient.execute(httpPost);
                  HttpEntity httpEntity = httpResponse.getEntity();
                  is = httpEntity.getContent();
   
              }else if(method == "GET"){
                  // request method is GET
                  DefaultHttpClient httpClient = new DefaultHttpClient();
                  String paramString = URLEncodedUtils.format(params, "utf-8");
                  url += "?" + paramString;
                  HttpGet httpGet = new HttpGet(url);
   
                  HttpResponse httpResponse = httpClient.execute(httpGet);
                  HttpEntity httpEntity = httpResponse.getEntity();
                  is = httpEntity.getContent();
              }           
   
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
   
          try {
              BufferedReader reader = new BufferedReader(new InputStreamReader(
                      is, "iso-8859-1"), 8);
              StringBuilder str = new StringBuilder();
              String strLine = null;
              while ((strLine = reader.readLine()) != null) {
                  str.append(strLine + "\n");
              }
              is.close();
              json = str.toString();
          } catch (Exception e) {
             
        }
   
          // now will try to parse the string into JSON object
          try {
              jsonObj = new JSONObject(json);
          } catch (JSONException e) {
             
    }
   
      
          return jsonObj;
   
      }
   
  }
  

The JASONParser class is used by login.java class in order to make HTTP request to the server, calling a PHP script, and then collecting back the data in json format. The json format contains success tag, value and message. That can be seen in the login.php file above.

JSONParser class has methods, that is called, from the login.java class in the following line of codes:


JSONObject json = jsonParser.makeHttpRequest(

LOGIN_URL, "POST", params);


makeHttpRequest() method is the only method, that we use, it takes three parameters, the URL, where the PHP script file lies, and the method name such as POST and GET , Where as Third parameter is used to pass any array that we may want to send to the server.

Once the method is called, we simply use if and else to check the method type for our case we use POST as method of sending data, therefore the following line of code will be executed!

if(method == "POST"){
  // now defaultHttpClient object
                  DefaultHttpClient httpClient = new DefaultHttpClient();
                  HttpPost httpPost = new HttpPost(url);
                  httpPost.setEntity(new UrlEncodedFormEntity(params));
                  HttpResponse httpResponse = httpClient.execute(httpPost);
  HttpEntity httpEntity = httpResponse.getEntity();
                  is = httpEntity.getContent();
              }

Here, we make DefaultHttpClient and HttpPost objects, then call to setEntity() method that takes an object as argument which in itself takes an array of parameters as arguments.

login.xml

Now that we also have our JSON class ready, let's also mention, our xml file for login that contains two edittext fields and one button for login. The layout is relative, you can instead use any layout that has no impact on our code. You can also place nice icons for buttons, imageview for the login information, and much more can be done to make it look nice and attractive.

Listing 4: login.xml


<?xml version="1.0" encoding="utf-8"?>
  <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="wrap_content"
     
      android:orientation="vertical" >
   
      <Button
          android:id="@+id/login"
          android:layout_width="118dp"
          android:layout_height="wrap_content"
          android:layout_alignLeft="@+id/password"
          android:layout_alignRight="@+id/password"
          android:layout_below="@+id/password"
          android:text="login" />
   
      <EditText
          android:id="@+id/username"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignLeft="@+id/password"
      
          android:ems="10"
          android:focusable="true"
          android:hint="Enter username"
          android:imeOptions="actionNext"
          />
   
      <EditText
          android:id="@+id/password"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/username"
          android:layout_centerHorizontal="true"
          android:ems="10"
          android:hint="Enter Password"
          android:imeOptions="actionDone"
          />
   
  </RelativeLayout>

Login.xml Graphical representation:

Here is simple snapshot of the application, to give you some idea how it should look like.

Figure 1: Application Snapshot

After making the login.xml , we now only need to mention the manifest file. Please note down we need internet connection either mobile internet, or wifi. If any one of them will be available, then only we can run and test our application. To use this we also need to add permission to our manifest.xml file.

manifest.xml :

The manifest file contains all the information about the android application, that includes, permissions used by the android application, number of activities used, services used, and much more advanced concept may need to be mentioned, here. You only need to remember for now that the information of the android application is contained in the manifest file. Let's know show you the code for manifest.xml code for our android login application using MySQL database.

Listing 5: manifest.xml


<?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android=" http://schemas.android.com/apk/res/android"
      package="com.mrbool.app"
      android:versionCode="1"
      android:versionName="1.0" >
   
      <uses- sdk
          android:minSdkVersion=""
          android:targetSdkVersion="18" />
      
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.INTERNET" />
  

      <!-- Required OpenGL ES 2.0. for Maps V2 -->
      <uses-feature
          android:glEsVersion="0x00020000"
          android:required="true" />


      <application
          android:allowBackup="true"   
       android:label="@string/app_name"
          android:theme="@style/AppTheme" >
          <activity
              android:name="com.mrbool.app.Login"
              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="com.mrbool.app.Otheractivity"
              android:label="@string/app_name" >         
  </intent-filter>
          </activity>
      </application>
  </manifest>


Creating hello world OtherActivity.java

This is a simply an empty activity that does not need any sort of coding. We just only need to include this to the manifest file. This is used, when we are successfully logged in , it will take us to the other activity behaving as if it is our main application activity that should not be accessed by unauthorized users.

Listing 6: OtherActivity.java

package com.mrbool.app;
  import android.os.Bundle;
  import android.app.Activity;
  import android.view.Menu;
  public class OtherActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_other);
        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.other, menu);
              return true;
        }
   
  }
  


Listing 7: activity_other.xml


<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:paddingBottom="@dimen/activity_vertical_margin"
      android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      tools:context=".OtherActivity" >
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/hello_world" />
  </RelativeLayout>

Figure 2: Graphical representation of activity_ other.xml


Now you just only need to run the application, and it should be working fine, so you have created your first login application android application using MySQL database. Similarly you can create any sort of application that may use online, server and database. For further information, you need to learn about web services, that makes things easier and provide you different functionalities by just calling to a specific URL. In the same fashion, as we have called, our PHP script, and it has run the query on the database, and provide us information, weather the user data is valid or invalid.

An example of Web services can be thought of as: suppose we want to make a weather application, the data about weathers can be retrieved by using specific services, and calling a URL, and retrieving and displaying that data , is merely our work, behind the scene what is happening we have nothing to do with that!

Hope you people have learned something useful from the article.



computer science Graduate :Ceo at www.gigsclerk.com (Best Marketplace to Buy and sell service online from 2$-100$ ) and www.trustingeeks.com. Interested in programming, online buissiness. Android development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login