Android PHP Login

When you create an Android application that requires the user's login, this tip might be useful to you. In this Android tip, I am going to show you how to create a login activity using PHP and MySQL.

To create an Android PHP Login, first you need to login to the phymyadmin and create a database called dbtest. In my machine, I have WampServer installed to work as a web server. In the database, you will create a table called tbluser that has three fields: userid, username, and password. You also need to create an account with "test" user name and "test" password. The account will be used in PHP code to connect to the dbtest database. Then run the sql statement below to insert a sample user.



INSERT INTO `tbluser`(`username`, `password`) VALUES ('admin','admin123')

After adding the sample data, create two php files. The name of the first file should be login.php and the second file is connection.php. The login.php file will be used in Java code to validate the login information.

login.php file

  <?php
include("connection.php");
$user_name=$_POST['username'];
$pwd=$_POST['password'];
$sql="SELECT userid, username, password FROM tbluser WHERE username=? AND password=?";
if ($stmt = $mysqli -> prepare($sql)){
$stmt -> bind_param("ss",$user_name,$pwd);
$stmt -> execute();
$stmt->bind_result($uid,$uname, $pwd);
while ($stmt->fetch())
{
echo $uname;
}

$stmt->close();

}

?>

connection.php file

<?php
$DB_USER='test';        
$DB_PASS='test';      
$DB_HOST='localhost';    
$DB_NAME='dbtest';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if (mysqli_connect_errno()) {
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
}


?>

These two files must be saved in the root folder of your web server. In my case, they are in D:\wamp\www.

Now our back-end setup is ready. Next, to have a workable Android application to demonstrate the PHP login, you will create a new Android project. Then modify the activity_main.xml file to add two EditTexts, one Button, and one TextView as shown below. The two EditTexts allow the user to input user name, and password. The button will be pushed to validate the login information. When there is an incorrect login, the TextView displays the message "Invalid login! Please try again." in red color.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/container"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   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=".MainActivity"
  
   >
  <EditText
     android:id="@+id/txt_user"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:hint="User Name"
     android:inputType="text"
     android:layout_marginLeft="10dp"
     android:layout_marginRight="10dp"
      />

   <EditText
     android:id="@+id/txt_pwd"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:hint="Password"
     android:inputType="textPassword"
     android:layout_marginLeft="10dp"
     android:layout_marginRight="10dp"
     />

   <Button
      android:id="@+id/btlogin"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:onClick="doLogin"
      android:layout_gravity="center"
      android:text="Log In"
      android:layout_marginLeft="10dp"
      android:layout_marginRight="10dp"
      android:textColor="#ffffff"
      />  
   <TextView
     android:id="@+id/txt_status"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:textSize="20sp"
     android:gravity="center"
     android:textColor="#ff1100"/>
</LinearLayout>


In the MainActivity class, you write code as shown below. The task to validate the user starts from the doLogin method when the user clicks the Log In button. The user validation task can take few seconds so it is a good idea to place it in the background process using AsyncTask. The progress dialog is provided so that the user will wait while the validation task is processing. In the onPreExecute method, an ProgressDialog instance is created and the dialog is shown. In the doInBackground, you will write code to execute the login.php file. In this example, I use HttpClient and HttpPost to execute the login.php file on the web server. When creating an instance of the HttpPost, you have to provide the address of the php file to be executed. Because I execute login.php in my local web server, In Emulator, the IP that points to the local sever is 10.0.2.2. In my web server, I use port 8080. Thus to execute the login.php, the address to be passed to the HttpPost is http://10.0.2.2:8080/login.php. If the login.php is on an online web server, you will provide the IP or name to that server (e.g. http://www.example.com/login.php) and set the permission to use internet in the AndroidManifest.xml file. The HttpPost allows you to pass data to the login.php file. You will store name/value of data in a BasicNameValuePair data structure and call the setEntity method of the HttpPost instance to attach the data. In this example, the data to be passed to the login.php file are user name and password. You can make a request to the server by calling the execute method of the HttpClient instance.


  package com.example.andtip;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.os.AsyncTask;

public class MainActivity extends Activity{

   Activity context;  
   HttpPost httppost;
   StringBuffer buffer;
   HttpResponse response;
   HttpClient httpclient;
   List<NameValuePair> nameValuePairs;
   ProgressDialog pd;
protected void onCreate(Bundle savedInstanceState) {
   //TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   context=this;
  
   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.main, menu);
       //create a LayoutTransition object
      
     return true;
   }
  
   public void doLogin(View view){
     EditText txtuser=(EditText)findViewById(R.id.txt_user);
    EditText txtpwd=(EditText)findViewById(R.id.txt_pwd);
    BackTask task=new BackTask();          task.execute(txtuser.getText().toString().trim(),txtpwd.getText().toString().trim(),null);
   }
  
   //background process to validate the user at remove server
   private class BackTask extends AsyncTask<String,String,Void>{  
  
   String returnText="";
   String username;
   String password;
     protected void onPreExecute(){
     super.onPreExecute();
     //show process dialog
     pd = new ProgressDialog(context);
     pd.setTitle("Validating the user");
     pd.setMessage("Please wait.");
     pd.setCancelable(true);
     pd.setIndeterminate(true);
     pd.show();
    
      
       }
       protected Void doInBackground(String...params){  
       username=params[0];
       password=params[1];
       try{
            //create HttpClient object
            httpclient=new DefaultHttpClient();  
            //create HttpPost object
            httppost= new HttpPost("http://10.0.2.2:8080/login.php");    
           //add your post data
             nameValuePairs = new ArrayList<NameValuePair>(2);
             nameValuePairs.add(new BasicNameValuePair("username",username));          

            nameValuePairs.add(new BasicNameValuePair("password",password));              

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
             //Execute HTTP Post Request
             response=httpclient.execute(httppost);
             //create ResponseHander object
             ResponseHandler<String> responseHandler = new BasicResponseHandler();  
             //get responded text
             returnText= httpclient.execute(httppost, responseHandler);
     
       }catch(Exception e){
       if(pd!=null)
       pd.dismiss();  //close the dialog if error occurs
       String errmess=e.getMessage();
       if(errmess!=null)
       Log.e("error from Login",errmess);
      
       }
      
     return null;
      
       }       
      
       protected void onPostExecute(Void result){
       TextView txtstatus=(TextView)findViewById(R.id.txt_status);
       //close the progress dialog
       if(pd!=null)
        pd.dismiss();
       try{
       if(returnText.equals(username)){
       txtstatus.setText("");
       //redirect user to another activity
       Intent intent=new Intent(context,SecondActivity.class);
       intent.putExtra("user", username);
       context.startActivity(intent);
      
         }
         else{
      
       txtstatus.setText("Invalid login! Please try again.");
         }
      
       }catch(Exception e){}
      
       }
      
       }
}



Finally create another activity called SecondActivity. The SecondActivity will display when the login information is correct. It simply displays a welcome message. Below are the content of the activity_second.xml file and SecondActivity.java file.

activity_second.xml file:

<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=".SecondActivity" >
  
    <TextView
     android:id="@+id/txtuser"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginBottom="20dip"
     />

</RelativeLayout>


SecondActivity.java file:

package com.example.andtip;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;

public class SecondActivity extends Activity {

String user;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//read data sent from the login activity
Intent intent=getIntent();
Bundle b=intent.getExtras();
user=b.getString("user");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}

public void onStart(){
super.onStart();
TextView view=(TextView)findViewById(R.id.txtuser);
view.setText("Welcome "+user);
}


}


Android-PHP-Login

Posted by: Dara | post date: 07-16-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.