heading

heading

Saturday, 25 January 2014

Android Login Application Using AsyncTask and HttpClient



In this tutorial, we are going to develop a simple app which will accept a username and a password from the user and send to the localhost server for authentication.  If the login information entered is correct, the user will be navigated to the main menu, otherwise an error message will be displayed.  This application will make use of the HttpClient class and also the AsyncTask class.

This tutorial will be divided into:
  • Server Side: The sever side will be a PHP(check.php) file hosted on a localhost server.
  • Client Side:  The client side represents our android application.

Structure of the Android Project:
  • Classes: 
    • LoginActivity.java
    • MainMenuActivity.java
    • CustomHttpClient.java
  • XML file:
    • activity_login.xml
    • activity_mainmenu.xml
Codes:
  • AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.logintutorial"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.logintutorial.LoginActivity"
            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.example.logintutorial.MainMenuActivity"
            android:label="@string/app_name" >
        </activity>
    </application>
</manifest>
  • res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">logintutorial</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="heading1">Welcome. Login to continue.</string>
    <string name="heading2">Login Success! You are on the main menu.</string>
    <string name="hint_user">enter your username</string>
    <string name="hint_pwd">enter your password</string>
    <string name="login_button">LOGIN</string>
</resources>
  • res/layout/activity_login.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=".LoginActivity" >

     <TextView
        android:id="@+id/txtheading1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txtError"
        android:layout_alignParentTop="true"
        android:layout_marginTop="57dp"
        android:gravity="center"
        android:text="@string/heading1"
        android:textColor="#00F"
        android:textSize="40sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/txtUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txtheading1"
        android:layout_below="@+id/txtheading1"
        android:layout_marginTop="105dp"
        android:ems="10"
        android:hint="@string/hint_user"
        android:textSize="25sp" />
     
    <EditText
       android:id="@+id/txtPassword"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/txtUsername"
       android:layout_below="@+id/txtUsername"
       android:layout_marginTop="40dp"
       android:ems="10"
       android:hint="@string/hint_pwd"
       android:textSize="25sp" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txtPassword"
        android:layout_below="@+id/txtPassword"
        android:layout_marginTop="28dp"
        android:text="@string/login_button"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/txtError"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="" />

</RelativeLayout>

  • res/layout/activity_mainmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

     <TextView
         android:id="@+id/txtheading1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_alignParentTop="true"
         android:layout_marginTop="131dp"
         android:gravity="center"
         android:text="@string/heading2"
         android:textColor="#00F"
         android:textSize="40sp"
         android:textStyle="bold" />

</RelativeLayout>
  • src/com.example.logintutorial/LoginActivity.java
package com.example.logintutorial;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {

//define controls
EditText  txt_uname, txt_pwd;
TextView  txt_Error;
Button btnLogin;
String response = null;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        //initalise controls
        txt_uname=(EditText)findViewById(R.id.txtUsername);
        txt_pwd=(EditText)findViewById(R.id.txtPassword);
        btnLogin =(Button)findViewById(R.id.btnLogin);
        txt_Error =(TextView)findViewById(R.id.txtError);
        
        btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String uname = txt_uname.getText().toString();
String pwd = txt_pwd.getText().toString();
validateUserTask task = new validateUserTask();
task.execute(new String[]{uname, pwd});
}
        }); //close on listener
    }// close onCreate
    
    private class validateUserTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("username", params[0] ));
                postParameters.add(new BasicNameValuePair("password", params[1] ));
                String res = null;
        try {
           response = CustomHttpClient.executeHttpPost("http://akinads.0fees.net/check.php", postParameters);
           res=response.toString();
           res= res.replaceAll("\\s+","");                        
       
        catch (Exception e) {
        txt_Error.setText(e.toString());
        }
return res;
}//close doInBackground
@Override
protected void onPostExecute(String result) {
if(result.equals("1")){
//navigate to Main Menu
Intent i = new Intent(LoginActivity.this, MainMenuActivity.class);
startActivity(i);
}
else{
txt_Error.setText("Sorry!! Incorrect Username or Password"); 
}  
}//close onPostExecute
    }// close validateUserTask 
}//close LoginActivity
  • src/com.example.logintutorial/MainMenuActivity.java
package com.example.logintutorial;
import android.app.Activity;
import android.os.Bundle;

public class MainMenuActivity extends Activity{
@Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_mainmenu);
   }
}//close MainMenuActivity
  • src/com.example.logintutorial/MainMenuActivity.java
package com.example.logintutorial;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class CustomHttpClient {
/** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }
    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

As mentioned previously, the server side will be a PHP file hosted on a domain or on a localhost server.  In this example, the PHP file consist of a static 'if..else' function.  However, you can customize the PHP file to link it to your database. 
  • check.php
<?php
//you can include here: Database connection & SQL query
    try{
         $uname = $_POST['username'];
         $pw = $_POST['password'];
         //valid login
         echo "1";
    }
    catch(PDOException $e)    {
        echo $e->getMessage();
    }
?>

No comments:

Post a Comment