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.
Related
I have a problem with EditText-fields in a listview. After i scroll some settings seem to be reset (selectAllOnFocus) and the selection cursor goes bananas.
I have a listview with a custom ArrayAdapter and a custom dataobject. In this case the object only holds one String (to simplify it).
My Activity
// adapter + content
List<ListviewObject> listViewContent = new ArrayList<ListviewObject>();
for(int i = 0; i < 50; i++) {
listViewContent.add(new ListviewObject("num: " + i));
}
adapter = new CustomListAdapter(AddNewPerson.this, R.layout.list_item, listViewContent);
// list
ListView mListView = (ListView)findViewById(R.id.sample_list);
mListView.setItemsCanFocus(true);
mListView.setAdapter(adapter);
My Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HolderObject holder = null;
if(convertView == null) {
convertView = mLayoutInflater.inflate(layoutResourceId, parent, false);
holder = new HolderObject();
holder.name = (TextView) convertView.findViewById(R.id.txt);
convertView.setTag(holder);
} else {
holder = (HolderObject) convertView.getTag();
}
holder.lvObject = items.get(position);
setNameTextChangeListener(holder);
// Retrieve the correct value
holder.name.setText(holder.lvObject.getName());
return convertView;
}
public static class HolderObject {
ListviewObject lvObject;
TextView name;
}
private void setNameTextChangeListener(final HolderObject holder) {
holder.name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Update the value
holder.lvObject.setName(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
To fix all the focusproblems I found in other threads I've set:
.setItemsCanFocus(true) on the listview
android:descendantFocusability="beforeDescendants" in the activity XML
android:windowSoftInputMode="adjustPan" in the manifest XML
Focussing and editing text works fine. When I scroll the correct values are held and all this seems to work fine.
Before I scroll and I click on some of the EditTexts this happens. (Last focused blurs, clicked one focuses, content is selected)
http://imgur.com/eeIKhCv
After I scroll down and up again, and do the same clicks as before, this happens.
http://imgur.com/75mjPc3
This is due to listView recycling mechanism. To know more about listview recycling mechanism you can refer this link
in your case you avoid the problem by storing a last focused editText and In getView set focus to only last stored integer and skip other position. hope this help you...
It's quite easy:
Declare a String[] to keep track each EditText's input inside the afterTextChanged() of "addTextChangedListener().
Becareful of the order:
viewHolder.editText.removeTextChangedListener(viewHolder.textWatcher);
viewHolder.textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
mInputs[position] = editable.toString(); //record input
viewHolder.editText.setSelection(viewHolder.editText.getText().length()); //set cursor to the end
}
};
viewHolder.editText.addTextChangedListener(viewHolder.textWatcher);
viewHolder.editText.setText(mInputs[position]);
Add android:windowSoftInputMode="adjustPan" to your Activity in AndroidManifest file.
Good luck!
I'm on an android project since September, and I've to deal with AutocompleteTextView.
I made my personnal ArrayAdapter to populate the dropdown suggestion list, it works, but act strangely.
When i select an item in the dropdown list, it replace the text in my textView by the selection (that's okay), but after this, reShow the Dropdown.
I want it to hide until the user type something else on the keyboard.
Here is a sample of my code :
private List<String> autocompleteAddress;
addressBox = (AutoCompleteTextView)findViewById(R.id.form_address_box);
autocompleteAdapterAddress = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, autocompleteAddress){
#Override
public Filter getFilter(){
Filter custom_filter = new Filter(){
#Override
protected FilterResults performFiltering(CharSequence constraint){
FilterResults filterResults = new FilterResults();
filterResults.values = autocompleteAddress;
filterResults.count = autocompleteAddress.size();
return filterResults;
}
#Override
protected void publishResults(CharSequence contraint, FilterResults results){
notifyDataSetChanged();
}
};
return custom_filter;
}
};
addressBox.setAdapter(autocompleteAdapterAddress);
addressBox.addTextChangedListener(new TextWatcher(){
#Override
public void onTextChanged(CharSequence s, int start, int before, int count){
//ac is an asynctask populating the suggestion list (autocompleteAddress)
GetGoogleAutocompletion ac = new GetGoogleAutocompletion();
ac.execute(addressBox.getText().toString());
}
#Override public void afterTextChanged(Editable s){}
#Override public void beforeTextChanged(CharSequence s, int start, int count, int after){}
});
addressBox.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// here i just store the autocompleted text in a String
}
});
I thought the setText() method would be call in onItemClick(), and I could have used dismissDropDown(), but as i overrided onItemClick(), I'm pretty sure it's not there.
So i really don't know neither where the setText() is called, nor how to avoid the display of the dropDown menu after a selection.
Thanks in advance!
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) {
}
});
I have a listView with about 30 items in it and have added a search function to it via an editText. When I type 'a' in the textfield everything that starts with an 'a' shows up on the list but when I type another letter the list disappears even tho the list contains an item with 'a' + the other letter i typed.
Another thing that confuses me is that there is an item in the list called IWU Trading and thats the only item I can search for, means that if I type 'I' + 'W' the item shows up in the listView. But if I type 'a' + 'r' an item that is named 'art' dosent show up.
My question(s).
How can I do to make this search function work?
Why does it act like it does?
My XML
<EditText
android:id="#+id/searchEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/selectCustomerTextView"
android:layout_marginTop="20dp"
android:hint="#string/typeToSearch"
android:ems="10"
android:imeOptions="actionDone"
android:inputType="textNoSuggestions"/>
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/nextButton"
android:layout_alignParentLeft="true"
android:layout_below="#+id/searchEditText"
android:choiceMode="singleChoice"
android:dividerHeight="5dp" >
</ListView>
My code:
private ArrayAdapter<Customer> _oldAdapter = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView(R.layout.activity_customer_pick);
EditText searchText = (EditText) findViewById(R.id.searchEditText);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
searchText.addTextChangedListener(filterTextWatcher);
_oldAdapter = _phoneDAL.BindValues(this);
listView.setAdapter(_oldAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String s = _oldAdapter.getItem(arg2).toString();
_listViewPostion = arg2;
Toast.makeText(CustomerPick.this, "Du valde: " + s, arg2).show();
}
});
}
The search method:
private TextWatcher filterTextWatcher = 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) {
ArrayAdapter<Customer> _adapter = new ArrayAdapter<Customer>(CustomerPick.this, android.R.layout.simple_list_item_single_choice, new ArrayList<Customer>());
ListView listView = (ListView) findViewById(R.id.list_view);
int textLength = s.length();
if(textLength == 0){
listView.setAdapter(_oldAdapter);
return;
}
for (int i = 0; i < listView.getAdapter().getCount(); i++)
{
String word = _oldAdapter.getItem(i).getCustName().toLowerCase();
if (textLength <= word.length())
{
if(s.toString().equalsIgnoreCase(word.substring(0, textLength)))
{
_adapter.add(_oldAdapter.getItem(i));
}
}
}
listView.setAdapter(_adapter);
}
};
}
My CustomerClass (private ArrayAdapter _oldAdapter = null;)
public class Customer {
private final int _custNumber;
private final String _custName;
public Customer(int custNumber, String custName){
_custNumber = custNumber;
_custName = custName;
}
public int getCustNumber() {
return _custNumber;
}
public String getCustName() {
return _custName;
}
#Override
public String toString(){
return _custName;
}
}
Solved the problem by adding:
ListView listView = (ListView) findViewById(R.id.list_view);
((Filterable) listView.getAdapter()).getFilter().filter(s);
into the afterTextChanged method of the TextWatcher(after reading Luksprog's comment).
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();
}
});