Skip to main content

Online database thru JSON in Android Studio

The tutorial is about how to connect Android apps and online database using the JSON formatted data interchange. The server facilities and JSON encoded data has been explained in the previous tutorials;
( Android and JSON Insert, Android and JSON Search ).

The overview concept of JSON data inter change.

android-json-php-mysql-illustration

JSON formatted data sample

json-format-example

First we look at our database structure for this project.

Part A: The online database

The table is training, and this is the structure.

training-table

There is a PHP script that generate a JSON encoded data from the above table.

JSON-training-table

The PHP script to generate JSON formatted data;

<?php
//search.php
/*
 * Following code will search training based on keywords
 */
 
// array for JSON response
$response = array();
 
// include connect class
require_once __DIR__ . '/connect.php';
 
// connecting to db
$db = new DB_CONNECT();

$keyword=$_GET["keyword"];
// get idioms based on keyword

//using LIKE
$result = mysql_query("SELECT * FROM a_training WHERE trainingname LIKE '%$keyword%' LIMIT 0, 20") 
or die(mysql_error());
 
// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    $response["traininglist"] = array();
 
    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $traininglist= array();
        $traininglist["id"] = $row["id"];
        $traininglist["trainingname"] = $row["trainingname"];
        $traininglist["website"] = $row["website"];
		$traininglist["contact"] = $row["contact"];
		$traininglist["trainingdesc"] = $row["trainingdesc"];
 
        // push single idiom array into final response array
        array_push($response["traininglist"], $traininglist);
    }
    // success
    $response["success"] = 1;
 
    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No training found";
 
    // echo no users JSON
    echo json_encode($response);
}
?>

The expected output as viewed in the Android device.

result-set-listing-android-json

Part B: The mobile app interfaces

This part is to create a mobile apps interface, by creating a new project in Android Studio. There will be two activities. The first is the search box. And the second screen activity is to display the result.

As you could notice there is a login UI below, that is for the next exercise to create a LOGIN facility.

activity_main_xml

activity_main.xml – the search box.

 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:id="@+id/activity_main"  
   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="net.kerul.jsonlisting.MainActivity"  
   android:background="@drawable/bgsplit">  
   <EditText  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:inputType="textNoSuggestions|textPersonName"  
     android:ems="10"  
     android:layout_alignParentTop="true"  
     android:id="@+id/txtsearch"  
     android:hint="Search training..."  
     android:layout_alignParentLeft="true"  
     android:layout_alignParentStart="true"  
     android:layout_toLeftOf="@+id/btnsearch"  
     android:layout_toStartOf="@+id/btnsearch"  
     android:layout_alignBottom="@+id/btnsearch" />  
   <ImageButton  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     app:srcCompat="@drawable/ic_search48"  
     android:layout_alignParentRight="true"  
     android:layout_alignParentEnd="true"  
     android:id="@+id/btnsearch"  
     android:layout_alignParentTop="true" />  
   <LinearLayout  
     android:orientation="vertical"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:layout_below="@+id/txtsearch"  
     android:layout_marginTop="120dp"  
     android:layout_alignParentRight="true"  
     android:layout_alignParentEnd="true"  
     android:background="#50ff0000">  
     <TextView  
       android:text="Authorised login only"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:id="@+id/textView"  
       android:textColor="#000000"  
       android:textAlignment="center"  
       android:textSize="24sp"  
       android:background="#ff0000" />  
     <EditText  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:inputType="textPersonName"  
       android:ems="10"  
       android:id="@+id/txtuname"  
       android:hint="Username" />  
     <EditText  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:inputType="textPassword"  
       android:ems="10"  
       android:id="@+id/txtpwd"  
       android:drawableRight="@android:drawable/ic_secure"  
       android:hint="Password" />  
     <Button  
       android:text="Login"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:id="@+id/btnlogin" />  
   </LinearLayout>  
 </RelativeLayout>  

 

activity_listing_xml

activity_listing.xml – the result display. The main UI component here is ListView with the id list.

 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:id="@+id/activity_listing"  
   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="net.kerul.jsonlisting.Listing"  
   android:background="#FFA233" >  
   <ListView  
     android:id="@+id/list"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content" />  
 </RelativeLayout>  

list_item.xml – this is to display one record. This list_item will be re-used by ListView for each record.

 <?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:orientation="vertical">  
   <TextView  
     android:id="@+id/id"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:paddingBottom="2dip"  
     android:paddingTop="6dip"  
     android:textColor="@color/colorPrimaryDark"  
     android:textSize="16sp"  
     android:textStyle="bold" />  
   <TextView  
     android:id="@+id/trainingname"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:paddingBottom="2dip"  
     android:textColor="@color/colorAccent" />  
   <TextView  
     android:id="@+id/website"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:textColor="#5d5d5d"  
     android:textStyle="bold" />  
 </LinearLayout>  

 

Part C: The Java files contain;
1. MainActivity.java
– main interface where the search box is.
2. Listing.java – will search to the online database do the result listing.
3. HttpHandle.java – to handle the connection to the JSON service online page.

 

MainActivity.java – the activity screen is activity_main.xml

 package net.kerul.jsonlisting;  
 import android.app.Dialog;  
 import android.app.ProgressDialog;  
 import android.content.Intent;  
 import android.os.AsyncTask;  
 import android.support.v7.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.widget.EditText;  
 import android.widget.ImageButton;  
 import java.io.InputStream;  
 public class MainActivity extends AppCompatActivity implements View.OnClickListener{  
   ImageButton btnsearch;  
   EditText txtsearch;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     //UI  
     txtsearch=(EditText)findViewById(R.id.txtsearch);  
     btnsearch=(ImageButton)findViewById(R.id.btnsearch);  
     btnsearch.setOnClickListener(this);  
   }//end onCreate  
   public void onClick(View v){  
     if(v.getId()==R.id.btnsearch){  
       Intent listing= new Intent(this,Listing.class);  
       listing.putExtra("searchkey",txtsearch.getText().toString());  
       startActivity(listing);  
     }  
   }//end onCLick  
 }  

Listing.java – the activity screen is activity_listing.xml

 package net.kerul.jsonlisting;  
 import android.app.ProgressDialog;  
 import android.os.AsyncTask;  
 import android.os.Bundle;  
 import android.support.v7.app.AppCompatActivity;  
 import android.util.Log;  
 import android.widget.ListAdapter;  
 import android.widget.ListView;  
 import android.widget.SimpleAdapter;  
 import android.widget.Toast;  
 import org.json.JSONArray;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import java.util.ArrayList;  
 import java.util.HashMap;  
 public class Listing extends AppCompatActivity {  
   private String TAG = Listing.class.getSimpleName();  
   private ProgressDialog pDialog;  
   private ListView lv;  
   // URL to get contacts JSON  
   ArrayList<HashMap<String, String>> traininglist;  
   String searchkey;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_listing);  
     Bundle extras = getIntent().getExtras();  
     searchkey=extras.getString("searchkey").toString();  
     //rename actionbar title to search keyword  
     setTitle(searchkey+" Trainings");  
     //URL with searchkey  
     traininglist = new ArrayList<>();  
     lv = (ListView)findViewById(R.id.list);  
     new GetTraining().execute();  
   }  
   /**  
    * Async task class to get json by making HTTP call  
    */  
   private class GetTraining extends AsyncTask<Void, Void, Void> {  
     //Log.e(url2);  
     @Override  
     protected void onPreExecute() {  
       super.onPreExecute();  
       // Showing progress dialog  
       pDialog = new ProgressDialog(Listing.this);  
       pDialog.setMessage("Please wait...");  
       pDialog.setCancelable(false);  
       pDialog.show();  
     }  
     @Override  
     protected Void doInBackground(Void... arg0) {  
       HttpHandler sh = new HttpHandler();  
       //set the URL address of the JSON service page here  
       String url2 = "http://khirulnizam.com/training/search.php?keyword="+searchkey;  
       Log.e(TAG,url2);  
       // Making a request to url and getting response  
       String jsonStr = sh.makeServiceCall(url2);  
       Log.e(TAG, "Response from url: " + jsonStr);  
       //if respon null  
       if (jsonStr != null) {  
         try {  
           JSONObject jsonObj = new JSONObject(jsonStr);  
           // Getting JSON Array node name  
           JSONArray contacts = jsonObj.getJSONArray("training");  
           // looping through All Contacts  
           for (int i = 0; i < contacts.length(); i++) {  
             JSONObject c = contacts.getJSONObject(i);  
             String id = c.getString("id");  
             String trainingname = c.getString("trainingname");  
             String website = c.getString("website");  
             // tmp hash map for single contact  
             HashMap<String, String> contact = new HashMap<>();  
             // adding each child node to HashMap key => value  
             contact.put("id", id);  
             contact.put("trainingname", trainingname);  
             contact.put("website", website);  
             // adding contact to contact list  
             traininglist.add(contact);  
           }  
           //if JSON format error  
         } catch (final JSONException e) {  
           Log.e(TAG, "Json parsing error: " + e.getMessage());  
           runOnUiThread(new Runnable() {  
             @Override  
             public void run() {  
               Toast.makeText(getApplicationContext(),  
                   "Json parsing error: " + e.getMessage(),  
                   Toast.LENGTH_LONG)  
                   .show();  
             }  
           });  
         }  
       } else {  
         // if JSON service server not responding  
         Log.e(TAG, "Couldn't get json from server.");  
         runOnUiThread(new Runnable() {  
           @Override  
           public void run() {  
             Toast.makeText(getApplicationContext(),  
                 "Couldn't get json from server. Check LogCat for possible errors!",  
                 Toast.LENGTH_LONG)  
                 .show();  
           }  
         });  
       }  
       return null;  
     }  
     @Override  
     protected void onPostExecute(Void result) {  
       super.onPostExecute(result);  
       // Dismiss the progress dialog  
       if (pDialog.isShowing())  
         pDialog.dismiss();  
       /**  
        * Updating parsed JSON data into ListView  
        * */  
       ListAdapter adapter = new SimpleAdapter(  
           Listing.this, traininglist,  
           R.layout.list_item, //list_item.xml  
           new String[]{"id", "trainingname", "website"},//array list  
           new int[]{R.id.id, R.id.trainingname, R.id.website}//the UIs in list_item.xml  
       );  
       lv.setAdapter(adapter);  
     }  
   }  
 }  

The Helper class for connection to JSON service server.

HttpHandler.java (no screen for Helper class)

 package net.kerul.jsonlisting;  
 //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();  
   }  
 }  

 

Part D: The Internet permission in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
AndroidManifest_xml
Compile and RUN – all the best…

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

WebDev

http://blog.kerul.net PHP DEVELOPMENT TOOLS Download the XAMPP latest version from www.apachefriends.org . This installation file contains the Apache web server, PHP 5 and 4 interpreter, and the MySQL 5 Community edition. - download latest version MozillaFireFox (OpenSource web browser firefox) – download latest version Google Chrome – fastest web browser on earcth – fast download chrome here TEACHING PLAN Download the teaching plan here for Web/Internet Programming ( download ) NOTES HTML references HTML Editor -  http://www.sublimetext.com/ Lab 1: HTML Basics -  http://www.w3schools.com/html/ Lab 2: Responsive Design:  http://www.w3schools.com/html/html_responsive.asp Lab 3: HTML Forms  http://www.w3schools.com/html/html_forms.asp Lab 4: HTML 5  http://www.w3schools.com/html/html5_intro.asp Lab 5: Bootstrap for responsive Web -  http://www.w3schools.com/bootstra

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 blogger.com and AdSense, download here … Download Windows Live Writer (a superb offline blog post editor)

Contact Us at blog.kerul.net

Powered by EMF HTML Contact Form

ASK kerul pls...

Ask me please, just click the button... Any question related to the web, PHP, database, internet, this blog, my papers, or anything. I'll answer to you as soon as I can, if related to my domain. If not I'll try to find out from Google and provide you a link that can help you solve a problem. Sincerely, kerul. ASK kerul pls... http://kerul.blogspot.com