How To Add Search Functionality in ListView - android

how do i add Search Functionality in my android app?
i have a listview in which i want to add search functionality , i have the code but i dont know how do i integrate it properly with my app
here is the code -
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
and here is my java file
package com.Example.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView list1;
private String array[] = { "Iphone", "Tutorials", "Gallery", "Android",
"item 1", "item 2", "item3", "item 4", "item 1", "item 2", "item3", "item 4","item 1", "item 2", "item3", "item 4"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list1 = (ListView) findViewById(R.id.ListView01);
// By using setAdpater method in listview we an add string array in
// list.
list1.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, array));
list1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 1)
{
Intent myIntent = new Intent(getApplicationContext(),Baba.class);
startActivity(myIntent);
}
}
});
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stackFromBottom="true">
<EditText
android:id="#+id/inputSearch"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:hint="Search"
android:inputType="textVisiblePassword">
</EditText>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbarSize="5dp"
>
</ListView>
</LinearLayout>

Try the below
EditText inputSearch;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputSearch = (EditText) findViewById(R.id.inputSearch); // initialize edittext
list1 = (ListView) findViewById(R.id.ListView01);
adapter =new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array));
list1.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
list1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 1)
{
Intent myIntent = new Intent(getApplicationContext(),Baba.class);
startActivity(myIntent);
}
}
});
}
Initialize editText inputSearch in onCreate.
inputSearch = (EditText) findViewById(R.id.inputSearch); // initialize edittext
Initialize adapter
adapter =new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array));
Set the adapter op listview
list1.setAdapter(adapter);
This is where the search happens
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs); // filter based on input
}

Since you are using android's array adapter, you can use its getFilter() method too. So you just have to change minor things in your code.
Instead of setting array adapter like this
list1.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1, array));
Create a private variable outside of the methods
private ArrayAdapter adapter;
Then initialize and set it
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, array);
list1.setAdapter(adapter);
Now text changed method can call MainActivity.this.adapter.getFilter().filter(cs); without any problem

Related

How to insert a filter in my EditText in a ListView to filter my Database

I have a ListView with an EditText to prompt a simple query making a select in my database, and i need to implements this query in my TextWatcher {... but I don't know how to do that any ideas ??
And I need to query two columns in one table...
public class ListaMateriais extends Activity {
private ListView listamateriais;
ArrayAdapter<String> adapMatchMaterial;
EditText inputSearch;
public EditText ETclient;
ArrayList<HashMap<String, String>> productList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_material_match);
String products[] = { "Parafuso 3x4 092387",
"Cabeçote redpo 09873",
"alavanca de ignição 027625",
"Pistão de arranque 093298092",
"Eixo dianteiro 0343232",
"Cabeçote parafuseta 093232" };
listamateriais = (ListView) findViewById(R.id.list_match_material);
adapMatchMaterial = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
listamateriais.setAdapter(adapMatchMaterial);
listamateriais.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
String text= (String) arg0.getItemAtPosition(position);
Bundle bundle = new Bundle();
bundle.putString("TextMateriais", text);
Intent int_material = new Intent(ListaMateriais.this,Formulario_ItemNota.class);
int_material.putExtras(bundle);
startActivity(int_material);
finish();
}
});
inputSearch = (EditText) findViewById(R.id.materialSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
ListaMateriais.this.adapMatchMaterial.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
}
});
}
Any helps will be truly appreciated... Thanks
you need to create a custom adpater that will extends Filter,
try this tutorial:
http://www.survivingwithandroid.com/2012/10/android-listview-custom-filter-and.html
Then in performFiltering, you can query the database to get the data and refresh you list.
ArrayList<String> mArrayList = new ArrayList<String>();
for(mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor.moveToNext()) {
// The Cursor is now set to the right position
mArrayList.add(mCursor.getString(COLUMN_INDEX_YOU_WANT));
}
Use AutoCompleteTextView
AutoCompleteTextView atxtSearch = (AutoCompleteTextView) findViewById(R.id.atxtSearchUser);
atxtSearch.setThreshold(3);
ArrayAdapter<String> adapMatchMaterial = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,products); //products should be an array
atxtSearch.setAdapter(adapMatchMaterial );
Then When you type on this edit text, after typing 3 letters, it will automatically list the items

How can I use OnListItemClickListener using this Search Filtering ListView

I'm having trouble using setOnItemClickListener in my listview. Everytime I try, it causes too many errors with fixes that makes the code worse than what I'm intending to do.
This is my code:
public class Search extends Activity{
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
// Listview Data
final String products[] = {"Fill in the Blocks", "The Music Bee", "Little Paragon",
"Subway Surfers", "Cytus", "Temple Run", "Clumsy Ninja", "Smash Hit"};
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Search.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
I want to make the strings in the listview data clickable for my other activities but it won't work. I tried this code:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String openClass = adapter.getItem[position];
if (openClass.equals("Fill in the Blocks")) {
Intent myIntent = new Intent(view.getContext(), Fill_in_the_Blocks.class);
startActivityForResult(myIntent, 0);
}
else if (openClass.equals("The Music Bee")) {
Intent myIntent1 = new Intent(view.getContext(), The_Music_Bee.class);
startActivityForResult(myIntent1, 0);
}
else if (openClass.equals("Little Paragon")) {
Intent myIntent2 = new Intent(view.getContext(), Little_Paragon.class);
startActivityForResult(myIntent2, 0);
}
}
The errors were as follows:
-In the lv.setOnItemClickListener, "The method setOnItemClickListener(AdapterView.OnItemClickListener) in the type AdapterView is not applicable for the arguments (new OnItemClickListener(){})"
-In the (new OnItemClickListener(), "OnItemClickListener cannot be resolved to a type"
-In the public void onItemClick(AdapterView, "AdapterView cannot be resolved to a type"
-In the String openClass = adapter.getItem[position];, "getItem cannot be resolved or is not a field"
In the lv.setOnItemClickListener, "The method setOnItemClickListener(AdapterView.OnItemClickListener) in the type AdapterView is not applicable for the arguments (new OnItemClickListener(){})"
In the (new OnItemClickListener(), "OnItemClickListener cannot be resolved to a type"
In the public void onItemClick(AdapterView, "AdapterView cannot be resolved to a type"
The first 3 errors should disappear by replacing new OnItemClickListener() with
new AdapterView.OnItemClickListener()
and make sure you import:
import android.widget.AdapterView;
The final error:
In the String openClass = adapter.getItem[position];, "getItem cannot be resolved or is not a field"
You are meant to be calling the getItem method, rather than using array indexing.
replace the line:
String openClass = adapter.getItem[position];
with
String openClass = adapter.getItem(position);

Display one array value according to other array

I have created to arrays.One is for all the states(Full Form) in USA and other is the all short form of the states in USA.I have dispayed the states(Full form) in a spinner.Now what i have to do is display the state in short form according to which the user selects in the spinner.How can i achieve it.
You should use mapping i.e in both the arrays the elements should be mapped. Let me give you an example.
String[] fullForm = { Alabama, California, Florida, Illinois};
String[] shortForm = {AL, CA, FL, IL};
ArrayAdapter<String> ad = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,fullForm );
spinner.setAdapter(ad);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), " You selected " + fullForm[position] + "\n Short form is : " + shortForm[position], Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// try this way,hope this will help you...
**activity_main.xml**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Spinner
android:id="#+id/spnState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
**MainActivity.java**
public class MainActivity extends Activity {
Spinner spnState;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.activity_main);
spnState = (Spinner) findViewById(R.id.spnState);
String[] stateFullNameArray = new String[]{"statefullname1","statefullname2","statefullname3","statefullname4","statefullname5"};
final String[] stateShortNameArray = new String[]{"stateshortname1","stateshortname2","stateshortname3","stateshortname4","stateshortname5"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,stateFullNameArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnState.setAdapter(adapter);
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,stateShortNameArray[position],Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}

Related spinners Android

I'm begginer in android. I'm working on a project. But i get very difficult to do two spinners related to each others. Actually one spinner for the country and another for the city. Instead of the country that is chosen the second spinner will show the cities.
I'v used "OnItemSelectedListener" but the " ArrayAdapter.createFromResourc​e " can't be used inside OnItemSelectedListener.
I've tried a lot of other ways but still none of them working.
Can anybody help me Please???
(P.S. I have read and tried the other posts about this topic but it still doesn't work )
This is the code:
spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
int spinnerId = spinner.getSelectedItemPosition();
if (spinnerId==0){
adaptert = ArrayAdapter.createFromResource(
this, R.array.tirana, android.R.layout.simple_spinner_item);
adaptert.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
else if (spinnerId==1) {
adaptert = ArrayAdapter.createFromResource(
this, R.array.durres, android.R.layout.simple_spinner_item);
adaptert.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
spinnert.setAdapter(adaptert);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
public class AdapterViewImplementation extends Activity implements OnItemSelectedListener{
Spinner sp1; // One Spinner
Spinner sp2; // Another Spinner
ArrayAdapter stateAdapter; // Adapter for state
ArrayAdapter cityAdapter; // Adapter for city
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sp1 = (Spinner)findViewById(R.id.Spinner01);
sp2 = (Spinner)findViewById(R.id.Spinner02);
stateAdapter = ArrayAdapter.createFromResource(AdapterViewImplementation.this,
R.array.state, android.R.layout.simple_spinner_item);
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(stateAdapter);
sp1.setOnItemSelectedListener(AdapterViewImplementation.this);
cityAdapter = ArrayAdapter.createFromResource(AdapterViewImplementation.this,
R.array.city, android.R.layout.simple_spinner_item);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(cityAdapter);
sp2.setOnItemSelectedListener(AdapterViewImplementation.this);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(arg0 == sp1){
sp2.setSelection(arg2);
}else{
sp1.setSelection(arg2);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

Android Spinner getting selectedItem Value?

I have setup Spinner with the layout below, and I wanted to get the value of the item selected, not the displayed text. Where does one pull out the value? Also will this work for pulling out values the layout below? Or do I need some other way to setup (value, displayText) pair? So I guess I need to know how to set it up so it has a value and also how in onItemSelected I would pull the value?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:paddingLeft="12dip">
<Spinner
android:id="#+id/viewSpin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/some_values"
android:prompt="#array/some_names"/>
</LinearLayout>
You resolve the Spinner instance in your activity class with findViewById and set an OnItemSelectedListener on it. Since you are populating the Spinner with some kind of Adapter, use the items that you constructed the Adapter with and the position of the selected item as reported back in the third parameter of OnItemSelectedListener's onItemSelected method
http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onItemSelected%28android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long%29
I hope it will helpful to you.
Try this Code..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<String> list=new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
list.add("Item 5");
final String[] str={"Report 1","Report 2","Report 3","Report 4","Report 5"};
final Spinner sp1= (Spinner) findViewById(R.id.spinner1);
final Spinner sp2= (Spinner) findViewById(R.id.spinner2);
final Spinner sp3= (Spinner) findViewById(R.id.spinner3);
ArrayAdapter<String> adp1=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,list);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adp1);
ArrayAdapter<String> adp2=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,str);
adp2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adp2);
sp2.setSelection(adp2.getPosition("Report 3"));
ArrayAdapter<CharSequence> adp3=ArrayAdapter.createFromResource(this,
R.array.str2, android.R.layout.simple_spinner_item);
adp3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adp3);
sp1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
int pos1=position;
String str1=sp1.getSelectedItem().toString();
//Toast.makeText(getBaseContext(), list.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long id) {
// TODO Auto-generated method stub
int selected_item_position = arg2;
String selected_item=sp2.getSelectedItem().toString();
Toast.makeText(getBaseContext(), ""+selected_item_position, Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), selected_item, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp3.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
int pos1=position;
String str1=sp1.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}

Categories

Resources