Tuesday 25 February 2014

Android Login Activity using Json and HTTP connection

Here is the simple example how to create a Login functionality using HTTP connection. 

Step1 : Create a Class LoginActivity

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
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.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);   

        //Button actions
        Button login = (Button) findViewById(R.id.loginButton);
        login.setOnClickListener(this);         

        EditText emailHint = ((EditText) findViewById(R.id.email));
        emailHint.setText("Rahul@Android.Com");

        EditText pwdHint = ((EditText) findViewById(R.id.password));
        pwdHint.setText("Test1234");
    }

    String email;
    String pwd;
    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        case R.id.loginButton:
            email = ((EditText) findViewById(R.id.email)).getText().toString().trim();
            pwd = ((EditText) findViewById(R.id.password)).getText().toString().trim();

            if (email.length() >= 1 && pwd.length() >= 1) {
                if (Util.isConnectionAvailable(this)) {
                    //if (email.matches(emailPattern)){
                    new loginRequest().execute(JsonURL.loginURL, email,
                            pwd);

                } else {
                    showToast("No Connection available");
                }
            } else {
                showToast("Please enter complete details");
            }
            break;

        default:
            break;
        }

    }

    /**AsyncTask enables proper and easy use of the UI thread.
     * This class allows to perform background operations and
     * publish results on the UI thread without having to manipulate
     * threads and/or handlers.
     */

    public class loginRequest extends AsyncTask<String, Void, String> {
        private ProgressDialog spinner;

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            spinner = ProgressDialog.show(LoginActivity.this, "Signing up", "Please wait...");
            spinner.setCancelable(false);
        }

        @Override
        protected String doInBackground(String... params) {

            signUp(params[0], params[1], params[2]);

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            System.out.println("RES -- "+res);
            //start the activity
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
            if (spinner.isShowing())
                spinner.dismiss();
        }

        // Json Parser
        JSONObject jsonDataObject = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        String res;
        private void signUp(String url, String email, String pwd) {

            try {
                System.out.println("Login --"+email+"--"+pwd);
                jsonDataObject.put("userName", email);
                jsonDataObject.put("password", pwd);
           
                // Interface for an HTTP client
                HttpClient client = ConnectionWrapper.getNewHttpClient();
                HttpPost post = new HttpPost("YOUR URL");

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("userName", email));
                nameValuePairs.add(new BasicNameValuePair("password", pwd));
                nameValuePairs.add(new BasicNameValuePair(HTTP.CONTENT_TYPE,"application/json"));

                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = client.execute(post);
                System.out.println("Response -- -"+response);
               
                //Wraps an existing Reader and buffers the input.
                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                String line = "";
                while ((line = rd.readLine()) != null) {
                    System.out.println("Buffered rd -- "+line);

                    JSONObject jObj = new JSONObject(line);
                    JSONArray menuListObject = jObj.getJSONArray("Data");

                    for(int i = 0 ; i < menuListObject.length(); i++){                       
                        JSONObject menu = menuListObject.getJSONObject(i);
                        // Storing each json item in variable
                        String loginUserId = menu.getString("username");
                        String loginRole = menu.getString("role");
                        menu.getString("location");
                        menu.getString("loggedin");
                        System.out.println(loginRole+ " - Login - "+loginUserId);
                    }          
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (spinner.isShowing())
                    spinner.dismiss();
                showToast(e + "");

            }
        }
    }

    private void showToast(final String message) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }

}




Step2 : Create a Class ConnectionWrapper

import java.io.InputStream;
import java.security.KeyStore;import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

public class ConnectionWrapper {

    public static InputStream downloadFromServer(String url) throws Exception {
        return  new DefaultHttpClient().execute(new HttpGet(url)).getEntity().getContent();
    }

    public static HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }   
}         

 

 

Step3 : Create a login layout 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center" 
    android:gravity="center"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="#99676767"
        android:orientation="vertical"
        android:padding="20dp" >

        <EditText
            android:id="@+id/email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"  
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="10dp"            

            android:hint="email"
            android:paddingBottom="10dp"
            android:paddingTop="10dp"
            android:singleLine="true"
            android:textColor="@android:color/black"
            android:textSize="12dp" />

        <EditText
            android:id="@+id/password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"           

            android:hint="password"
            android:inputType="textPassword"
            android:paddingBottom="10dp"
            android:paddingTop="10dp"
            android:singleLine="true"
            android:textColor="@android:color/black"
            android:textSize="12dp" />

        <Button
            android:id="@+id/loginButton"
            android:layout_width="fill_parent"
            android:layout_height="30dp"
            android:layout_gravity="right"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1"

            android:gravity="center"
            android:text="Login"
            android:textColor="@android:color/white" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center_vertical"
            android:gravity="center"
            android:text="Create New Account"
            android:textColor="@android:color/holo_blue_light"
            android:textSize="18sp"
            android:textStyle="bold|italic" />
    </LinearLayout>

</LinearLayout>


Here is the Screenshot of Login Screen