Skip to main content

Login JSON Android using Login Activity

I’ve been trying to release this tutorial quite a while. At last after a long hard effort. Since HttpClient is not supported any more in Android SDK 23, I have to resort to org.json.JSONObject and library to do online database with JSON.
The objective of this tutorial is to log-in from a mobile client with the username and password stored in an online database facility.
STEP 1: Create a new Android project, this time choose the LoginActivity .
The Interface
As the interface is provided by the ListActivity template, I will not elaborate.

STEP 2. Add the HttpHandler helper class.
This helper class is to check several errors of HTTP data format. It is also to convert HTTP stream into STRING.
Add JAVA the file to the main package.

package net.kerul.logindirectory;


import android.util.Log;


public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");//method type
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        return response;

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
        } catch (IOException e) {
        } finally {
            try {
            } catch (IOException e) {
        return sb.toString();
STEP 3: The main java file to handle button LOGIN click and connection to the online server.
The code is too long, I just highlight several important functions.
The UserLoginTask class that implemented in AsyncTask (multi-threading).

     * Represents an asynchronous login/registration task used to authenticate
     * the user.
    public class UserLoginTask extends AsyncTask<String, Void, String> {

        private final String mEmail;
        private final String mPassword;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;

        protected void onPreExecute(){

        protected String doInBackground(String... arg0) {

            try {

                URL url = new URL(""); // here is your URL path

                JSONObject postDataParams = new JSONObject();
                //add name pair values to the connection

                postDataParams.put("username", username);
                postDataParams.put("password", password);


                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));


                int responseCode=conn.getResponseCode();
                Log.e("responseCode", "responseCode "+responseCode);
                if (responseCode == HttpsURLConnection.HTTP_OK) {//code 200 connection OK
                    //this part is to capture the server response
                    BufferedReader in=new BufferedReader(new

                    StringBuffer sb = new StringBuffer("");
                    String line="";

                        Log.e("MSG sb",sb.toString());
                    }while ((line = in.readLine()) != null) ;

                    return sb.toString();//server response message

                else {

                    return new String("false : "+responseCode);
            catch(Exception e){
                //error on connection
                return new String("Exception: " + e.getMessage());
        }//end doInBackground

        protected void onPostExecute(String result) {
            //Toast.makeText(getApplicationContext(), result,
            //return result;
            //call method to handle after verification

            mAuthTask = null;

        }//end onPostExecute

        protected void onCancelled() {
            mAuthTask = null;
        }//end onCancelled
    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

            String key=;
            Object value = params.get(key);

            if (first)
                first = false;

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }//end getPostDataString
        return result.toString();
    }//end UserLoginTask
The loginVerification function to display dialog box to the login status.

private void loginVerification(String svrmsg){
        String savemsg="";
        //if new record successfully saved
        Toast.makeText(this, "svrmsg:"+svrmsg,Toast.LENGTH_LONG).show();
        if (svrmsg.equals("success")){

            savemsg="Logged in...";

        else {//save failed
            savemsg="Email/password not match!";

        //**********common dialog box
        AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
        builder1.setTitle("User Login");
        builder1.setPositiveButton("ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

        //call ListUsers page if servermessage is success
        if (svrmsg.equals("success")){

            Intent i=new Intent(this,ListUsers.class);

    }//end loginVerification
STEP 4: The middleware in the online server

// include connect class

require_once __DIR__ . '/connect.php';

// connecting to db

$db = new DB_CONNECT();

$result = mysql_query("SELECT * FROM sd_users WHERE email='$username' AND password=md5('$password')") 

or die(mysql_error());

// check for empty result

if (mysql_num_rows($result) > 0) {
    // match found
 //send success
  echo "success";
  //$response["success"] = 1;
 }//end match found

 else{//no match found
  //send status fail
  echo "fail";
  //$response["success"] = 0;
 //echo json_encode($response);


Need face-to-face lesson?, we also provide Android Studio training, 0129034614

Disclaimer: Intermediate level. This tutorial works on Android Studio 2.2. Should you have any difficulties, leave your comment in the comment section.
SHARE to your friends...


Popular posts from this blog

Several English proverbs and the Malay pair

Or you could download here for the Malay proverbs app – English proverbs and the Malay pair Corpus Reference: Amir Muslim, 2009. Peribahasa dan ungkapan Inggeris-Melayu. DBP, Kuala Lumpur CTRL+F to search Proverbs in English Definition in English Similar Malay Proverbs Definition in Malay 1 Where there is a country, there are people. A country must have people. Ada air adalah ikan. Ada negeri adalah rakyatnya. 2 Dry bread at home is better than roast meat home's the best hujan emas di negeri orang,hujan batu di negeri sendiri Betapa baik pun tempat orang, baik lagi tempat sendiri. 3 There's no accounting for tastes We can't assume that every people have a same feel Kepala sama hitam hati lain-lain. Dalam kehidupan ini, setiap insan berbeza cara, kesukaan, perangai, tabia

Submit your blog address here

Create your own blog and send the address by submitting the comment of this article. Make sure to provide your full name, matrix and URL address of your blog. Refer to the picture below. Manual on developing a blog using and AdSense, download here … Download Windows Live Writer (a superb offline blog post editor)

Applications of Web 2.0

Web 2.0 describes the changing trends in the use of World Wide Web technology and web design that aim to enhance creativity , secure information sharing, collaboration and functionality of the web. Web 2.0 concepts have led to the development and evolution of web-based communities and hosted services , such as social-networking sites , video sharing sites , wikis , blogs . Find a website or web application that conform to the criteria of Web 2.0. Put the name of the application and the URL in the comment below. Please provide your full name and matrix number. Make sure the application you choose is not already chosen by your friend in the previous comment.

Kursus Ionic 2021

Kursus terbaharu IONIC-5 Pengenalan sepintas lalu pembangunan apps Ionic WhatsApp kami di Dapatkan tarikh kursus terkini di Kolej Komuniti Temerloh September 2020 ILP Selandar Ogos 2020 Berikut senarai tutorial yang sedang kami bangunkan; HARI 1 & 2 Pengenalan IONIC dan cara pasang dalam Windows10 (   ). Versi  PDF pengenalan & install IONIC Pasang plugin TypeSript (skrip utama dalam Ionic) dalam Sublime. Struktur asas Page dalam projek Ionic. Sharing intent kepada media sosial. Plugin Kamera dalam apps Ionic ( ) HARI 2 & 3 IONIC + FIREBASE Firebase Ionic CRUD – masukkan rekod baharu ( download slides ) Firebase Ionic CRUD – baca rekod dan senaraikan ( download slides ) Firebase Ionic CRUD – perbaharui dan pada rekod (download slides) Kod contoh lengkap S-CRUD IONIC+FIREBASE di Kita pasti biasa dengan pem

Bootstrap Template for PHP database system - MyCompanyHR

HTML without framework is dull. Doing hard-coded CSS and JS are quite difficult with no promising result on cross platform compatibility. So I decided to explore BootStrap as they said it is the most popular web framework. What is BootStrap? - Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. (   ) Available here - Why you need Flat-UI? Seems like a beautiful theme to make my site look professional. Anyway you could get variety of BootStrap theme out there, feel free to select here Flat-UI is from DesignModo - Web Programming MyCompanyHR – PHP & MySQL mini project (with Boostrap HTML framework) Template 1: Template for the Lab Exercise. This is a project sample of a staff record management system. It has the PHP structured co