DEVELOPMENT

Hey guys, today i'm going to share a code that depicts a quick way to perform a search functionality in android.

home android search android


The Table - For the current case i've used a table located on the server whose rows content will be searched by the user.

db android

build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.tut.tut_7_5"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets { main { res.srcDirs = ['src/main/res', 'src/main/res/xml'] } }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
   // compile 'com.android.support:appcompat-v7:22.2.0'
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.tut.tut_7_5" >

 <uses-permission android:name="android.permission.INTERNET" />

 <application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:theme="@style/CustomActionBarTheme"
 android:label="@string/app_name" >
 <activity
 android:name=".MainActivity"
 android:label="@string/app_name"
 >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 <meta-data
 android:name="android.app.default_searchable"
 android:value=".SearchableActivity" />
 </activity>
 <activity android:name=".SearchableActivity"
 android:launchMode="singleTop" >
 <intent-filter>
 <action android:name="android.intent.action.SEARCH" />
 </intent-filter>
 <meta-data android:name="android.app.searchable"
 android:resource="@xml/searchable"/>
 </activity>

 </application>

</manifest>

res/menu/menu_main.xml - For adding a Search View widget, paste the below highlighted line.
<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="com.example.tut.tut_7_5.MainActivity" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
android:showAsAction="always"/>
<item
android:id="@+id/menu_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView"
android:title="Search"/>
</menu>

res/xml/searchable.xml - To include a search functionality, we must have to create a searchable configuration. Searchable configuration explains how the SearchView behaves. This searchable configuration is defined in the given file(as below).
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
 android:label="@string/app_name"
 android:hint="@string/search_hint" >
</searchable>
res/layout/searchlist.xml - Our search result will be displayed using list, thus this file is a XML graphical layout of our listview item.
<?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="match_parent"
 android:orientation="vertical" >

 <TextView
 android:id="@+id/title1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>

 <TextView
 android:id="@+id/subtitle1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/title1"
 android:textSize="10dp" />
 
</RelativeLayout>
res/menu/menu_searchable.xml
<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="com.example.tut.tut_7_5.MainActivity">
 <item android:id="@+id/action_settings" 
 android:title="@string/action_settings"
 android:orderInCategory="100" 
 android:showAsAction="never" />
</menu>
res/layout/activity_main.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:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 android:paddingBottom="@dimen/activity_vertical_margin"
 tools:context="com.example.tut.tut_7_5.MainActivity">
</RelativeLayout>

res/layout/activity_searchable.xml - XML graphical layout for SearchableActivity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

 <TextView
 android:id="@+id/txtQuery"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
 <TextView
 android:id="@+id/nf"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
 <ProgressBar
 android:id="@+id/progressBar1"
 style="?android:attr/progressBarStyleSmall"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />
 <ListView
 android:id="@+id/list1"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
 </ListView>

</LinearLayout>

res/values/theme.xml - Custom theme for the application.
<?xml version="1.0" encoding="utf-8"?>
<resources>

 <style name="CustomActionBarTheme"
 parent="@android:style/Theme.Holo.Light.DarkActionBar">
 <item name="android:actionBarStyle">@style/MyActionBar</item>
 </style>

 <style name="MyActionBar"
 parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">

 </style>
</resources>
    
MainActivity.java
package com.example.tut.tut_7_5;

 import android.app.Activity;
 import android.app.SearchManager;
 import android.content.Context;
 import android.os.Bundle;
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
 import android.widget.SearchView;



public class MainActivity extends Activity {

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

 }
 @Override

 public boolean onCreateOptionsMenu(Menu menu) {
 MenuInflater inflater = getMenuInflater();
 inflater.inflate(R.menu.menu_main, menu);

 SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
 SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
 searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
 searchView.setIconifiedByDefault(false);

 return true;
 }
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 switch (item.getItemId()) {

 case R.id.action_settings:

 return true;
 default:
 return super.onOptionsItemSelected(item);
 }
 }

}
SearchableActivity.java
package com.example.tut.tut_7_5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SearchableActivity extends Activity {

 private TextView txtQuery;
 ProgressBar pb;
 ListView lstView;

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

 lstView = (ListView)findViewById(R.id.list1);

 ActionBar actionBar = getActionBar();

 actionBar.setDisplayHomeAsUpEnabled(true);
 pb=(ProgressBar)findViewById(R.id.progressBar1);
 txtQuery = (TextView) findViewById(R.id.txtQuery);
 handleIntent(getIntent());

 }

 @Override
 protected void onNewIntent(Intent intent) {
 setIntent(intent);
 handleIntent(intent);
 }


 private void handleIntent(Intent intent) {
 if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
 String query = intent.getStringExtra(SearchManager.QUERY);

 pb.setVisibility(View.VISIBLE);
 txtQuery.setText("Search Query: " + query);

  new ReadJSONFeedTask().execute("http://search.php?q="+query);//add url
 }
 }
 public String readJSONFeed(String URL) {
 StringBuilder stringBuilder = new StringBuilder();
 HttpClient client = new DefaultHttpClient();
 HttpGet httpGet = new HttpGet(URL);
 try {
 HttpResponse response = client.execute(httpGet);
 StatusLine statusLine = response.getStatusLine();
 int statusCode = statusLine.getStatusCode();
 if (statusCode == 200) {
 HttpEntity entity = response.getEntity();
 InputStream content = entity.getContent();
 BufferedReader reader = new BufferedReader(
 new InputStreamReader(content));
 String line;
 while ((line = reader.readLine()) != null) {
 stringBuilder.append(line);
 }
 } else {
 Log.e("JSON", "Failed to download file");
 }
 } catch (ClientProtocolException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 return stringBuilder.toString();
 }

 private class ReadJSONFeedTask extends AsyncTask<String, Integer, String> {
 ArrayList<Map<String, String>> arrlist = new ArrayList<Map<String, String>>();
 Map<String, String> m = null;

 protected String doInBackground(String... urls) {
 return readJSONFeed(urls[0]);
 }

 protected void onPostExecute(String result) {
 pb.setVisibility(View.GONE);

 try {

 JSONArray jsonArray = new JSONArray(result);

 for (int i = 0; i < jsonArray.length(); i++) {
 JSONObject jsonObject = jsonArray.getJSONObject(i);
 m = new HashMap<String, String>();
 m.put("title", jsonObject.getString("t"));
 m.put("subtitle", jsonObject.getString("s"));
 arrlist.add(m);

 }
 lstView.setAdapter(new SimpleAdapter(SearchableActivity.this, arrlist, R.layout.searchlist, new String[]{"title", "subtitle"}, new int[]{R.id.title1, R.id.subtitle1}));


 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 protected void onProgressUpdate(Integer... progress) {
 pb.setProgress(progress[0]);
 }
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 MenuInflater inflater = getMenuInflater();
 inflater.inflate(R.menu.menu_main, menu);

 SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
 SearchView searchView = (SearchView) menu.findItem(R.id.menu_search)
 .getActionView();
 searchView.setSearchableInfo(searchManager
 .getSearchableInfo(getComponentName()));

 return super.onCreateOptionsMenu(menu);
 }
}

search.php - Place this file on your server.
<?php
header('content-type: application/json; charset=utf-8');
$q=$_GET['q'];
$conn=mysql_connect("","","") or die("ERROR");
$db=mysql_select_db("",$conn) or die("ERROR");



$query="SELECT * from srch";
$result=mysql_query($query);
$num=mysql_numrows($result);

mysql_close();

$i=0; $temp="";
$s=0;
while($i<$num)
{ 
 $t = mysql_result($result,$i,'title');
 $s_t= mysql_result($result,$i,'subtitle');
 $lq=strtolower($q);
 $lt=strtolower($t); //changing the case of name to lower-case.
 $lst=strtolower($s_t);// changing the case of subtitle to lower-case.
 if (strpos($lt,$lq) !== false || strpos($lst,$lq) !== false) { 
 
 $arr[$s]['t']=$t;
 $arr[$s]['s']=$s_t; 
 $s++; 
 }
$i++; 
}
 echo json_encode($arr);
?>


Leave a Comment  
Download Code(53)





All rights reserved, the content is copyrighted to the author.

RELATED POST