Immanuel

Tuesday, February 4, 2014

Android Web login Using JSON Example

Logging in to the web site in android mobile can be achieved by loading the entire page in Web view but this has lots of drawbacks
1. Your web site should be mobile compatibility and more responsive
2. Network bandwidth
3. Time delay

This can be overcome by using the HttpClient and JSON in Android.

We are about to create a native android application that will have a login and register form which is used to login / register the user to the website that is running PHP (You  can your any other also) in internet.
JSON (Java Script Object Notation) is the intermediate data transfer agent between web server and Android Mobile

Pre-requestion 
1. Android Development Environment in your system
            Refer:http://arunimmanuel.blogspot.in/2012/07/installing-android-in-windows.html
            (or)
            Download latest Android studio from google  http://developer.android.com/sdk/installing/studio.html
2. Web site with PHP, MYSQL which give JSON array output.

Steps to be followed
Create a Signup page in Web server named signup.html



Sign Up


User Name:

Password:



Then create signup.php
$Uname = $_POST["txtUname"];
$Pass = $_POST["txtPass"];
$con=mysqli_connect("YOUR_HOST","YOUR_USERNAME","YOUR_PASS","YOUR_DB");
// Check connection
if (mysqli_connect_errno())
{
$response["success"] = 0;
 $response["message"] = "Database Error!";
die(json_encode($response));
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
try{

mysqli_query($con,"INSERT INTO login VALUES ('$Uname','$Pass')");
$response["success"] = 1;
 $response["message"] = "Registration successful!";
die(json_encode($response));
}
catch(Exception $e){
$response["success"] = 0;
 $response["message"] = "Cannot Add";
die(json_encode($response));
}
mysqli_close($con);

?>


Create login page login.html




User Name:


Password:



Create login.php

$Uname = $_POST["txtUName"];
$Pass = $_POST["txtPass"];

$con=mysqli_connect("YOUR_HOST","YOUR_USERNAME","YOUR_PASS","YOUR_DB");// Check connection
if (mysqli_connect_errno())
  {
$response["success"] = 0;
 $response["message"] = "Database Error!";
die(json_encode($response));
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM login where UName='$Uname' AND Pass='$Pass'");

while($row = mysqli_fetch_array($result))
  {
$response["success"] = 1;
 $response["message"] = "Login successful!";
die(json_encode($response));
header("Location: home.php");
  }

mysqli_close($con);
?>


Now create a new Android Project

My MainActivity is renamed to Login

Create login.xml

Code for login.xml

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

   


Create register.xml

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

            android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/password"
        android:layout_centerVertical="true"
        android:text="Username" />

            android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" />

            android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/username"
        android:layout_below="@+id/username"
        android:text="Password" />

            android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="Android Remote Server Tutorial"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

            android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/TextView01"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPassword" />

   


Now inflate these activity and views in respective Java files

I have Login.java and Register.java

Login.java

package com.android.json.login;

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 mSubmit, mRegister;
   
     // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();
   
    //php login script location:
   
    //localhost : 
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
   // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
   
    //testing on Emulator:
    private static final String LOGIN_URL = "http://arunimmanuel.000space.com/Social/login.php";
   
  //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
   
    //JSON element ids from repsonse of php script:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
       
        //setup input fields
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
       
        //setup buttons
        mSubmit = (Button)findViewById(R.id.login);
        mRegister = (Button)findViewById(R.id.register);
       
        //register listeners
        mSubmit.setOnClickListener(this);
        mRegister.setOnClickListener(this);
       
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.login:
                new AttemptLogin().execute();
            break;
        case R.id.register:
                Intent i = new Intent(this, Register.class);
                startActivity(i);
            break;

        default:
            break;
        }
    }
   
    class AttemptLogin extends AsyncTask {

         /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;
       
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
       
        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List params = new ArrayList();
                params.add(new BasicNameValuePair("txtUName", username));
                params.add(new BasicNameValuePair("txtPass", password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                       LOGIN_URL, "POST", params);

                // check your log for json response
                Log.d("Login attempt", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                    Intent i = new Intent(Login.this, Home.class);
                    finish();
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);     
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
           return null; 
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
            }
        }     
    }
 }


Register.java

package com.android.json.login;

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.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 Register extends Activity implements OnClickListener{
   
    private EditText user, pass;
    private Button  mRegister;
   
     // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();
   
    //php login script
   
    //localhost : 
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
   // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
   
    //testing on Emulator:
    private static final String LOGIN_URL = "http://arunimmanuel.000space.com/Social/signup.php";
   
  //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
   
    //ids
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
       
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
       

        mRegister = (Button)findViewById(R.id.register);
        mRegister.setOnClickListener(this);
       
    }


    public void onClick(View v) {
        // TODO Auto-generated method stub
       
                new CreateUser().execute();
       
    }
   
    class CreateUser extends AsyncTask {

         /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;
       
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Register.this);
            pDialog.setMessage("Creating User...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
       
        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List params = new ArrayList();
                params.add(new BasicNameValuePair("txtUname", username));
                params.add(new BasicNameValuePair("txtPass", password));

                Log.d("request!", "starting");
               
                //Posting user data to script
                JSONObject json = jsonParser.makeHttpRequest(
                       LOGIN_URL, "POST", params);

                // full json response
                Log.d("Login attempt", json.toString());

                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User Created!", json.toString());                 
                    finish();
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);
                   
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
           
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
            }

        }
       
    }
  }


We need JSON parser class to parse the JSON response
JSONParser.java

package com.android.json.login;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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 jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                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 sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Now update the Manifest
1. Permission to Access Internet
2. Add new Activity to Manifest

AndroidManifest.xml



            android:name = ".Register"/>
                    android:name=".Home"/>


Download Source code from GitHub : https://github.com/arunimmanuelpro/Android-JSON
Happy Hacking :)

6 comments:

  1. When entering wrong credentials the app crashes.. please tell me how to solve this

    ReplyDelete
  2. Application crashes while login or registration... how to solve it ?

    ReplyDelete
  3. how about database in mysql?
    can u help me

    thanx

    ReplyDelete
  4. Congratulations guys, quality information you have given!!!..Its really useful blog. Thanks for sharing this useful information
    Android Training in chennai with placement | Android Training in velachery

    ReplyDelete
  5. can u show me the json format?
    thanks

    ReplyDelete

Twitter Bird Gadget