Step 1 :
Make an android project named “AutoComplete”.
Step 2 :
Paste the following code in MainActivity.java file.
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
SuggestionAdapterNew adapter;
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_new);
txt = (TextView) findViewById(R.id.textView1);
}
/** Callback function */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Create an option menu from res/menu/items.xml */
getMenuInflater().inflate(R.menu.items, menu);
/** Get the action view of the menu item whose id is search */
View v = (View) menu.findItem(R.id.search).getActionView();
final AutoCompleteTextView acTextView = (AutoCompleteTextView) v
.findViewById(R.id.autoComplete);
acTextView.setAdapter(new SuggestionAdapter(this, acTextView.getText()
.toString()));
final String search = "";
ImageButton img = (ImageButton) v.findViewById(R.id.imageButton1);
img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String search = acTextView.getText().toString().trim();
Toast.makeText(getApplicationContext(), "Abc" + search,
Toast.LENGTH_SHORT).show();
txt.setText(search);
}
});
return super.onCreateOptionsMenu(menu);
}
}
Step 2 :
Paste the following code in activity_main_new.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"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView" />
</RelativeLayout>
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView" />
</RelativeLayout>
Step 3 :
Paste the following code in activity_main_new.xml file.
It will be the layout for your Action bar Search View
<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"
tools:context=".MainActivity" >
<AutoCompleteTextView
android:id="@+id/autoComplete"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/imageButton1"
android:ems="10"
android:hint="Search Videos"
android:popupBackground="#ffffff" >
<requestFocus />
</AutoCompleteTextView>
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/autoComplete"
android:layout_alignParentRight="true"
android:background="@null"
android:layout_alignParentTop="true"
android:src="@drawable/ic_action_search" />
</RelativeLayout>
Step 4:
Paste Following code into your menu file into res-->menu-->
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/search"
android:actionLayout="@layout/activity_main"
android:icon="@drawable/ic_action_search"
android:showAsAction="always|collapseActionView"
android:title="Search"/>
</menu>
Step 5:
Paste Following Code into Your jsonparse file
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonParse {
public JsonParse() {
}
public List<SuggestGetSet> getParseJsonWCF(String sName) {
List<SuggestGetSet> ListData = new ArrayList<SuggestGetSet>();
try {
String temp = sName.replace(" ", "%20");
URL js = new URL(
"10.0.2.2/autocompelete.php?title="
+ temp);
URLConnection jc = js.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(
jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject r = jsonArray.getJSONObject(i);
ListData.add(new SuggestGetSet(r.getString("id"), r
.getString("name")));
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return ListData;
}
}
Step 6:
Paste Following Code into Suggest get Set file
public class SuggestGetSet {
String id, name;
public SuggestGetSet(String id, String name) {
this.setId(id);
this.setName(name);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Step 7:
Paste Following Code into "SuggestionAdapter"
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.Filter;
public class SuggestionAdapter extends ArrayAdapter<String> {
protected static final String TAG = "SuggestionAdapter";
private List<String> suggestions;
public SuggestionAdapter(Activity context, String nameFilter) {
// super(context, R.layout.search_layout);
super(context, android.R.layout.simple_dropdown_item_1line);
suggestions = new ArrayList<String>();
}
@Override
public int getCount() {
return suggestions.size();
}
@Override
public String getItem(int index) {
return suggestions.get(index);
}
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
JsonParse jp = new JsonParse();
if (constraint != null) {
// A class that queries a web API, parses the data and
// returns an ArrayList<GoEuroGetSet>
List<SuggestGetSet> new_suggestions = jp
.getParseJsonWCF(constraint.toString());
suggestions.clear();
for (int i = 0; i < new_suggestions.size(); i++) {
suggestions.add(new_suggestions.get(i).getName());
}
// Now assign the values and count to the FilterResults
// object
filterResults.values = suggestions;
filterResults.count = suggestions.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence contraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}
SERVER SIDE
Now i am showing you php files with databse script and php Script
Step 1:
Create Database:
create table `countries` (
`id` int (255),
`name` varchar (765)
);
Step 2:
Insert some values
Step 3:
for autocomplete use that php file
<?php
include('db.php');
$myresult['results'] = array();
if (isset($_GET['name'])) {
$country_name = $_GET['name'];
$query3 = "SELECT * FROM countries where name like'$country_name%'";
$result3 = mysql_query($query3)or die(mysql_error());
while ($row3 = mysql_fetch_assoc($result3)) {
array_push($myresult['results'], $row3);
}
$myarray = array();
echo json_encode($myresult);
}
?>
Step 4:
Create a databse connection file
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'test';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct');
mysql_select_db($database,$conn) or die('Database Information is not correct');
?>
It will be the layout for your Action bar Search View
<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"
tools:context=".MainActivity" >
<AutoCompleteTextView
android:id="@+id/autoComplete"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/imageButton1"
android:ems="10"
android:hint="Search Videos"
android:popupBackground="#ffffff" >
<requestFocus />
</AutoCompleteTextView>
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/autoComplete"
android:layout_alignParentRight="true"
android:background="@null"
android:layout_alignParentTop="true"
android:src="@drawable/ic_action_search" />
</RelativeLayout>
Step 4:
Paste Following code into your menu file into res-->menu-->
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/search"
android:actionLayout="@layout/activity_main"
android:icon="@drawable/ic_action_search"
android:showAsAction="always|collapseActionView"
android:title="Search"/>
</menu>
Step 5:
Paste Following Code into Your jsonparse file
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonParse {
public JsonParse() {
}
public List<SuggestGetSet> getParseJsonWCF(String sName) {
List<SuggestGetSet> ListData = new ArrayList<SuggestGetSet>();
try {
String temp = sName.replace(" ", "%20");
URL js = new URL(
"10.0.2.2/autocompelete.php?title="
+ temp);
URLConnection jc = js.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(
jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject r = jsonArray.getJSONObject(i);
ListData.add(new SuggestGetSet(r.getString("id"), r
.getString("name")));
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return ListData;
}
}
Step 6:
Paste Following Code into Suggest get Set file
public class SuggestGetSet {
String id, name;
public SuggestGetSet(String id, String name) {
this.setId(id);
this.setName(name);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Step 7:
Paste Following Code into "SuggestionAdapter"
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.Filter;
public class SuggestionAdapter extends ArrayAdapter<String> {
protected static final String TAG = "SuggestionAdapter";
private List<String> suggestions;
public SuggestionAdapter(Activity context, String nameFilter) {
// super(context, R.layout.search_layout);
super(context, android.R.layout.simple_dropdown_item_1line);
suggestions = new ArrayList<String>();
}
@Override
public int getCount() {
return suggestions.size();
}
@Override
public String getItem(int index) {
return suggestions.get(index);
}
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
JsonParse jp = new JsonParse();
if (constraint != null) {
// A class that queries a web API, parses the data and
// returns an ArrayList<GoEuroGetSet>
List<SuggestGetSet> new_suggestions = jp
.getParseJsonWCF(constraint.toString());
suggestions.clear();
for (int i = 0; i < new_suggestions.size(); i++) {
suggestions.add(new_suggestions.get(i).getName());
}
// Now assign the values and count to the FilterResults
// object
filterResults.values = suggestions;
filterResults.count = suggestions.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence contraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}
SERVER SIDE
Now i am showing you php files with databse script and php Script
Step 1:
Create Database:
create table `countries` (
`id` int (255),
`name` varchar (765)
);
Step 2:
Insert some values
Step 3:
for autocomplete use that php file
<?php
include('db.php');
$myresult['results'] = array();
if (isset($_GET['name'])) {
$country_name = $_GET['name'];
$query3 = "SELECT * FROM countries where name like'$country_name%'";
$result3 = mysql_query($query3)or die(mysql_error());
while ($row3 = mysql_fetch_assoc($result3)) {
array_push($myresult['results'], $row3);
}
$myarray = array();
echo json_encode($myresult);
}
?>
Step 4:
Create a databse connection file
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'test';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct');
mysql_select_db($database,$conn) or die('Database Information is not correct');
?>
Tada And You Will get Your Desired out Put
http://androidprogrammingsolutions.blogspot.co.id/2015/02/autocomplete-using-json-and-mysql.html