AndroidCSS

Android material design Programming Blog

Android Search View with PHP and MySQL

This tutorial demonstrates how to deal with search view in android using PHP as server side scripting language and MySQL as backend.

User enters search query into search view/search bar to search for particular information, the query is sent to php file and result from php file is displayed on Android ListView / RecyclerView.

Let’s see the files and functions involved.

Download Code From Github

Android SearchView video demo

Mysql

Below is the structure of table ‘tbl_fish’.

CREATE TABLE IF NOT EXISTS `tbl_fish` (
  `fish_id` int(11) NOT NULL AUTO_INCREMENT,
  `fish_name` varchar(255) NOT NULL,
  `cat_name` varchar(50) NOT NULL,
  `size_name` varchar(50) NOT NULL,
  `price` int(11) NOT NULL,
  KEY `fish_id` (`fish_id`),
  FULLTEXT KEY `my_index` (`fish_name`,`cat_name`,`size_name`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Table ‘tbl_fish’ holds data row like this.

INSERT INTO `tbl_fish` (`fish_id`, `fish_name`, `cat_name`, `size_name`, `price`) VALUES
(1, 'Indian Mackerel', 'Marine Fish', 'Medium', 100),
(2, 'Manthal Repti', 'Marine Fish', 'Small', 200),
(3, 'Baby Sole Fish', 'Marine Fish', 'Medium', 300),
(6, 'Clam Meat', 'Shell Fish', 'Medium', 150),
(7, 'Indian Prawn', 'Shell Fish', 'Medium', 500);

PHP

The files involved are as follow.

config.inc.php

The configuration file for PHP.

<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";

try {
    	$connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    	$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
    {
    	die("OOPs something went wrong");
    }

?>

fish-search.php

Search database for query sent from Android and return the result as JSON format.

<?php

     if(isset($_POST['searchQuery']))
     {
     	  require_once('config.inc.php');
	  $search_query=$_POST['searchQuery'];
          $sql = 'SELECT * from tbl_fish where MATCH(fish_name,size_name,cat_name) AGAINST(:search_query)';
          $statement = $connection->prepare($sql);
	  $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
          $statement->execute();
          if($statement->rowCount())
          {
	    $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
	    header('Content-type: application/json');
   	    echo json_encode($row_all);
          }  
          elseif(!$statement->rowCount())
          {
	    echo "no rows";
          }
     }
		  
?>

Android

The Steps and files involved are as follow.

Adding Dependencies

Open your build.gradle(Module: app) file and add the following dependencies highlighted below and sync your project gradle.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:recyclerview-v7:23.3.0'
}

Note: You may need to replace the version of recyclerview dependency as your appcompat version, in my case version is 23.3.0.

MainActivity.java

Here are the major steps involved.

  • When user enters data into search field and clicks GO button on keypad innitiates recreation of activity which in turn calls onNewIntent(Intent intent) where an object of AsyncFetch class is created to carry out Asynchronous task.
  • onPreExecute(), invoked on the UI thread before the task is executed. Here We are displaying loading message.
  • doInBackground(Params...), invoked on the background thread immediately after
    onPreExecute() finishes executing. The sending of search query entered by user to PHP file and recieving of data from PHP file using HttpURLConnection class has done in this function.
  • onPostExecute(Result), invoked on the UI thread after the background computation finishes. Here we are extracting data recieved from JSON file.
  • Finally, the data is passed to adapter to display it on RecyclerView.
package com.androidcss.searchexample;

import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFish;
    private AdapterFish mAdapter;

    SearchView searchView = null;


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // adds item to action bar
        getMenuInflater().inflate(R.menu.search_main, menu);

        // Get Search item from action bar and Get Search service
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
        if (searchItem != null) {
            searchView = (SearchView) searchItem.getActionView();
        }
        if (searchView != null) {
            searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
            searchView.setIconified(false);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    // Every time when you press search button on keypad an Activity is recreated which in turn calls this function
    @Override
    protected void onNewIntent(Intent intent) {
        // Get search query and create object of class AsyncFetch
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            if (searchView != null) {
                searchView.clearFocus();
            }
            new AsyncFetch(query).execute();

        }
    }

    // Create class AsyncFetch
    private class AsyncFetch extends AsyncTask<String, String, String> {

        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;
        String searchQuery;

        public AsyncFetch(String searchQuery){
            this.searchQuery=searchQuery;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

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

                // Enter URL address where your php file resides
                url = new URL("http://192.168.1.7/test/fish-search.php");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("POST");

                // setDoInput and setDoOutput to true as we send and recieve data
                conn.setDoInput(true);
                conn.setDoOutput(true);

                // add parameter to our above url
                Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {
                    return("Connection error");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }


        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread
            pdLoading.dismiss();
            List<DataFish> data=new ArrayList<>();

            pdLoading.dismiss();
            if(result.equals("no rows")) {
                Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
            }else{

                try {

                    JSONArray jArray = new JSONArray(result);

                    // Extract data from json and store into ArrayList as class objects
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject json_data = jArray.getJSONObject(i);
                        DataFish fishData = new DataFish();
                        fishData.fishName = json_data.getString("fish_name");
                        fishData.catName = json_data.getString("cat_name");
                        fishData.sizeName = json_data.getString("size_name");
                        fishData.price = json_data.getInt("price");
                        data.add(fishData);
                    }

                    // Setup and Handover data to recyclerview
                    mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                    mAdapter = new AdapterFish(MainActivity.this, data);
                    mRVFish.setAdapter(mAdapter);
                    mRVFish.setLayoutManager(new LinearLayoutManager(MainActivity.this));

                } catch (JSONException e) {
                    // You to understand what actually error is and handle it appropriately
                    Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                    Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
                }

            }

        }

    }
}

DataFish.java

package com.androidcss.searchexample;

public class DataFish {
    public String fishName;
    public String catName;
    public String sizeName;
    public int price;
}

AdapterFish.java

Here Binding data to views and recycling of views will be done when user scroll through RecyclerView.

package com.androidcss.searchexample;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataFish> data= Collections.emptyList();
    DataFish current;

    // create constructor to initialize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataFish> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // Inflate the layout when ViewHolder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.container_fish, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;
    }

    // Bind data
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in RecyclerView to bind data and assign values from list
        MyHolder myHolder= (MyHolder) holder;
        DataFish current=data.get(position);
        myHolder.textFishName.setText(current.fishName);
        myHolder.textSize.setText("Size: " + current.sizeName);
        myHolder.textType.setText("Category: " + current.catName);
        myHolder.textPrice.setText("Rs. " + current.price + "\\Kg");
        myHolder.textPrice.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }


    class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        TextView textFishName;
        TextView textSize;
        TextView textType;
        TextView textPrice;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            textFishName= (TextView) itemView.findViewById(R.id.textFishName);
            textSize = (TextView) itemView.findViewById(R.id.textSize);
            textType = (TextView) itemView.findViewById(R.id.textType);
            textPrice = (TextView) itemView.findViewById(R.id.textPrice);
            itemView.setOnClickListener(this);
        }

        // Click event for all items
        @Override
        public void onClick(View v) {

            Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();

        }

    }

}

activity_main.xml

XML file for MainActivity.java.

<?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">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/fishPriceList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="10dp"
        android:layout_weight="1"
        />
</LinearLayout>

container_fish.xml

XML file for AdapterFish.java.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:orientation="horizontal"
    android:padding="10dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="fish name"
        android:id="@+id/textFishName"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="price"
        android:id="@+id/textPrice"
        android:textColor="@color/colorAccent"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/textSize"
        android:layout_marginLeft="5dp"
        android:layout_below="@id/textFishName"
        android:textColor="#666"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="sd"
        android:id="@+id/textType"
        android:layout_marginLeft="5dp"
        android:layout_below="@id/textSize"
        android:textColor="#666"/>

</RelativeLayout>

search_main.xml

This file must be placed inside res→menu resource directory. If you don’t find any menu folder inside res directory, then add one by Right clicking on res directory(Right click on res→New→Android Resource Directory).

<menu 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" tools:context=".SearchResultsActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"/>

</menu>

searchable.xml

This file must be placed inside res→xml resource directory. If you don’t find any xml folder inside res directory, then add one by Right clicking on res directory(Right click on res→New→Android Resource Directory).

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="Search..."
    android:label="@string/app_name" />

AndroidManifest.xml

Make sure you added below marked code to your AndroidManifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidcss.searchexample" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".MainActivity" />

        <activity android:name=".MainActivity" android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.intent.action.SEARCH" />
                <action android:name="android.intent.action.VIEW" />
            </intent-filter>
            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>
    </application>

</manifest>

218 Comments

Add yours

  1. i make this project can not using eclipse

    • I’m not going to tell you it’s impossible to do this project with Eclipse but i’m sure you may end up with technical problems somewhere because there may be some libraries that may only compatible with android studio. Even automatically searching and adding dependencies in gradle is not supported by eclipse, you may need to use maven for that.

  2. what about using restrofit please ?
    i just confuse about getting data using http request because im using retrofit. Thanks

    • Choosing between library is entirely depend on your requirement, It depends on your application complexity, library size and many more factors. Refer particular library for features they provide and compare whether you really require that feature in your application. Use AsyncTask in case of fewer request to server and loading some small files(Remember you need to handle error).

  3. OOPs something went wrong

    can you tell me how to fix it master ?
    no line error saying but i cant connect it

  4. I done this tutorial successfully !
    I wish to see more tutorial for android studio..
    Or can give some tutorial to fetch image from mysql to android?

  5. Hi, I tried implementing my own database into this tutorial. The data are able to display into the emulator but the search function does not work (meaning when I key in the keywords into the search bar, it does not filter the data. Instead, it remains as a list of data presented in the emulator). There is no error when building the project. May I know how can I solve this problem? Thanks

    • In our PHP file we are using mysql MATCH() and AGAINST() function to search for a query in database which in turn requires FULLTEXT index for fields(Please see in MySQL section).

      Please test your PHP file in your browser for some query and make sure that your PHP file outputting correct data before testing into emulator.

      • I used the php and sql codes that are given here but there is no data output in the browser.

        • It will not output any data because there is a if condition if(isset($_POST['searchQuery'])) in php which specifically check for post data from android. In order to test that file in your browser you need to remove that if block and set variable $search_query='medium' rather than $search_query=$_POST['searchQuery'];. For your reference i altered that fish-search.php, remove all code from fish-search.php and copy the below code into your fish-search.php.

          <?php
          
                    require_once('config.inc.php');
          	  $search_query='medium';
                    $sql = 'SELECT * from tbl_fish where MATCH(fish_name,size_name,cat_name) AGAINST(:search_query)';
                    $statement = $connection->prepare($sql);
          	  $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
                    $statement->execute();
                    if($statement->rowCount())
                    {
          	    $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
          	    header('Content-type: application/json');
             	    echo json_encode($row_all);
                    }  
                    elseif(!$statement->rowCount())
                    {
          	    echo "no rows";
                    }
          		  
          ?>
          
        • Hello Robert,

          You copied all code into stackoverflow and i request you to remove it asap. Why cant you link back to my post there and propose your problem.

      • Instead of using Match and Against in the PHP file, How would I use LIKE()

        • For your reference i altered fish-search.php to work with LIKE function. Please remove all code from fish-search.php and paste this fresh code.

          <?php
          
               if(isset($_POST['searchQuery']))
               {
               	  require_once('config.inc.php');
          	  $search_query='%' . $_POST['searchQuery'] . '%';
                    $sql = 'SELECT * FROM tbl_fish WHERE fish_name LIKE :search_query';
                    $statement = $connection->prepare($sql);
          	  $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
                    $statement->execute();
                    if($statement->rowCount())
                    {
          	    $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
          	    header('Content-type: application/json');
             	    echo json_encode($row_all);
                    }  
                    elseif(!$statement->rowCount())
                    {
          	    echo "no rows";
                    }
               }
          		  
          ?>
          
  6. Im Having difficulties Changing your MATCH clause to a LIKE Clause so that instead of having to type in “Indian” in order to view both the Mackrel and Prawn, I could type in “ind” or “dian” and the query would generate results similar to that. Im currently working on the php file and im not sure how to add in the ‘%’ ___?___’%’ so that the Like clause will work. Can you help me out

    • like something of this sort. except this doesnt work. Hoping you can teach/help me out

      prepare($sql);
      $statement->bindParam(‘:search_query’, $search_query, PDO::PARAM_STR);
      $statement->execute();
      if($statement->rowCount())
      {
      $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
      header(‘Content-type: application/json’);
      echo json_encode($row_all);

      }
      elseif(!$statement->rowCount())
      {
      echo “no rows”;
      }
      }

      ?>

    • ignore the last one since it didnt format properly

      $sql = ‘SELECT * from tbl_fish WHERE (`fish_name` LIKE ‘%”searchQuery”%’) AGAINST(:search_query)’;

      i was trying to change this line to allow for instances when the users Serach/query can show results similar to what the database has.

      • You need to use AGAINST if your are using MATCH function in query and for correct LIKE syntax refer below code. You may replace $_POST['searchQuery'] as ‘ind’ or ‘dian’ to test.

        $search_query='%' . $_POST['searchQuery'] . '%';
        $sql = 'SELECT * FROM tbl_fish WHERE fish_name LIKE :search_query';
        
  7. Hi GURURAJ,

    Fantastic tutorial, incredibly easy to understand and follow. Thank you.

    Can you please guide me how I can display a URL address I retrieve from MySQ database in Search result? I’m having difficulty in display the image, I already got the URL from MySQL and I placed an NetworkImageView widget in container_fish.xml.

    • Please look at tutorial Android JSON Parsing and display with RecyclerView for image display and if you find any difficulty understanding, let me know.

      • Hi GURURAJ,

        Thank you for the suggestion, that tutorial helped me display images in search view.

        Now that I have Name, Size and Image can you please show me how to push those variables to a new activity during the intent action?

        • @mustafa

          // Store your variable to bundle and call activity. Replace CurrentActivity as your current class name and NewActivity as your launching activity. 
          
          Intent i = new Intent(CurrentActivity.this,NewActivity.class);
          i.putExtra("Name", "Indian Mackerel");
          i.putExtra("Size", "Medium");
          i.putExtra("ImageName", "1.jpg");
          startActivity(i);
          
          // Retrieve variable on onCreate() function of your launching activity(NewActivity.class)
          
          String Name='';
          String Size='';
          String ImageName='';
          
          Bundle extras = getIntent().getExtras();
          if (Name != null) { Name = extras.getString("Name"); }
          if (Size != null) { Size = extras.getString("Size"); }
          if (Image != null) { ImageName = extras.getString("ImageName"); }
          
          • Gururaj,

            Thank you once again. Some minor modifications had to be made on my end for your suggestion to work. For your readers I will provide what I had to do.

            Since I was calling the intent from an adapter I had to use the following:

            Intent search = new Intent(context, DetailsView.class);
            search.putExtra(“Name”, textFishName.getText());
            search.putExtra(“Url”, textFishUrl.getText());
            context.startActivity(search);

            Notice that “putExtras” is changed to “putExtra” and “context” is used or else the activity wont start. I also used the variables retrieved in my JSON to send to the new activity.

          • Gururaj P Kharvi

            June 8, 2016 at 4:29 pm

            That’s good suggestion mustafa…nice

          • Mustafa im error at textFishName.getText() ? how to fix it?

          • where im implement bundle exrtras? in onCreate?

          • Gururaj P Kharvi

            June 28, 2016 at 8:22 am

            Yes. Read the comment written inside code block.

          • i’m sorry guruaj i not understand T.T..
            i put intent in adaptor like a Mustafa.. and then i put bundle in second activity and error T.T what worng? can you tell me step by step?
            or php file needed modifed? i using above php file..

          • Gururaj P Kharvi

            June 28, 2016 at 3:45 pm

            @muhel

            Let me know whether you are getting output or not(define exact database and php file) and for putextra please define your problem clearly.

          • i following your tutorial http://androidcss.com/android/fetch-json-data-android/
            and i’m useing the php file which is defined in above tutorial

            and then i add method onItemclick in adapterfish to push those variables to a new activity, and then following:
            Intent search = new Intent(context, DetailsView.class);
            search.putExtra(“Name”, textFishName.getText());
            search.putExtra(“Url”, textFishUrl.getText());
            context.startActivity(search);
            on my method onItemClick.. and then add bundle extras in onCreate()…
            so… there is something less ??

            thanks for help me gururaj 🙂

          • Gururaj P Kharvi

            June 29, 2016 at 1:59 am

            May i know, how you implemented onItemclick in adapterfish. [To paste your code please go to tohtml.com paste your code there and click on highlight to get html code and paste the same here in comment box]

          • thanks gururaj.. i change name to namakategori.. and textfishname to label1
            i wanna record label1 and and catch it in my kategori.class
            and this my php.file

            <?php

                 require_once(‘config.inc.php’);

                      $sql = ‘SELECT * FROM wisata’;
                      $statement = $connection->prepare($sql);
                      $statement->execute();
                      if($statement->rowCount())
                      {
            $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
            header(‘Content-type: application/json’);
                echo json_encode($row_all);
                      }
            ?>

          • Gururaj P Kharvi

            June 29, 2016 at 6:12 am

            Hope your onClick() method works. Now, will see whether data sent from onClick() method to activity works or not.

            Add this below code into your onClick() method of AdapterKategori class.

            Intent i = new Intent(context,Kategori.class);
            i.putExtras("Test", "Works!");
            context.startActivity(i);
            

            Add this below code into onCreate() method of your Kategori.class.

            String Test='';
            Bundle extras = getIntent().getExtras();
            if (Test != null) { Test = extras.getString("Test"); }
            Toast.makeText(context, Test.toString(), Toast.LENGTH_LONG).show();
            

            and let me know whether you are getting “Works!” toast message or not.

          • hmm… context in onCreate() error dude.. and i try to create field context in kategori.class and not error but… im try aplication is error, if i click cannot move to kategori.class i check android monitor and context is error?

          • Gururaj P Kharvi

            June 29, 2016 at 4:14 pm

            Oh! sorry, I made mistake there in toast. Please change context to this and also putextras in adapter class to putextra.

          • oh nice this is work!… and now how to implement with my php.file?
            in my table wisata ther is NamaWisata, NamaKategori and infoWisata.. and then i wanna catch namaKategori in my adapter and send namaKategori to in my kategori.class selected database by namaKategori…

          • Gururaj P Kharvi

            June 29, 2016 at 4:55 pm

            In your onClick method add below code.

            
            DataKategori currentItem = data.get(getPosition());
            Intent i = new Intent(context,Kategori.class);
            i.putExtra("label1", currentItem.label1);
            context.startActivity(i);

            Add this below code into onCreate() method of your Kategori.class.

            String label1='';
            Bundle extras = getIntent().getExtras();
            if (label1 != null) { label1 = extras.getString("label1"); }
            Toast.makeText(this, label1.toString(), Toast.LENGTH_LONG).show();

            hope you get correct output.

          • im try change “work!” to current.namaKategori to catch NamaKategori in my database.. and work it..

          • hmm.. i use this to get output in namaKategori

            String kode = current.namaKategori;
            Intent i = new Intent(context,Kategori.class);
            i.putExtra(“Test”, kode);
            context.startActivity(i);

            and me get value in label1… label1 me setText to current.namaKategori see public void onBindViewHolder in my adaptor

          • this is work it to get correct output in namaKategori

          • Gururaj P Kharvi

            June 30, 2016 at 7:41 am

            I din’t get your question please explain clearly.

          • sorry gururaj.. my bad :(..
            i wanna show table wisata in kategori.class by namaKategori..
            i confused to tell it… hope you understand what i mean..

          • hmm.. i mean selected by namaKategori in my database..
            example query “select *from wisata where namaKategori = ‘Test'”..
            Test is Test in onclick in my adaptor… how to make php file it?

          • Gururaj P Kharvi

            June 30, 2016 at 5:18 pm

            I assume that your field in table as ‘label1’ and written following code.

            <?php
            
                 if(isset($_POST['label1']))
                 {
                 	  require_once('config.inc.php');
            	  $label1=$_POST['label1'];
                      $sql = 'SELECT * from wisata where label1=:label1';
                      $statement = $connection->prepare($sql);
            	  $statement->bindParam(':label1', $label1, PDO::PARAM_STR);
                      $statement->execute();
                      if($statement->rowCount())
                      {
            	    $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
            	    header('Content-type: application/json');
               	    echo json_encode($row_all);
                      }  
                      elseif(!$statement->rowCount())
                      {
            	    echo "no rows";
                      }
                 }
            		  
            ?>
            
          • hmm.. i trying and fail T.T
            how to use $_GET in php.file? no use $_POST?

          • Gururaj P Kharvi

            June 30, 2016 at 6:49 pm

            Replace $_POST as $_GET in all your statement. Please test your php file with browser before testing in your phone.

          • i test with browser is work.. if i testing in my phone is not work?
            is there something wrong in my kategori.java?

          • Gururaj P Kharvi

            July 1, 2016 at 4:47 am

            Display toast message in onPostExecute() to see whether you get data or not. If error then let me have some screenshots please.

          • Gururaj P Kharvi

            July 1, 2016 at 5:22 am

            I redefined your Kategori.class and wisata2.php. Please find it in your mail inbox.

          • hmm sorry.. me following your code and then not work..
            if i click onclick, message toast work but database not show..
            “org.Json.JSONException : END of input at character 0 of” :((

          • Gururaj P Kharvi

            July 1, 2016 at 4:56 pm

            Your PHP file not returning any data(JSON array) so you are getting JSON Exception while processing. I request you please check your PHP file in a browser or display Toast message like this in your onPostExecute() method of Kategori.class to see what data is returned from PHP.

            Toast.makeText(Kategori.this, "Data Returned from PHP: " + result.toString(), Toast.LENGTH_LONG).show();
          • if i change php.file like a
            <?php

             
                  require_once(‘config.inc.php’);
            $Test=’Wisata Alam’
                      $sql = ‘SELECT * from wisata WHERE NamaKategori = :Test’;
                      $statement = $connection->prepare($sql);
            $statement->bindParam(‘:Test’, $Test, PDO::PARAM_STR);
                      $statement->execute();
                      if($statement->rowCount())
                      {
            $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
            header(‘Content-type: application/json’);
                echo json_encode($row_all);
                      }
                      elseif(!$statement->rowCount())
                      {
            echo “no rows”;
                      }
                
            ?>

            and test in my browser and then error “Parse error: syntax error, unexpected ‘$sql’ (T_VARIABLE) in C:\xampp\htdocs\Android\wisatakategori.php on line 6”

            i want try give toast message in onPostExecute()..

          • Gururaj P Kharvi

            July 2, 2016 at 4:57 am

            You missed semicolon in $Test='Wisata Alam'.

          • me try display Toast message in onPostExecute.. maybe data is not returned.. because if me click, message only show “Data Returned from PHP: “

          • maybe php file cannot work with space..
            if url me change is url = new URL(“http://192.168.1.3/Android/wisatakategori.php?Test=Wisata Alam”); this cannot show data,
            and if changed url to url = new URL(“http://192.168.1.3/Android/wisatakategori.php?Test=Wisata%20Alam”); data can show by “Wisata Alam”.. how to fix it master?

          • Gururaj P Kharvi

            July 2, 2016 at 5:06 am

            Embedding parameter along with URL is not works in android, you need to embed parameter from your code using Uri.Builder and it’s method appendQueryParameter()(I already done this with code i sent to you before).

          • so what wrong master? please help me… me already follow your kode, and always “END of input at character 0 of” I am so confused T.T.. i use this tutorial to my search and work.. but if i use to onclick and then failed T.T

          • Gururaj P Kharvi

            July 2, 2016 at 5:35 pm

            In your PHP return GET data say return($_GET('Test')); and print toast in your onPostExecute() method to see whether you are able to get test value.

          • BTW how to make setClickListener in my adaptor? maybe something wrong is there??

          • where i put return($_GET(‘Test’)); in my php ?

          • Gururaj P Kharvi

            July 3, 2016 at 6:05 am

            In your PHP file. Remove all code from your PHP just put return($_GET(‘Test’)); to see the value sent from Android is recieved or not.

          • sorry master, value in Test cannot send to my php
            toast in result “Data Returned from PHP: return($_GET(‘Test’)); ”
            T.T

          • Gururaj P Kharvi

            July 5, 2016 at 12:51 am

            You have problem in sending data from android to PHP. Please send your kategori.class file.

          • i make kategori.class like a you in top comment master..

          • Gururaj P Kharvi

            July 5, 2016 at 8:27 am

            There may be minor mistakes in your PHP or Java file. Please, let me have Kategori.class and wisata2.php both to analyze it further.

          • master.. i change GET to POST in my kategori.class and php file, and work master.. thank you so much gururaj…and once again Thanks you so much master :))

  8. Gururaj,

    Can you confirm something for me if possible?

    Let’s say your database contained text that had accents in fish_name (ie: José or jessé) do you get an error? I have about 1000 records, any record I search without an accent displays fine. However, when I search for a record that has an accent I get the following “org.json.jsonexception end of input at character 0 of”.

    Thanks.

    • Yes, if your query result contains accents then json_encode($result) output will be blank so you are getting json exception. To solve this you need to encode(utf8) rows which contains accents.

      I altered PHP code $row_all = $statement->fetchall(PDO::FETCH_ASSOC); as

          while($row=$statement->fetch(PDO::FETCH_ASSOC))
          {
          	$row_all[]=array_map("utf8_encode", $row);
          }
      

      In above code i encoded all rows. you may encode particular row which contains accent character.

      Now, it works fine but, when you search for 'José' you'll get empty result set. here is a fix for that.

      1. You need to decode POST data coming from android with utf8.

        $search_query=utf8_decode($_POST['searchQuery']);
      2. Your query should go like this.

        $sql = 'SELECT * from tbl_fish where MATCH(fish_name,size_name,cat_name) AGAINST(CONVERT(:search_query USING utf8))';

      Here is the screenshot of tested results.

      Android accent text with PHP and MySQL

  9. Thanks Gururaj.

    The only part I modified was:

    while($row=$statement->fetch(PDO::FETCH_ASSOC))
    {
    $row_all[]=array_map(“utf8_encode”, $row);
    }

    The remainder I kept the same as it worked with the accents in my testing environment.

  10. Hi Gururaj,

    Something that I’ve spotted and wondering if you can give your input please.

    In my searchable.xml under “res -> xml” I have the following:

    Yet whenever I launch the app and go to my Search activity I still see “Search…”

    My AndroidManifest.xml looks like this:

    • What i understand from your question is, you are trying to change hint text or placeholder text of search box. If so, Adding below code inside if (searchView != null) block may solve your problem.

      searchView.setQueryHint("What is your wish today...");

      • Gururaj,

        Thank you for 1) removing my previous comments, I did not want spam on the comments section and 2) for the answer. It worked like a charm.

  11. Hi sir,
    I have done this successfully!! May I know how can I implement this searchview tutorial into the listview activity that I have created in my project? Thanks!

    • @janet

      Define the string arraylist.

      ArrayList<String> dataList = new ArrayList<String>();

      while JSON parsing add your item to ArrayList like this

      dataList.add(json_data.getString("fish_name"));

      Convert ArrayList to String Array and finally, populate your ListView by setting adapter.

      String [] dataArray = dataList.toArray(new String[dataList.size()]);
      ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1, android.R.id.text1, dataArray);
      ListView listView = (ListView) findViewById(R.id.fishPriceList);
      listView.setAdapter(adapter);
      
  12. Hello master,

    I already add and blob image in mysql, when I run in emulator, it show toast message error

    org.json.JSONException; End of input at character 0 of

    I really dont know how to find out code error.. Where should I add suitable code..
    Hope you can help me.

    • you are getting org.json.JSONException; End of input at character 0 error because your PHP file not returning anything. Test your PHP file in your browser whether its working correctly or not. Display data in Toast to see what exactly returning from PHP.

  13. thanks sir for such a great tutorial,,,,how can i create a searchview with outputs search suggestion below the searchview in real-time as the user types the word he wants to search..

  14. i dint your code exactly what you have posted but i get this error .. 🙁

    E/RecyclerView: No adapter attached; skipping layout.

    please help me buddy ..

    • You may be missing mRVFish.setAdapter(mAdapter); code inside your onPostExecute(String result) method of AsyncTask. Please re validate your MainActivity.java file. Make sure you also created FishAdapter.java file.

      Even after you are facing issue with running your code then please download project from GITHUB(tested project) and try to compare your code where exactly you missed something with your code.

      • im getting the same error even after copying the same code.
        even i made the table exactly like yours still problem arising.

        • Please check your php file in browser for correct output. What if php returns no data? Adapter don’t have any data to attach it right.

  15. Hi! thanks for wonderfull and understandable tutorial,sir i need to display item_id from database not from view position when doing onClick.failed to do that i need help from you or anyone reading this post,thanks in advance.

    • Follow below steps.

      1. In your DataFish.java define extra field public String item_id;
      2. Send item_id from your PHP file along with other parameters.
      3. In your MainActivity.java while JSON parsing inside for loop have a statement like fishData.item_id= json_data.getString("item_id");
      4. Finally, In your AdapterFish.java class’s onClick() method add below code(Added toast message to see item_id).
        DataFish currentItem = data.get(getPosition());
        Toast.makeText(context, currentItem.item_id, Toast.LENGTH_LONG).show();
      • Thank you sir,appreciated your assistance! God bless you,keep helping others like me to come the world of developers.thanks very much!

  16. I am Italian and I know little English.
    The program works very well with Android 6.0 API 23 but not with Android 4.2.2 APP 17.
    what minimum API to work? Why?
    Thank you

    • The AppCompatActivity and RecyclerView is supported in version 21 or above. In your dependencies, hope you added those two support library with version 21 or higher. If everything goes right then app should work with API level 15 or above.

      Further, if you not able to identify the issue then please send error message(logcat).

      [It works perfectly with android version 4.2.1 as i taken screenshots from it and set it as featured image on top]

      • It works perfectly with android version 4.2.2. My old device was not connected to the internet… sorry.
        I have another problem. I have worked with the downloaded program. Now I would like to make a new program.
        I opened a new project, copied the two layout files, the three java files, an XML file and directory, a menu file. Adding Dependencies, correct AndroidManifest.xml but the program does not work. Any suggestions?
        It appears no toast.
        Thank you!

        • Did you get any error?

          • No, not by any error.
            But in this new program open a new page for each test.
            In your app if the desired name is not in the DB returns all records. In my App I do not give any result. It seems that does not connect to DB.
            I will do further tests trying to figure out if I forgot something in the copy.
            Thank you.

          • found error.
            the error is in in AndroidManifest
            In APPLICATION

            in ACTIVITY

            Where I put them if MyActivity is not the main activity in my project?

          • Gururaj P Kharvi

            July 7, 2016 at 12:50 pm

            I din’t get your question properly.

          • Gururaj P Kharvi

            July 8, 2016 at 2:03 pm

            Hi Marco,

            Hope your problem solved, If not please define your problem with snippet of code so it will help me to solve your problem.

  17. how to make the search results to be on top of the current layout,help please

    • Try to add intent.addFlags(Intent.Intent.FLAG_ACTIVITY_SINGLE_TOP | FLAG_ACTIVITY_CLEAR_TOP); before launching your search activity.

    • i am implementing this search functionality in navigation drawer,help please results can not be displayed on top of current layout

      • By default launching activity will always be on top. I don’t know why you are not getting it on top. Try to launch blank activity from your drawer to see whether it appears on top or not.

  18. sir i have another option for launching a search activity on clicking the search-menu item,but it can’t post searchquery to php script to fetch data,i think the problem is my search activity is not defined in manifest application where a could declare the searchable meta.is there any way to do that sir,in simple way i can’t use this MainActivity as intent launched activity only works when it is a application launcher activity.

    • Read Android Search with Fragment post on StackOverFlow and let me know your opinion.

      • Sir,it seen to be possible to implement a working search-view using fragment,but very tedious work to be done and require intermediate level of a development technology,cause by default android search-view is configured to work with activity not fragment.thanks for your help i will keep learning until i succeed.if you get the alternatives continue to help me sir,have a nice day

        • May be true. Sure, i will give a try if i have time, with my busy schedule i can’t do anything now. Try to post your question on stackoverflow so that chances of getting answers are high(may be someone tried).

  19. hii, i get the message like this”org.json.jsonobject cannot be converted to jsonarray” when try search, can you resolve it”

  20. DataFish current;
    int currentPos=0; not using in your class Why?

  21. Why you cannot used encoding utf-8 unicode .I have more problem whith it(latin1).Sorry i speaking english a bit.

  22. Hello my friend, please I have a problem here; Example “Nétra” : I have an exception message : org.json.jsonException: End iput at character 0 of. Help me please

    • YEEEEEEEEEEES!!!!!!! i have find the solution with :
      while($row=$statement->fetch(PDO::FETCH_ASSOC))
      {
      $row_all[]=array_map(“utf8_encode”, $row);
      }

  23. my application with this error
    I tested the browser and works (GET) but no android (POST)
    http://pastebin.com/M5mcCTCm
    errors:
    https://drive.google.com/open?id=0B_vZ7c3vNCozc1VpX0JjemZYQ00

    • The JSON parsing code which is written in our article is to parse JSON Array but what you are returning from PHP is JSON object([..] is array and {...} is object), so you are getting error while parsing. Please refer this example.json file in Android JSON Parsing article.

      If you don’t want to pass JSON array(want to pass JSON object as in your screenshot) then you can alter above code by removing for loop and construct code accordingly. Let me know, if you find any difficulty in doing so.

  24. Hi, congratulations for the tutorial. I tried your code with my personal table “users” But when I go to do the research gives me the following error:
    org.json.JSONException: Value Connection of type.java.lang.String can not be converted to JSONArray

    in the Android logcat study he tells me: E / RecyclerView: No adapter attached; skipping layout

    the code is completely taken out of your tutorial, I only change the table entries.

    the fish-search.php file is as follows:

     if(isset($_POST['searchQuery']))
         {
         	  require_once('configdb.php');
    	  $search_query=$_POST['searchQuery'];
              $sql = 'SELECT * from utenti where MATCH(cognome,nome,paese,provincia) AGAINST(:search_query)';
              $statement = $connection->prepare($sql);
    	  $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
              $statement->execute();
              if($statement->rowCount())
              {
    	    $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
    	    header('Content-type: application/json');
       	    echo json_encode($row_all);
              }  
              elseif(!$statement->rowCount())
              {
    	    echo "no rows";
              }
         }
    

    why?

    • Your PHP file returning empty result or some string which is not in required JSON format. The reason may be you’re not added ‘FullText’ Index to your searchable fields in tables, Please refer my answer here. I recommend you to test your PHP file in browser before testing in your phone. Even after your problem not solved then let me know.

      • I made the changes you’ve asked me.
        The table in Mysql I selected fields of research in Fulltext.
        the search php files I changed to this:
        require_once (‘configdb.php’);
        $ Search_query = ‘roma’;
                   $ Sql = ‘SELECT * from users WHERE MATCH (name, first name, country, province) AGAINST (: search_query)’;
                   $ Statement = $ connection-> prepare ($ sql);
        $ Statement-> BindParam (‘: search_query’, $ search_query, PDO :: PARAM_STR);
                   $ Statement-> execute ();
                   if ($ statement-> rowCount ())
                   {
        $ Row_all = $ statement-> fetchall (PDO :: FETCH_ASSOC);
        header (‘Content-type: application / json’);
            echo json_encode ($ row_all);
                   }
                   elseif (! $ statement-> rowCount ())
                   {
        echo “no rows”;
                   }

        But it does not work the same

        Thank you

        • did you check this file with browser? let me know if any error or output.

          • the browser gives me blank page

          • I solved.
            in this line
            $ Sql = ‘SELECT * from users WHERE MATCH (name, first name, country, province) AGAINST (: search_query)’;
            I deleted leaving only a “country” field and it works

    • Same error org.json.JSONException: Value Connection of type.java.lang.String can not be converted to JSONArray.

  25. make a tutorial on how to save the item clicked in a local bank, please

  26. If the table are tbl_fish fits the latitude and longitude field, you can display the results on a map? And how?

  27. Hi Gururaj,
    Thanks for nice Article.

    I have an issue the example is running successfully individually, when i am using with multiple activity then output is not showing.
    i mean option for android:launchMode=”singleTop”

    Please suggest me,
    Thanks
    Krrish,

  28. Hello, clicking on an item in the ListView I want to display another screen with the selected data of the item (and you should pass the id). How can I do?
    Thank you

    • In your onClick(View v) method of MyHolder class add below code.

      if(getPosition()==0)
      {
      // Clicked on first item 
      
      }else if(getPosition()==1)
      {
        // Clicked on second item 
      } and so on...
  29. hi sir I’m having a problem to what folder do I put the searchable.xml. And by the way sir I have this project and Im kinda noob since Im new in android do you know how to have a fragment activity that serves as a search activity, then passing the search output to a new fragment recyclerview?

    • This searchable.xml file must be placed inside res→xml resource directory as clearly specified in article under searchable.xml heading.

      • yup, i have fixed that sir but cant reply due to slow internet. Sir I have a problem, Why is the application opening the same activity when you click search

        • forgot to say sir, it creates the new activity but does’nt show results

          • Gururaj P Kharvi

            July 27, 2016 at 3:42 pm

            did you check your PHP file for correct JSON output? You may missing ‘full index’ to your searchable fields if so refer this comment. Please test your PHP file with browser to ensure proper data is returning.

          • sir I have fixed it, I just have a question if I were to separate the search functionality how can I achieve it here is the search interface that I have created.

  30. Want to add SearchView instead of TextView? or you want to perform search by using TextView?

  31. Sir how about if I just want to search for the fish_name only and disregard other searches like if ever there were a fish_name “medium” and a cat_name “medium” the only search query that will be posted are for the fish_name.

    • For that i think you need to have 3 separate queries for 3 fields, by doing so, you come to know in which query result the string found and handling it appropriately.

      • thanks for replying, Sir if you may which part of this should I change, cost I get an error in changing the “*” and also the (bookTitle,bookAuthor,bookPublisher). I believe this is the part of the code that I need to change for me to achieve specific searches, thanks guru in advance. This is your code that I alter it works well but I cant make it do the different types of search, I hope you can enlighten me.

        $sql = 'SELECT * from bookrecord where MATCH(bookTitle,bookAuthor,bookPublisher) AGAINST(:search_query)';
        • That’s what i suggested before. See

          • Send “button id” along with “search query” to PHP, say, when “title” button is clicked send ‘0’(for Author button ‘1’, for Publisher/keyword ‘2’, for Category ‘3).
          • In your PHP file, retrieve that button id and write query based on button click. I also included php scipt for your reference.
          
          < ?php
          
               if(isset($_POST['searchQuery']))
               {
               	  require_once('config.inc.php');
          	  $search_query=$_POST['searchQuery'];
                    $button_id=$_POST['buttonId'];/*you need to send this "button id" from android*/
                    if($button_id==0)
                    {
                      $sql = 'SELECT * from bookrecord where MATCH(bookTitle) AGAINST(:search_query)';
                    }else if($button_id==1)
                    {
                      $sql = 'SELECT * from bookrecord where MATCH(bookAuthor) AGAINST(:search_query)';
                    }else if($button_id==2)
                    {
                      $sql = 'SELECT * from bookrecord where MATCH(bookPublisher) AGAINST(:search_query)';
                    }else if($button_id==3)
                    {
                      $sql = 'SELECT * from bookrecord where MATCH(bookCategory) AGAINST(:search_query)';
                    }
                    $statement = $connection->prepare($sql);
          	  $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
                    $statement->execute();
                    if($statement->rowCount())
                    {
          	    $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
          	    header('Content-type: application/json');
             	    echo json_encode($row_all);
                    }  
                    elseif(!$statement->rowCount())
                    {
          	    echo "no rows";
                    }
               }
          		  
          ?>
          

          Please make sure you added ‘fulltext index’ to all 4 fields seperately(As in our example we added ‘fulltext index’ to group(3 fields together)).

          ALTER TABLE `bookrecord` ADD FULLTEXT INDEX `Index1` (`bookTitle`);
          ALTER TABLE `bookrecord` ADD FULLTEXT INDEX `Index2` (`bookAuthor`);
          ALTER TABLE `bookrecord` ADD FULLTEXT INDEX `Index3` (`bookPublisher`);
          ALTER TABLE `bookrecord` ADD FULLTEXT INDEX `Index4` (`bookCategory`);
          
          • I do thought that my error has something to do with the ALTER TABLE thing, sir thanks for this. I know, I maybe asking too much but can you fill me in with the codes in sending the button ID. Im very sorry sir as I don’t have much knowledge in this. If you may, ill lay down my logic but I think this is what you were saying.Could you tell me what codes in your program should I alter. I have 4 buttons title, keywords,etc this buttons are having codes that will open 4 different activities(they are your activities sir just having different button id’s in your code according in what button the user clicked) having the same code aside from their button ID’s. I do see in your code along with the AsyscTask the searchQuery but I dont know what to alter. I think I got a grasp in your php code. If you could only help me more,

          • Gururaj P Kharvi

            July 31, 2016 at 2:58 pm

            Pass your buttonId to Activity you are launching.

            Example: When user clicked on “Title” button pass TextView value and buttonId to your new Activity.

            
            // context refers to your current class
            Intent i = new Intent(context,NewActivity.class);
            i.putExtra("searchText", textView.text());
            i.putExtra("buttonId", "0");
            context.startActivity(i);
            

            and in your onCreate() method of NewActivity.class retrieve data like this and call AsyncTask class with parameter.

            
            String searchText='';
            String buttonId='';
            Bundle extras = getIntent().getExtras();
            if (searchText != null) { searchText= extras.getString("searchText"); }
            if (buttonId != null) { buttonId= extras.getString("buttonId"); }
            new AsyncFetch(searchText, buttonId).execute();
            

            finally, send those parameter to PHP file(mentioned above) from your AsyncTask.

  32. Sir I have added the code but not in inside the onCreate mehod, it gets errors there. I tried adding it outside along with the private static codes.

    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVBook;
    private AdapterBook mAdapter;

    //HERE SIR

    SearchView searchView = null;
    Bundle extras = getIntent().getExtras();//ADDED
    String ButtonId=””;//ADDED

    then in your onNewIntent I added the if statementS, but I dont really get what the “label 1” is for sir so didnt included the label 1, I added btnid in the newAsyncFetch, by the way sir the “query” contains the search string am I right? so am I right that im trying to pass here the ButtonId? should this be string or int?.

    // Every time when you press search button on keypad an Activity is recreated which in turn calls this function
    @Override
    protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
    String query = intent.getStringExtra(SearchManager.QUERY);
    String btnid= intent.getStringExtra(ButtonId);//my addition, though still wrong

    if (searchView != null) {
    searchView.clearFocus();
    }

    //ADDED
    if (ButtonId != null){
    extras.getString(“ButtonId”);
    }
    //ALTERED ADDED btnid
    new AsyncFetch(query,btnid).execute();

    }
    }

    I am not planning sir on having a separate textview activity for the search.I only plan on having a separate activity containing buttons like this my activity has 4 buttons title, categories, etc once the user clicks them they will be redirected to your activity sir passing the button id and still using your searchview to search. thanks sir for replying

  33. You are doing such a great job bro . You are working on completely unique topics which are not available on entire google.

  34. Hi GURURAJ P KHARVI,

    I wanted to use Search Page in Fragment instead of Activity. please guide me. Some of the code is not working in fragment.

    Thanks
    Krrish

  35. Hi Guru,
    When i am getting error when using Search in Fragment
    Error at @Override public boolean onCreateOptionsMenu(Menu menu)
    that “Method doesn’t override method from its Superclass”

    public class SearchEvent extends android.support.v4.app.Fragment {
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFish;
    private EventData mAdapter;
    SearchView searchView = null;
    private static final String ARG_PARAM1 = “param1”;
    private static final String ARG_PARAM2 = “param2”;
    private String mParam1;
    private String mParam2;
    private OnFragmentInteractionListener mListener;
    public static SearchEvent newInstance(String param1, String param2) {
    SearchEvent fragment = new SearchEvent();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
    }

    public SearchEvent() {
    // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    mParam1 = getArguments().getString(ARG_PARAM1);
    mParam2 = getArguments().getString(ARG_PARAM2);
    }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getActivity().getMenuInflater();
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
    searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
    searchView.setIconified(false);
    }
    return true;
    }

    please guide me.
    Thanks
    Krrish

  36. I did everything! but my php page is blank!! what do I do?
    I am using Amazon web services.
    This is my php code!

    
    <?php
              prepare($sql);
    	  $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
              $statement->execute();
              if($statement->rowCount())
              {
    	    $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
    	    header('Content-type: application/json');
       	    echo json_encode($row_all);
    		echo "elite";
              }  
              elseif(!$statement->rowCount())
              {
    	    echo "no rows";
              }
         }
    		  
    ?>
    
  37. Sir your php codes “fish-search” and “config.inc” works fine in my emulation here at my pc but when I uploaded it online it wont work what might be wrong my other codes for login are working just fine. Im using 000webhost free webhosting I hope you can tell me. thanks

    • Please check your url in browser and make sure you added proper url in android code and updated your ‘config.inc.php’ file with correct host, username, password(you can find all info in your 000webhost panel) and database name. If everything proper then you may not added ‘fulltext index’ to your table, please refer answer1 and answer2 in other comments.

  38. Hi, if instead of using the search using a field I wanted to do it with other fields like below how I can change your script (java and php)?

    Thank you

  39. I’m not enter the code.
    The fields with which to do the research are
    gender
    marital Status
    Profession
    City

    • you need to add ‘fulltext index’ to your table, please refer answer1 and answer2 in other comments.

      • I’ll explain.
        if I in the search form insert other fields (gender, marital status, profession, city)

        php file and add the line
        $ Sql = ‘SELECT * from users WHERE MATCH (gender, marital status, profession, city) AGAINST (: search_query)’;

        It also does research in those fields?

        • Yes, for that you need to add full text index in group. Refer MySQL section of article to see ‘how to add full text index to all three fields(in your case it is 5)’.

          • and xml part where you enter all fields how can I change it?

            now in MainActivity.java there is this part of the code that calls R.menu.search_main, menu (I have to do the research by opening a xml with the fields I need for research). How can I change it? How to connect the XML file to MainActivity.java?

            public boolean onCreateOptionsMenu (Menu menu) {

            // Adds item to the action bars
            getMenuInflater (). inflate (R.menu.search_main, menu);

            // Get the Search item from the action bars and Get Search service
            MenuItem searchItem = menu.findItem (R.id.action_search);
            SearchManager searchManager = (SearchManager) CercaActivity.this.getSystemService (Context.SEARCH_SERVICE);
            if (searchItem! = null) {
            SearchView = (SearchView) searchItem.getActionView ();
            }
            if (SearchView! = null) {
            searchView.setSearchableInfo(searchManager.getSearchableInfo(CercaActivity.this.getComponentName()));
            searchView.setIconified (false);
            }

            return true;
            }

            Thank you

  40. and xml part where you enter all fields how can I change it?

    now in MainActivity.java there is this part of the code that calls R.menu.search_main, menu (I have to do the research by opening a xml with the fields I need for research). How can I change it? How to connect the XML file to MainActivity.java?

    public boolean onCreateOptionsMenu (Menu menu) {

            // Adds item to the action bars
            getMenuInflater (). inflate (R.menu.search_main, menu);

            // Get the Search item from the action bars and Get Search service
            MenuItem searchItem = menu.findItem (R.id.action_search);
            SearchManager searchManager = (SearchManager) CercaActivity.this.getSystemService (Context.SEARCH_SERVICE);
            if (searchItem! = null) {
                SearchView = (SearchView) searchItem.getActionView ();
            }
            if (SearchView! = null) {
                searchView.setSearchableInfo(searchManager.getSearchableInfo(CercaActivity.this.getComponentName()));
                searchView.setIconified (false);
            }

            return true;
        }

    Thank you

  41. nice tutorial sir, when i start search menu, didn’t show anything just no result.

  42. Is there any solution instead of Alter -ing and using the FULLTEXT function to the table ? because the database is already created from the company that i’ve worked so I cant easily change the table settings.

  43. Nice tutorial, how can I make it to be suggesting from the server as I type in the search?
    So that as I typed, it will fetched suggestions from the server and display it so that user can just click on the suggested data?
    Thanks in advance!

  44. I have a problem…
    the problem is, “No adapter attached; skipping layout”
    I am exactly the same as your code.
    plz help me .
    my webpage is blank page

  45. can u help me that it cannot work
    the log cat showed that:
    E/RecyclerView: No adapter attached; skipping layout
    E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40d61a0

    should I add extra something?

  46. Hi Gururaj,
    Very Nice Articles, which is not available any where on google.
    I wanted to display details of fish after clicking on searched fish.
    please help me.

    Thanks
    Krishna

  47. Boa tarde Gururaj,

    Estou tomando isso quando faço a consulta.

    org.json.JSONException: OOPs valor do tipo java.lang.String não pode ser convertido para JSONArray

    Sabe o que pode estar acontecendo?

  48. Hi,
    I am not getting the json data when i excecute php file..I downloaded the source code from here.No error is displaying

  49. Ola Gururaj,

    Como implementar um OnClick na RecyclerView?

    Preciso clicar em um item e mostrar sua informações em outra tela.

  50. it says “No adapter attached; skipping layout”

  51. thanks a lot for this tutorial. How to check if URL is connecting?
    i try to put it in my desktop-http://10.0.0.2/desktop/fish-search.php
    i tried in my WWW folder of my xamp but nothing is shown!
    by the way- the my SQL server is creating fine with your table (tbl_fish)

  52. Hey my search menu icon not listening to clicks. Nothing happening

  53. Haii Gururaj, i have a simple question for you, but its so difficult for me. The question is, how i can change the color of textview if (sample) the size name is middle then the color is red, or when the size name is small then the color of textview is green. Can you help me?

  54. hi sir! When I ran your codes in my genymotion emulator, when I clicked the application, the application has stopped working and then when I checked the logcat this is what I found ( InputDispatcher: Application is not responding
    WindowManager: Input event dispatching timed out sending to application error reason: because the touched window has not finished processing the input events that were previously delivered to it.) what do you think is the problem and how can I solve it?

    I really hope you could help me

  55. Hi !
    I want to add search view in Relative layout instead of action bar. How to do that?

  56. Hi Sir,
    Can u tell me more about fish search algorithm? or can you give me a refrence book?

  57. Great Tutorial
    Possible use this search view function in this tutorial .
    (Android JSON Parsing and display with RecyclerView)

Leave a Reply

Your email address will not be published.

*

About | Policy | Disclaimer

Creative Commons LicenceUp ↑