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 java.net.HttpURLConnection 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.
skrin-loginskrin-login-success
STEP 1: Create a new Android project, this time choose the LoginActivity .
login-new-project
choose-login-activity
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.
HttpHandler-java-file
HttpHandler.java

package net.kerul.logindirectory;

//HttpHandler.java

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

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) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        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;
        }

        @Override
        protected void onPreExecute(){
            showProgress(true);
        }//onPreExecute

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

            try {

                URL url = new URL("http://khirulnizam.com/prebetgo/login.php"); // here is your URL path

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

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

                Log.e("params",postDataParams.toString());
                Log.e("URL",url.toString());

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.connect();

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

                writer.flush();
                writer.close();
                os.close();

                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
                            InputStreamReader(
                            conn.getInputStream()));
                    //Log.e("response",conn.getInputStream().toString());

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

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

                    in.close();
                    Log.e("response",conn.getInputStream().toString());
                    Log.e("textmessage",sb.toString());
                    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

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


            mAuthTask = null;
            showProgress(false);

            loginVerification(result);
        }//end onPostExecute

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

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

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

        while(itr.hasNext()){
            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

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

        }//end getPostDataString
        //Log.i("result",result.toString());
        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.setMessage(savemsg);
        builder1.setCancelable(false);
        builder1.setPositiveButton("ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).create().show();

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

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

    }//end loginVerification
STEP 4: The middleware in the online server
<?php
$username=$_POST['username'];
$password=$_POST['password'];

// 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);

?>
Download-blueDOWNLOAD THE COMPLETE SOURCE CODE herehttps://drive.google.com/file/d/0B5_Hw_xzXWcXbm8xTHZtLVI3bTg/view?usp=sharing

Need face-to-face lesson?, we also provide Android Studio training, 0129034614
http://bit.ly/androidjsk
android-kokuis-banner2

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...



Comments

Popular posts from this blog

Several English proverbs and the Malay pair

Or you could download here for the Malay proverbs app – https://play.google.com/store/apps/details?id=net.kerul.peribahasa English proverbs and the Malay pair Corpus Reference: Amir Muslim, 2009. Peribahasa dan ungkapan Inggeris-Melayu. DBP, Kuala Lumpur http://books.google.com.my/books/about/Peribahasa_dan_ungkapan_Inggeris_Melayu.html?id=bgwwQwAACAAJ 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...

Pemasangan Joomla! 1.7 pada pelayan web komputer anda

Latihan ini akan memasang sistem pengurusan kandungan laman web ke dalam pelayan web yang anda telah pasang sebelum ini . LANGKAH 1: Aktifkan Pelayan Web dan Pangkalan Data Aktifkan XAMPP Control Panel, melalui “ Start->All Programs->ApacheFriends->XAMPP Control Panel ”. Rajah 2.1 Pastikan pelayan web Apache dan pelayan pangkalan data MySQL diaktifkan dengan klik butang START. -> Rajah 2.2

searchdelete.php (list records of table to delete)

< form name = 'search' method = 'get' action = '' > Insert the firstname < input type = 'text' name = 'txtname' > < input type = 'submit' value = 'search name' > </ form > < ?php //database connect $db = mysqli_connect ( "localhost" , "root" , "" , "mycompanyhr" ); //checking database connection if ( $db == false ) { echo "Connect failed: " . mysqli_connect_error ( $db ); exit (); } else { echo "Connection successful" ; } $n = $_GET [ 'txtname' ]; $sql = "select EMPNO, FIRSTNAME, LASTNAME, WORKDEPT, PHONENO from employee where FIRSTNAME like '%$n%' " ; $rs = mysqli_query ( $db , $sql ); if ( $rs == false ){ echo ( "Query cannot be executed!<br>" ); echo ( "SQL Error : " . mysqli_error ( $db )); } else { echo "<table border=1>...

ViewFlipper Example–a simple FlashCard

UPDATE: Improved with Fling gesture (Sept 2012) UPDATE: ViewFlipper with Flip-In and Flip-Out Animation (August 2012) This tutorial is to demonstrate the ViewFlipper layout that is almost similar to CardLayout (in Java). The app will produce a simple Flash card that provide several screens with different picture for each card. Flip-in and Flip-out animation provided. Added in Sept 2012 – an improvement to support Fling gesture – enjoy… The amendment is only on the coding part. Some how the layout design (main.xml) is quite long. Later I’ll produce separated screen by including several XML layout from outside files. Screenshots;

Installing Google AdMob into Android Apps

Previously I wrote on why ads are needed to help maintaining an app. Read the article here http://blog.kerul.net/2011/05/generating-revenue-from-free-mobile.html . ---This is quite an old article. You may find the latest supporting AdMob 6.x in here http://blog.kerul.net/2012/08/example-how-to-install-google-admob-6x.html --- This is quite a long tutorial, there are 3 major steps involved. The experiment is done using Windows 7, Eclipse Helios and AdMob SDK 4.1.0 (which currently is the latest-during time of writing). STEP 1: Get the ads from AdMob.com To display the AdMob ads in your Android mobile apps, you need to register first at the admob.com . After completing the registration, login and Add Site/App. Refer to Figure 1. Figure 1 Choose the desired platform and fill in the details (as in Figure 2). Just put http:// in the Android Package URL if your app is not published in the market yet. And click Continue. Figure 2 Download the AdMob Android SDK, and save the zip fil...