well i'm trying to update the autoCompleteTextview ArrayAdapter dynamiclly each time text changed by using TextWathcer.
every time text changed there is an http request in a new AsyncTask and in the callback from the async task (onPostExecute) i call clear() from the adapter and adding new items to him and then call notifyDataSetChanged.
Unfortunately the auto complete drop down is never shown..
please, where do i go worng?!
here is the code:
AutoCompleteTextView acCountry = (AutoCompleteTextView)layout.findViewById(R.id.autoComplete);
final ArrayAdapter<RMAutoComplete.ListItem> countriesAdapter = new ArrayAdapter<RMAutoComplete.ListItem>(this.context,android.R.layout.simple_dropdown_item_1line);
acCountry.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 1)
{
new AsyncTask<String, Void, List<RMAutoComplete.ListItem>>(){
#Override
protected List<ListItem> doInBackground(String... params) {
List<ListItem> l = null;
try {
l = location.getCountryData(params[0]);
} catch (Exception e) {
Log.e(TAG,"error when getCountryData",e);
}
return l;
}
#Override
protected void onPostExecute(List<ListItem> countries) {
countriesAdapter.clear();
if (countries != null)
for (ListItem listItem : countries) {
countriesAdapter.add(listItem);
}
countriesAdapter.notifyDataSetChanged();
}
}.execute(s.toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
}
);
Common mistake : Did you set the adapter to acCountry at all?
Related
Recylerview
#Override
public void onBindViewHolder(#NonNull CustomListview.ViewHolder holder, int position) {
holder.Sno.setText(""+(position+1));
//remove colth unwanted characters
String cloth = list.get(position).getCloth();
String withoutFirstCharacter = cloth.substring(2,cloth.length()-1); // index starts at zero
holder.Cloth.setText(""+withoutFirstCharacter);
holder.qty.setText(list.get(position).getQuantity());
holder.QtyId.setText(list.get(position).getQtyId());
holder.Dis.setText(list.get(position).getDispatchedQty());
holder.deliverd is a edittext
if (list.get(position).getValue()==null){
holder.deliverd.setText("0");
list.get(position).setValue("0");
} else {
holder.deliverd.setText(String.valueOf(list.get(position).getValue()));
}
holder.deliverd.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (TextUtils.isEmpty(holder.deliverd.getText()))
{
list.get(position).setValue("0");
} else {
list.get(position).setValue(holder.deliverd.getText().toString());
}
int a = Integer.parseInt(list.get(position).getValue());
//str is arraylist
str.add(Integer.parseInt(list.get(position).getValue()));
Log.i( "str",String.valueOf(str));
//interface through pass the values to mainactivity
dtInterface.onSetValues(str);
// activity.array_val();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
Interface
public interface DataTransferInterface {
public void onSetValues(ArrayList<Integer> in );
}
MAinactivity interface implements and override the interface method
#Override
public void onSetValues(ArrayList<Integer> a )
{
HashMap<Integer, ArrayList<Integer>> hm=new HashMap<>();
hm.put(100,a);
//display hashmap element
Set s = hm.entrySet();
Iterator itr = s.iterator();
while (itr.hasNext()){
Map.Entry m = (Map.Entry)itr.next();
System.out.println(m.getKey()+":values:"+m.getValue());
Toast.makeText(this, "aaa"+m.getValue(),Toast.LENGTH_SHORT).show();
}
}
when i change the 1st,2nd,3rd edittext are correctly fetched the values one time. The problem is 4th,5th,etc edittext repeating the values 2 times and added to the arraylist. how to slove it.i tried more than 25days.. i attached the error below.
[![enter image description here][1]][1]
[enter link description here][1]
https://andriodretrofit.000webhostapp.com/WhatsAppVideo2020-02-03at83032PM.gif
I want the listView to be displayed only when a search string is inserted in the EditText. Below is my code...Please help me I would be highly obliged...
public class MainActivity extends AppCompatActivity {
private ListView mSearchNFilterLv;
private EditText mSearchEdt;
private ArrayList<String> mStringList;
private ValueAdapter valueAdapter;
private TextWatcher mSearchTw;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
initData();
valueAdapter = new ValueAdapter(mStringList, this);
mSearchNFilterLv.setAdapter(valueAdapter);
mSearchEdt.addTextChangedListener(mSearchTw);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void initData() {
mStringList = new ArrayList<String>();
mStringList.add("one");
mStringList.add("two");
mStringList.add("three");
mStringList.add("four");
mStringList.add("five");
mStringList.add("six");
mStringList.add("seven");
mStringList.add("eight");
mStringList.add("nine");
mStringList.add("ten");
mStringList.add("eleven");
mStringList.add("twelve");
mStringList.add("thirteen");
mStringList.add("fourteen");
mSearchTw = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
valueAdapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
if(mSearchEdt.getVisibility() != View.VISIBLE)
mSearchEdt.setVisibility(View.VISIBLE);
}
};
}
private void initUI() {
mSearchNFilterLv = (ListView) findViewById(R.id.list_view);
mSearchEdt = (EditText) findViewById(R.id.txt_search);
}
}
You can use the code below:
mSearchTw = new TextWatcher() {
#Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s != null && s.toString().trim().length() > 0) {
mSearchNFilterLv.setVisibility(View.VISIBLE);
} else {
mSearchNFilterLv.setVisibility(View.GONE);
}
}
#Override public void afterTextChanged(Editable s) {
}
};
This will show the ListView when there is an entered text (while entering text to EditText) and if text has 1 or more characters.
If you want ListView to be changed only when the insertion is over move the given code inside onTextChanged to afterTextChanged
PS: You can use the same structure with SearchView instead of EditText with query listeners.
Updated
You can use below code to hide ListView initially:
private void initUI() {
mSearchNFilterLv = (ListView) findViewById(R.id.list_view);
mSearchEdt = (EditText) findViewById(R.id.txt_search);
mSearchNFilterLv.setVisibility(View.GONE);
}
I have a AutoCompleteTextView and ProgressBar right of it and visibility of ProgressBar is invisible at beginning.
I am setting adapter to AutocompleteTextView in onCreate of my activity with custom class PlacesAutoCompleteAdapter and xml file autocomplete which contains the TextView,
actvFrom.setAdapter(new PlacesAutoCompleteAdapter(this,
R.layout.autocomplete));
In PlacesAutocompleteAdapter class i am implementing Filterable interface.
private class PlacesAutoCompleteAdapter extends ArrayAdapter<String>
implements Filterable {
private ArrayList<String> resultList;
public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public android.widget.Filter getFilter() {
android.widget.Filter filter = new android.widget.Filter() {
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// TODO Auto-generated method stub
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(
final CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
// TODO Auto-generated method stub
resultList = autocomplete_fill_data(constraint
.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
};
return filter;
}
}
In autocomplete_fill_data function i am doing call to the server and adding it to ArrayList myCollection and returning it.
public ArrayList<String> autocomplete_fill_data(String value) {
myCollection = new ArrayList<String>();
// call to server
...
myCollection.add(result);
return myCollection;
}
AutoComplete is working fine but the problem is i am not able to show the ProgressBar whenever there is call to server.
I tried all this,
Using addTextChangedListener
autocomplete.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
if (s.length() >= 1) {
System.out.println("Count ="+count);
progressBar.setVisibility(View.VISIBLE);
} else {
progressBar.setVisibility(View.INVISIBLE);
}
}
But Problem with this is even though you stopped typing text the progressBar will be still rotating. I wanted to hide the ProgressBar as soon as the user stops writing the text.
In performFiltering i tried to hide the progressBar but the autocomplete box is getting stuck as you type.
Is there any other way so i can try to hide the progressBar as the user stops typing the text.
you should try to use
public void afterTextChanged(Editable s)
autocomplete.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
progressBar.setVisibility(View.GONE);
}
I have an AutoCompleteTextView where i want to search for locations, example:
You type "vig" and the AutoCompleteTextView list shows the 5 best results for that:
"4560 Vig", "Juan Pablo Perez..", "The Vig 4041...", "Vig"
Another example, you type "vigo": it says the right place: "Vigo, Pontevedra" and you can select it and put it on the AutoCompleteTextView.
For now, what i have is working almost good but i have one error:
The display list is only showing when you delete on character, if not doesn't show, and what it shows is the last string result, example:
you have typed "vigo", and nothing appears, you delete the "o" and the display list shows results for "vigo" instead of "vig", that is what is typed in the AutoCompleteTextView in the moment.
I perform the search for the locations in an AsyncTask:
private class SearchAddress extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
//adapter.clear();
String[] addressArray = getStreetList(query);
return addressArray;
}
#Override
protected void onPostExecute(String[] addressArray) {
if(addressArray == null)
Toast.makeText(NewRouteActivity.this, "No address obtained from server", Toast.LENGTH_SHORT).show();
else{
adapter.clear();
for(String address: addressArray){
adapter.add(address); <------HERE IS THE 2ND ERROR
Log.d("ASYNC", address);
}
}
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
Here is my AutoCompleteTextView Code:
String[] array = {};
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, array);//simple_dropdown_item_1line
autoFrom.setAdapter(adapter);
autoTo.setAdapter(adapter);
asyncSearch = new SearchAddress();
autoFrom.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (((AutoCompleteTextView) autoFrom).isPerformingCompletion()) {return;}
if (s.length() < 2) {
return;
}else{
query = s.toString();
if (asyncSearch.getStatus().equals(AsyncTask.Status.FINISHED)){
asyncSearch = new SearchAddress();
asyncSearch.execute(query);
Log.d("ASYNC", "FINISH GOOD");
Log.d("ASYNC", query);
}else{
Log.d("ASYNC", "CANCEL");
asyncSearch.cancel(false);
asyncSearch = new SearchAddress();
asyncSearch.execute(query);
}
return;
}
}
});
I hope with this is enough, getStreetList() is working good, giving good results.
If you need something else just ask.
Thanks in advance!!!
I don't know if this is going to help you, but I've had problems with TextWatcher and AutoCompleteTextView. You should be using a filter on an adapter and not a TextWatcher.
A good implementation of google places + AutoCompleteTextView by google:
https://developers.google.com/places/training/autocomplete-android
I have a listview with products in it. I override the tostring method of the products:
#Override
public String toString() {
return this.getNaam();
}
I add addTextChangedListener to my EditText.
tvZoek.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString().toLowerCase());
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
When I do a search the list is filtered. But for example if I search for "Bio" and there are 5 product in the list with "Bio" in their name, than it is showing first 5 products in the list, not the 5 products with "Bio" in their name.
I didn't override the getFilter() method in the adapter.
How do I show the correct products? (I'm working with ArrayAdapter)
try the following.
public void onTextChanged(CharSequence s, int start, int before, int count) {
updateList(s.toString);
}
public void updateList(String filter) {
List<> tempList = new ArrayLsit<>();
int yourListSize = myList.count();
for (int i = 0; i < myListSize; i++) {
if (filter != null) {
if (myList.get(i).contains(filter)) {
tempList.add(myList.get(i));
}
}
}
// create adapter using tempList
// setAdapter
}