Skip to main content

Search Operation on Android online Database JSON

For the database setup, please refer to http://blog.kerul.net/2014/04/insert-new-record-on-android-online.html

INTRODUCTION
This tutorial will demonstrate how to retrieve an records form an online database. We are using the JSON data format to transfer the database content to the Android client.
search-UI display-result list
STEP 1: JSON DATA FORMAT GENERATOR (server-side)
android-json-php-mysql-illustration
Overview illustration (click to enlarge)
In order to fetch records form the database, we will use the JSON data format generator using the PHP script. Add this file named search.php to the existing folder in the idiomjson folder, in htdocs. (Refer STEP 1 of this article http://blog.kerul.net/2014/04/insert-new-record-on-android-online.html)
search-php
search.php
<?php
//search.php
/*
 * Following code will search idiom 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
/*
$result = mysql_query("SELECT * FROM a_senarai_e WHERE " .
            "MATCH(entri) AGAINST ('$keyword' ".
            "IN NATURAL LANGUAGE MODE)") or die(mysql_error());
*/

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


When the page is called directly from the browser, this is the JSON formatted data you will see.

http://172.16.16.183/idiomjson/search.php?keyword=baik%20budi

{"idioms":[
    {"id":"106",
    "entry":"Baik budi ",
    "meaning":"Bersikap baik dan penyayang (suka menolong). "},
    
    {"id":"3401",
    "entry":"Yang merah saga, yang kurik kundi, yang indah bahasa, yang baik budi. ",
    "meaning":"Rupa yang elok sahaja, tidak disertakan budi bahasa akan tetap menjadi hina di kalangan masyarakat. "}
],"success":1}


STEP 2: CREATE A NEW PROJECT IN ECLIPSE-ADT (Android client-side)

new-project-search-json

The UI consist of an EditText with id txtkeyword, and a Button id btnsearch.

This is the UI XML file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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=".Search" >

    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Search for Idiom"
                android:textAppearance="?android:attr/textAppearanceLarge" />

        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <EditText
                android:id="@+id/txtkeyword"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10" >

                <requestFocus />
            </EditText>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/btnsearch"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Search" />

        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </TableRow>
    </TableLayout>

</RelativeLayout>


Search.java

This is only has the UI of the keyword entry. It will be calling another page/screen which will list the idioms that match the search keyword.

package net.kerul.searchjson;//change this to ur package name

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Search extends Activity implements OnClickListener {
    private EditText txtkeyword;
    private Button btnsearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        
        //link to UI
        txtkeyword=(EditText)findViewById(R.id.txtkeyword);
        btnsearch=(Button)findViewById(R.id.btnsearch);
        btnsearch.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.btnsearch){
            Intent listIntent = new Intent(this, ListResult.class);
            //send the keyword to the next screen
            searchIntent.putExtra("key",txtkeyword.getText().toString());
            //call the screen for listing
            startActivity(listIntent);
        }
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.search, menu);
        return true;
    }

}


Create the ListView named ListResult activity to handle the result listing.

To create a new activity, right click on project and choose New –> Other…

Use the name ListResult for the new activity.





new-android-activitynew-activity-ListResult

inside this UI XML file copy paste the following XML code. It must have ListView with the id named list.

activity_list_result.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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=".ListResult" >

    <!-- Main ListView
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</RelativeLayout>


Then add another XML file in the layout folder, by right clicking on the layout folder->New->Android XML File. This is to show the record. It will be reiterated for all records successfully fetched. It must be named list_view.xml; it will be called by activity_list_result.xml to populate the idiom data.

new-xml-file

list_item_xml

list_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
 
    <!-- Idioms id will be HIDDEN - used to pass to other activity -->
    <TextView
        android:id="@+id/id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />
 
    <!-- Entry data display -->
    <TextView
        android:id="@+id/entry"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="17dip"
        android:textStyle="bold" />
    <!-- the Meaning data display -->
    <TextView
        android:id="@+id/meaning"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="14dip" />
 
</LinearLayout>


and the ListResult.java file to do the fetch record and display processes.

ListResult.java

package net.kerul.searchjson;//change to your package name

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.ListActivity;
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.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
 
public class ListResult extends ListActivity {
 
    // Progress Dialog
    private ProgressDialog pDialog;
 
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
 
    ArrayList<HashMap<String, String>> idiomsList;
 
    // url to get the idiom list
    private static String url_search = "http://172.16.16.183/idiomjson/search.php";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_IDIOMS = "idioms";
    private static final String TAG_ID = "id";
    private static final String TAG_ENTRY = "entry";
    private static final String TAG_MEANING = "meaning";
 
    // products JSONArray
    JSONArray idioms = null;
    //search key value
    public String searchkey;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_result);
        Intent myIntent = getIntent(); 
        // gets the arguments from previously created intent
        searchkey = myIntent.getStringExtra("keyword");
 
        // Hashmap for ListView
        idiomsList = new ArrayList<HashMap<String, String>>();
 
        // Loading idioms in Background Thread
        new LoadIdioms().execute();
 
        // Get listview
        ListView lv = getListView();
 
        // on seleting single idioms
        // to do something 
        lv.setOnItemClickListener(new OnItemClickListener() {
 
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String iid = ((TextView) view.findViewById(R.id.id)).getText()
                        .toString();
 
            }
        });
 
    }
 
    /**
     * Background Async Task to Load Idioms by making HTTP Request
     * */
    class LoadIdioms extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ListResult.this);
            pDialog.setMessage("Loading IDIOMS. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        /**
         * getting Idioms from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            //value captured from previous intent
            params.add(new BasicNameValuePair("keyword", searchkey));
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_search, "GET", params);
 
            // Check your log cat for JSON response
            Log.d("Search idioms: ", json.toString());
 
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    idioms = json.getJSONArray(TAG_IDIOMS);
 
                    // looping through All Products
                    for (int i = 0; i < idioms.length(); i++) {
                        JSONObject c = idioms.getJSONObject(i);
 
                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String entry = c.getString(TAG_ENTRY);
                        String meaning = c.getString(TAG_MEANING);
 
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
 
                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_ENTRY, entry);
                        map.put(TAG_MEANING, meaning);
 
                        // adding HashList to ArrayList
                        idiomsList.add(map);
                    }
                } else {
                    // no idioms found
                    //do something
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            //return "success";
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting the related idioms
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            ListResult.this, idiomsList,
                            R.layout.list_item, new String[] { TAG_ID, TAG_ENTRY, TAG_MEANING},
                            new int[] { R.id.id, R.id.entry, R.id.meaning});
                    // updating listview
                    setListAdapter(adapter);
                }
            });
 
        }
 
    }
}




AND don’t forget the JSONParser.java file. Right click on the package name –>New->Class





add-new-class-JSONParsernew-class-JSONParser-name

JSONParser.java

package net.kerul.searchjson;//change to your package name

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<NameValuePair> 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;
 
    }
}


AndroidManifest.xml – don’t forget to add INTERNET Uses Permission. And save the file.

add-uses-permission

internet-uses-permission

Run on your device/emulator… All the best
.

NEXT - Android Studio 2.2 Training - is available here bit.ly/androidjsk

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

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)

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.

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. (  http://www.w3schools.com/bootstrap/   ) Available here -  http://getbootstrap.com/ 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  http://bootstraphero.com/the-big-badass-list-of-twitter-bootstrap-resources/ Flat-UI is from DesignModo -   http://designmodo.com/flat/ 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

List of Malay stop words

Malay Stop Word List ada inikah sampai adakah inilah sana adakan itu sangat adalah itukah sangatlah adanya itulah saya adapun jadi se agak jangan seandainya agar janganlah sebab akan jika sebagai aku jikalau sebagaimana akulah jua sebanyak akupun juapun sebelum al juga sebelummu alangkah kalau sebelumnya allah kami sebenarnya amat kamikah secara antara kamipun sedang antaramu kamu sedangkan antaranya kamukah sedikit apa kamupun sedikitpun apa-apa katakan segala apabila ke sehingga apakah kecuali sejak apapun kelak sekalian atas kembali