How to add search option to Android Spinner? - android

I have a long list of data display in android spinner. So i want to add a search option to this spinner ? Can any one help me with a simple example code.. (I saw some answers regarding this but they are not sufficient)..
I am new to android and i know actually this is not the correct way. but i want to add this kind of option to the spinner. When you hit a letter on the search box , list of items are displayed in the spinner relevant to that letter. Thanks a lot.
public void search(View view){
cursor = db.rawQuery("SELECT * FROM tblRepTeritories WHERE RepCode like?",
new String[]{"%" + searchText.getText().toString() + "%"});
SimpleCursorAdapter adapter1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
cursor,
new String[] {"TeriCode"},
new int[] {android.R.id.text1});
adapter1.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
Spinner s1 = (Spinner) findViewById( R.id.spinner2 );
s1.setAdapter(adapter1);
}

Use TextWatcher and then call notifyDataSetChanged() on your adapter:
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
cursor = db.rawQuery("SELECT * FROM tblRepTeritories WHERE RepCode like?",
new String[] {"%" + searchText.getText().toString() + "%"});
adapter1.notifyDataSetChanged();
}
});

Related

add first element a default item to arraylist

here i have an array list
ArrayList<String> arrlist = new ArrayList<String>();
while (cursors.moveToNext()) {
arrlist.add((cursors.getString(cursors.getColumnIndex("location"))));
adapter1 = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drop_list_item,
arrlist);
autocompletetextview.setAdapter(adapter1);
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
prepareMyList();
}
private void prepareMyList() {
ArrayList<String> arrlist = new ArrayList<String>();
String selectQuerys = "select distinct location from tb_user where location like '%"+autoservice.getText().toString()+"%'";
SQLiteDatabase dbs = sq.getReadableDatabase();
Cursor cursors = dbs.rawQuery(selectQuerys, null);
while (cursors.moveToNext()) {
arrlist.add((cursors.getString(cursors.getColumnIndex("location"))));
adapter1 = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drop_list_item,
arrlist);
autoservice.setAdapter(adapter1);
}
}
#Override
public void afterTextChanged(Editable s) {
}
if i type 'a' in autocomplete textview all items stating with 'a' will come as suggestions, similarly for all other letters
my need is i need a default item "automatic" at first of suggestion eventhough we type any letter in autocomplete textview
It sounds like you need to add the automatically detected location before you loop through the cursor. Earlier on, I'm assuming in onCreate, it would be:
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("automatically detect");
while (cursors.moveToNext()) { //...
Then in prepareMyList:
private void prepareMyList() {
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("automatically detect");
String selectQuerys = //...
This should add "automatically detect" as the first item initially and when you search.
Note: You should consider moving some of your code out of your while loop to make it more efficient (and likely less buggy). You don't need to create a new ArrayAdapter or set the adapter every time through the loop. You can just do this one time after the loop ends. All you need in your loops is:
while (cursors.moveToNext()) {
arrlist.add((cursors.getString(cursors.getColumnIndex("location"))));
}
adapter1 = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drop_list_item,
arrlist);
autoservice.setAdapter(adapter1);
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("Default element");

AutoCompleteTextView adapter issue

I have an AutoCompleteTextView, and depending from the changes in it, it shows the dropdown list with the data from server. Via listener after changing every symbol I make request to the server and take some list.
After that I show that list in AutoCompleteTextView, in code I do it by this way:
List<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getJSONObject(i).getString("title"));
}
String[] cities = list.toArray(new String[list.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities);
AutoCompleteTextView my = (AutoCompleteTextView) myView;
my.setAdapter(adapter);
Problem is it oftenly shows only the first element of the list, and after long click it shows the full list. I don understand why its happening.
Sorry for the bad eng, thanks in advance! Also you could check the rest of the code below:
xml part:
<AutoCompleteTextView
android:id="#+id/from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp"
android:background="#drawable/td_inp"
android:hint="Откуда"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:textColor="#000"
android:textColorHint="#757575" />
AutoCompleteTextView and its listener in onCreate
tCityFrom = (AutoCompleteTextView) findViewById(R.id.from);
tCityFrom.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if(s.length() >= 2) load_city(ssid, s.toString(),tCityFrom);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
I assume you want to show AutoComplete suggestions according to what user types. You have to load data from server onTextChanged():
tCityFrom = (AutoCompleteTextView) findViewById(R.id.from);
tCityFrom.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) { }
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length() >= 2)
load_city(ssid, s.toString(),tCityFrom);
}
});
Then declare ArrayList and Adapter globally:
List<String> list;
ArrayAdapter<String> adapter;
In onCreate():
list = new ArrayList<String>();
adapter = new ArrayAdapter<String>(DistanceCalculation.this, R.layout.support_simple_spinner_dropdown_item, cities);
AutoCompleteTextView my = (AutoCompleteTextView) myView;
my.setAdapter(adapter);
Replace your first code snippet of load_city() with below code :
list.clear();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getJSONObject(i).getString("title"));
}
adapter.notifyDataSetChanged();
Hope this helps.

Android AutoCompleteTextView as ListView header

I'm trying to set an AutoCompleteTextView as a ListView header, but if I do so the autocomplete box never appears. The code for creating the auto complete view comes directly from the Hello, AutoComplete tutorial in googles docs. The COUNTRIES array also comes from there.
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myList = (ListView) findViewById(R.id.ResultList);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
TableLayout searchHeader = (TableLayout) layoutInflater.inflate(R.layout.search_header, null);
myList.addHeaderView(searchHeader, null, false);
final AutoCompleteTextView textView = (AutoCompleteTextView) myList.findViewById(R.id.edit);
ArrayAdapter<String> searchAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
textView.setAdapter(searchAdapter);
textView.setThreshold(1);
//Dummy data for listview.
String[] listContent = {
"test", "test", "test", "test",
"test", "test", "test", "test"
};
ArrayAdapter<String> adapter = new SearchResultAdapter(this, listContent);
myList.setAdapter(adapter);
}
As a test, I added a TextChangedListener to try and force show the dialog
textView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
textView.showDropDown();
}
});
The dialog appears but is closed almost instantly. I wonder if some kind of event bubbling from the list view is causing this?
This question regarding focus of EditText views within a ListView & some reading of the AutoCompleteTextView source helped me find the answer. Setting the order of focus on the ListView to afterDescendants allowed the dialog to be shown normally.
<ListView
android:id="#+id/ResultList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="50dip"
android:descendantFocusability="afterDescendants"
android:fadingEdge="none" >
</ListView>
use in your XML file with autocompletetextview may be it will help

How to implement search functionality in multiple row List view based on single row using text watcher in android

I implemented multiple row list view(4 rows in single item).i want to search only based on second row in my list view.i implemented search functionality using text watcher that is not working properly. please help me guys.Thanks in advance.
inputsearch = (EditText) findViewById(R.id.inputsearch);
lst = (ListView) findViewById(android.R.id.list);
lst.setBackgroundColor(Color.WHITE);
lst.setCacheColorHint(Color.WHITE);
SimpleAdapter adapter = new SimpleAdapter(this, mylistData,R.layout.simple_list_item2, row, new int[] { R.id.tv1,
R.id.tv2, R.id.tv3, R.id.tv4, R.id.tv5 });
lst.setAdapter(adapter);
inputsearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int start, int before,
int count) {
// String array_sort[]=new String[headlines.length];
adapter.getFilter().filter(cs);
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence cs, int start,
int before, int count) {
}
});

Android AutocompleteTextView suggestion to be indexed to listview

I'm creating an activity wherein there are textview/autocompletetextview, listview and a button. My autocompletetextview works well, but I want to index what I input in the textview to the listview and when the it is highlighted, I'd click the button and go to the corresponding activity.
Here's so far what I've done:
String[] classes = {
"Acornsquash",
"Almonds",
"Apples", }
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature( Window.FEATURE_LEFT_ICON );
setContentView(R.layout.nutritional_list);
setFeatureDrawableResource( Window.FEATURE_LEFT_ICON, R.drawable.nutrition32 );
//ArrayAdapter<String> adapter = new ArrayAdapter<String>( this,
// android.R.layout.simple_dropdown_item_1line, classes );
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_list_item, classes );
AutoCompleteTextView tv = ( AutoCompleteTextView ) findViewById ( R.id.txtSearcEngine );
tv.setThreshold( 3 );
tv.setAdapter( adapter );
tv.setTextColor( Color.BLACK );
lv = ( ListView ) findViewById(R.id.lvListSearch);
lv.setAdapter(new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, classes ) );
lv.setOnItemClickListener( this );
public void onItemClick( AdapterView<?> parent, View v, int position, long id ) {
lv.setSelection(position);
switch( position )
{
case 0:
Intent acorn = new Intent( Nutritional_List.this, AcornSquash.class );
startActivity( acorn );
break;
case 1:
Intent almonds = new Intent( Nutritional_List.this, Almonds.class );
startActivity( almonds );
break;
My problem is, I don't have a clue on how to index suggestion from autocompletetextview to listview. Any help? thanks.
Rewrite
I am posting two ways to accomplish what you want. I believe that first method is simpler to code and less confusing to use. The second method is the direct answer to your question.
Method 1
I find it curious that you are using an AutoCompleteTextView and a ListView when they both provide the same information. The AutoCompleteTextView has the advantage of filtering the selection based on the user's text, but you can remove the AutoCompleteTextView and Button by using adding simple EditText that filters the ListView itself.
EditText edit = (EditText) findViewById(R.id.edit);
edit.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
});
Where adapter is a class variable like lv, tv, etc. and is the adapter passed to lv:
adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, classes );
lv.setAdapter(adapter);
Method 2
To do what you asked about initially, first let's change classes to a more powerful ArrayList<String>:
ArrayList<String> classesList = new ArrayList<String>(Arrays.asList(classes));
...
public void onCreate() {
...
// Update both of your adapters!
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_list_item, classesList );
create a new class variable as int tvIndex = -1. We'll use it when we click an item from the AutoCompleteTextView:
tv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = ((TextView) v).getText().toString();
tvIndex = classesList.indexOf(text);
lv.setSelection(tvIndex);
}
});
If the user pushes the Button to proceed:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(tvIndex > -1)
lv.performItemClick(lv.getChildAt(tvIndex), tvIndex, tvIndex);
}
});
Hope that helps!

Categories

Resources