Array Adapter - getCount return previous count - android

I'm using array adapter to implement a search view to search for hard coded elements
my code as follows
public class MainActivity extends AppCompatActivity {
ListView list;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.toolbar);
list = (ListView) findViewById(R.id.list_view);
EditText edittext = (EditText) findViewById(R.id.editText);
edittext.addTextChangedListener(textWatcher);
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.row_item, COUNTRIES);
}
TextWatcher textWatcher = 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.toString().equals(""))
list.setAdapter(null);
else {
adapter.getFilter().filter(s.toString());
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
// adapter.clear();
Log.v("HEY", adapter.getCount() + "");
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
private static final String[] COUNTRIES = new String[]{
"FAAAFA", "France", "FOO"};
}
When i type F in the search for example, the count is printed 0 instead of 3
then when i apply any other query the count is 3 (ie it prints the count of previous query to current one)

Related

Saving Data Issue, SharedPreferences

Here is my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
List all;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
editor = sharedPref.edit();
setListAdapter();
}
private void setListAdapter(){
final String[] data = displayData().toString().split(",");
ListAdapter listAdapter = new CustomAdapter(this, data);
listView = (ListView) findViewById(R.id.listView);
listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
listView.setAdapter(listAdapter);
}
public List displayData(){
all = new ArrayList<>();
try {
Map<String, ?> allMap = sharedPref.getAll();
for (Map.Entry<String, ?> entry : allMap.entrySet()) {
all.add(entry.getKey().toString() + ":" + entry.getValue().toString());
}
} catch(NullPointerException npe){
all.add(" : ");
}
Log.i("understandCode", "displayData: " + all.toString());
return all;
}
public void add(View view){
editor.putString(" ", " ");
editor.apply();
setListAdapter();
}
private class CustomAdapter extends ArrayAdapter<String> {
SharedPreferences.Editor editor;
String type;
String content;
public CustomAdapter(Context context, String[] resource) {
super(context, R.layout.custom_row, resource);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences
(MainActivity.this);
editor = sharedPref.edit();
}
EditText typeET;
EditText contentET;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View customView = layoutInflater.inflate(R.layout.custom_row, parent, false);
String singleItem = getItem(position);
typeET = (EditText) customView.findViewById(R.id.type);
contentET = (EditText) customView.findViewById(R.id.content);
String[] givenStrings = singleItem.split(":");
try {
typeET.setText(givenStrings[0]);
contentET.setText(givenStrings[1]);
}catch(ArrayIndexOutOfBoundsException aioobe){
typeET.setText(" ");
contentET.setText(" ");
}
typeET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
type = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
type = s.toString();
save();
}
#Override
public void afterTextChanged(Editable s) {
}
});
contentET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
content = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
content = s.toString();
save();
}
#Override
public void afterTextChanged(Editable s) {
}
});
return customView;
}
private void save() {
editor.putString(type, content);
editor.apply();
Log.i("understandCode", type + ":" + content);
}
}
}
Here is my log when I am editing my key, value:
05-04 17:52:52.107 11146-11146/com.x.xI/understandCode: [ my mom!a said:y ]
05-04 17:52:52.462 11146-11146/com.valerdaita.myinfo I/understandCode: [ my mom!a said:yo ]
05-04 17:52:52.698 11146-11146/com.valerdaita.myinfo I/understandCode: [ my mom!a said:yol ]
05-04 17:52:52.897 11146-11146/com.x.x I/understandCode: [ my mom!a said:yolo ]
When I restart the Activity:
05-04 17:53:05.085 12056-12056/com.x.x I/understandCode: displayData: [ : ]
So, it is not showing the data that I saved. I really am having trouble identifying the problem because I know that my save functionality is working well because of the Log, but I cannot identify any problem with the displayer.
You will definitely get NPE as you have not saved any values in your preferences yet.
Code flow is setListAdapter() ->displayData() ->sharedPref.getAll().
In between this you are not adding any key-value pair to preferences.
So why do you expect you'll not get NPE ?
Save some values before using getAll() if you don't want to get NPE.

Change ArrayAdapter while filling up AutoCompleteTextView onTextChanged

I found many questions like this, but no answer. Is it possible to change the ArrayList of the adapter while AutoCompleteTextView is being typed?
private void setUpAutocomplete() {
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
final AutoCompleteTextView textView = autocompleteTV;
textView.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) {
adapter.clear();
ArrayList<String> locations=gAPI.autocomplete(s.toString());
adapter.addAll(locations);
}
#Override
public void afterTextChanged(Editable s) {
}
});
textView.setAdapter(adapter);
}
Yes, there is. The following code retrieves places from the Google Places API and populates the an ArrayAdapter, which changes as the text in the AutocompleteTextView changes.
// declare this variable globally in your activity so that it can be
//referenced and updated in the inner class (public void onResult(...))
private ArrayAdapter<String> adapter;
AutoCompleteTextView locationText = (AutoCompleteTextView) findViewById(R.id.location_text);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line);
locationText.setAdapter(adapter);
locationText.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) {
String query = s.toString();
//mMap is a GoogleMap object. Alternatively, you can initialize a
//LatLngBounds object directly through its constructor
LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
AutocompleteFilter filter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_NONE)
.build();
PendingResult<AutocompletePredictionBuffer> autocompleteResult =
Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, query,
bounds, filter);
autocompleteResult.setResultCallback(new ResultCallback<AutocompletePredictionBuffer>() {
#Override
public void onResult(#NonNull AutocompletePredictionBuffer autocompletePredictions) {
for (int i = 0; i < autocompletePredictions.getCount(); i++) {
adapter.add(autocompletePredictions.get(0).getFullText(null).toString());
}
autocompletePredictions.release();
adapter.notifyDataSetChanged();
}
});
}
Below is the XML code for the AutocompleteTextView:
<AutoCompleteTextView
android:id="#+id/location_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:hint="Search location..." />

TextWatcher filter isn't working correctly after popBackStack

I have a ListView that contains an EditText to filter list result. Everything is working well during this phase.
My problem is after clicking an item in the list and then go back to the ListView, the item in the list is gone, most probably the because EditText contains an empty space after back button is pressed. Why is this so?
I've put a Log inside onTextChanged to see what character is being put when the back button is pressed. It's just blank. I'm not sure why this listener adds an empty space and filter the result after back button is pressed.
Here is the code in ListFragment:
public class CategoryFragment extends ListFragment {
...
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// filter result
etFilterCategory.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
// Log.d(TAG, "ontextchanged= " + charSequence);
va.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}
The BaseAdapter implementing Filterable:
public class CategoryAdapter extends ArrayAdapter<CategoryModel> implements
Filterable {
...
#Override
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final ArrayList<CategoryModel> list = originalData;
int count = list.size();
final ArrayList<CategoryModel> nlist = new ArrayList<CategoryModel>(count);
String filterableString;
for (int i = 0; i < count; i++) {
filterableString = list.get(i).getName();
if(filterableString.toLowerCase().contains(filterString)) {
// add the whole custom row
nlist.add(list.get(i));
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrCategory = (ArrayList<CategoryModel>) results.values;
notifyDataSetChanged();
}
}
}
How do I NOT make the ListView item filtered after every back button pressed?
EDIT:
After back button is pressed, the only way to make the ListView visible is to add a space into the EditText and remove it. That will show the previous list. What did I missed?
you may be re-creating your listAdapter object, this will nullify the previously created listAdapter.
Your call of textwatcher is pointing to older listadapter where in onResume/OnCreateView event your new instance of listadapter is generated.
I solved my problem by declaring listadapter object as member in my fragment and checking it in onResume method as follow
#Override
public void onResume() {
super.onResume();
if (news == null) {
if(CommonFun.isInternetOn(activity))
new NewsRetrivalTask().execute();
else
ToastMsg.showToast(activity, Msg.alertInternetMsg);
} else {
newsListAdapter = new NewsListAdapter(getActivity(), news);
lv.setAdapter(newsListAdapter);
lv.setOnItemClickListener(MAP_FragmentChatRoom.this);
lv.setVisibility(View.VISIBLE);
tvNoRecord.setVisibility(View.GONE);
}
}
and textwatcher in onCreateView method
etSearch.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) {
newsListAdapter.getFilter().filter(s);
}
});

Suggestions not shown in AutoCompleteTextView

I have a AutoCompleteTextView in my layout. When a user enter "#" character in that i have to show them some suggestions. It normally names i get it from internet.
I am getting the names and i create an ArrayAdapter as shown below.
autoCtextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
String lsatChar = s.toString().substring(s.length()-1,s.length());
if(lsatChar.equals("#")) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DisplayQuestionDetails.this,
android.R.layout.simple_list_item_1, namesLsist);
autoCtextView.setAdapter(adapter);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
But the suggestions are not shown. Am i doing anything wrong ? Please ask if need clarification on question
Do you miss autoCtextView.setThreshold(1); ?
(to start working from first character)
for example demo:
String[] strList={"a","aaa","aabb","b","bbc","cbb","c","cdd","caa","d","ddc","dda","e","eea","ebc","aec"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the instance of ArrayAdapter containing list
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.select_dialog_item,strList);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView autoCtextView= (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
autoCtextView.setThreshold(1); //to start working from first character
autoCtextView.setAdapter(adapter);//set the adapter data to the AutoCompleteTextView
}
After declare autocompleteTextView than fill the first adapter.
like Ref here
public class CountriesActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.countries_list);
textView.setAdapter(adapter);
}
private static final String[] COUNTRIES = new String[] {
"Belgium", "France", "Italy", "Germany", "Spain"
};
}
In my fragment layout, if I don't use the ems attribute (field size in number of "m"s), the suggestions will not be shown. When it is present, the suggestions are shown.
<AutoCompleteTextView
android:id="#+id/enter_activities_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:ems="10"
android:completionThreshold="1"/>
Do this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DisplayQuestionDetails.this, android.R.layout.simple_list_item_1, namesLsist);
autoCtextView.setAdapter(adapter);
Before
autoCtextView.addTextChangedListener(new TextWatcher() {...
I made custom AutoComplete Textbox with the help of this blog. It works when user types "#something", e.g."#f" then all the names which matches 'f' will come up.
CustomAutoComplete.java
public class CustomAutoComplete extends AutoCompleteTextView {
private String previous = "";
private String seperator = "#";
public CustomAutoComplete(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
this.setThreshold(0);
}
public CustomAutoComplete(final Context context, final AttributeSet attrs) {
super(context, attrs);
this.setThreshold(0);
}
public CustomAutoComplete(final Context context) {
super(context);
this.setThreshold(0);
}
/**
* This method filters out the existing text till the separator
* and launched the filtering process again
*/
#Override
protected void performFiltering(final CharSequence text, final int keyCode) {
String filterText = text.toString().trim();
previous = filterText.substring(0, filterText.lastIndexOf(getSeperator()) + 1);
filterText = filterText.substring(filterText.lastIndexOf(getSeperator()) + 1);
if (!TextUtils.isEmpty(filterText)) {
super.performFiltering(filterText, keyCode);
}
}
/**
* After a selection, capture the new value and append to the existing
* text
*/
#Override
protected void replaceText(final CharSequence text) {
super.replaceText(previous + text + getSeperator());
}
public String getSeperator() {
return seperator;
}
}
Layout file:
<com.example.app.CustomAutoComplete
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/autoCompleteTextView"
android:layout_gravity="center_horizontal|top" />
MainActivity:
public class MainActivity extends ActionBarActivity {
CustomAutoComplete autoCompleteTextView;
String[] namesLsist = {"zivame","ziooo","zoooO","flipme","flipkart"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (CustomAutoComplete) findViewById(R.id.autoCompleteTextView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, namesLsist);
autoCompleteTextView.setAdapter(adapter);
}
}

How can I filter ListView data when typing on EditText in android

I have a ListView and a EditText. How can I filter ListView data when typing on EditText?
Add TextWatcher to EditText#addTextChangedListener
In onTextChanged add or remove items from your ListView's adapter. If you are subclassing ArrayAdapter it would have add and remove methods
Yes you can, just implement this code. Use the following code to implement search and filter list in android:
SearchAndFilterList.java
public class SearchAndFilterList extends Activity {
private ListView mSearchNFilterLv;
private EditText mSearchEdt;
private ArrayList<String> mStringList;
private ValueAdapter valueAdapter;
private TextWatcher mSearchTw;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_and_filter_list);
initUI();
initData();
valueAdapter=new ValueAdapter(mStringList,this);
mSearchNFilterLv.setAdapter(valueAdapter);
mSearchEdt.addTextChangedListener(mSearchTw);
}
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) {
}
};
}
private void initUI() {
mSearchNFilterLv=(ListView) findViewById(R.id.list_view);
mSearchEdt=(EditText) findViewById(R.id.txt_search);
}
}
Custom Value adapter:
ValueAdapter.java
public class ValueAdapter extends BaseAdapter implements Filterable{
private ArrayList<String> mStringList;
private ArrayList<String> mStringFilterList;
private LayoutInflater mInflater;
private ValueFilter valueFilter;
public ValueAdapter(ArrayList<String> mStringList,Context context) {
this.mStringList=mStringList;
this.mStringFilterList=mStringList;
mInflater=LayoutInflater.from(context);
getFilter();
}
//How many items are in the data set represented by this Adapter.
#Override
public int getCount() {
return mStringList.size();
}
//Get the data item associated with the specified position in the data set.
#Override
public Object getItem(int position) {
return mStringList.get(position);
}
//Get the row id associated with the specified position in the list.
#Override
public long getItemId(int position) {
return position;
}
//Get a View that displays the data at the specified position in the data set.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder viewHolder;
if(convertView==null) {
viewHolder=new Holder();
convertView=mInflater.inflate(R.layout.list_item,null);
viewHolder.nameTv=(TextView)convertView.findViewById(R.id.txt_listitem);
convertView.setTag(viewHolder);
}else{
viewHolder=(Holder)convertView.getTag();
}
viewHolder.nameTv.setText(mStringList.get(position).toString());
return convertView;
}
private class Holder{
TextView nameTv;
}
//Returns a filter that can be used to constrain data with a filtering pattern.
#Override
public Filter getFilter() {
if(valueFilter==null) {
valueFilter=new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
if(constraint!=null && constraint.length()>0){
ArrayList<String> filterList=new ArrayList<String>();
for(int i=0;i<mStringFilterList.size();i++){
if(mStringFilterList.get(i).contains(constraint)) {
filterList.add(mStringFilterList.get(i));
}
}
results.count=filterList.size();
results.values=filterList;
}else{
results.count=mStringFilterList.size();
results.values=mStringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
mStringList=(ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
activity_search_and_filter_list.xml
<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" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/txt_search"
tools:context=".SearchAndFilterList"
android:hint="Enter text to search" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_view"
android:layout_below="#+id/txt_search"></ListView>
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt_listitem"/>
</RelativeLayout>
AndroidManifext.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.searchandfilterlistview"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SearchAndFilterList"
android:label="#string/title_activity_search_and_filter_list" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I hope this code will will helpful to implement custom search and filter listview.
You can use:
http://developer.android.com/reference/android/widget/TextView.html
addTextChangedListener( TextWatcher watcher )
to figure out when the textview was changed. I believe it should be called everytime a letter is added or removed.
Then update your list adapter to dislplay the new items by either:
creating a new list adapter and populating it with the items that satisfy the filter or
having a subclass of the BaseAdapter to accept your filter and call notifyDataSetChanged() after it has finished removing the items you no longer want
http://developer.android.com/reference/android/widget/BaseAdapter.html
Search a listview based on input in EditText
public class MainActivity extends Activity {
private ListView lv,lv2;
private EditText et;
String listview_array[]={"01634 ABOHAR","080 Bangalore","011 Delhi","Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "1234", "iPhone 4S", "Samsung Galaxy Note 800", "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
private ArrayList<String> array_sort = new ArrayList<String>();
int textlength = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.ListView01);
lv2 = (ListView) findViewById(R.id.ListView02);
et = (EditText) findViewById(R.id.EditText01);
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listview_array));
int x= lv.getHeaderViewsCount ();
System.out.println("x========"+x);
lv.setAdapter(new ArrayAdapter<String>
(MainActivity.this,
android.R.layout.simple_list_item_1, listview_array));
et.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
// Abstract Method of TextWatcher Interface.
}
public void beforeTextChanged(CharSequence s,
int start, int count, int after)
{
// Abstract Method of TextWatcher Interface.
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
textlength = et.getText().length();
array_sort.clear();
for (int i = 0; i < listview_array.length; i++)
{
if (textlength <= listview_array[i].length())
{
String s2= et.getText().toString();
if(listview_array[i].toString().contains(et.getText().toString()))
{
array_sort.add(listview_array[i]);
}
}
}
lv.setAdapter(new ArrayAdapter<String>
(MainActivity.this,
android.R.layout.simple_list_item_1, array_sort));
}
});
}
}
For search in custom listview based on class item refer the link implement search on a custom listview. Modify it according to your needs.
when you use custom listView
Adapter :
public class Adapter extends ArrayAdapter {
ArrayList<String> list = new ArrayList<>();
ArrayList<String> filteredData = new ArrayList<>();
public Adapter(#NonNull Context context, int resource) {
super(context, resource);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflate = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
#SuppressLint("ViewHolder") View vi = inflate.inflate(R.layout.ly_items, null);
try {
JSONObject js = new JSONObject(list.get(position));
TextView txtItem = vi.findViewById(R.id.txtItem);
ImageView imgItem = vi.findViewById(R.id.imgItem);
txtItem.setText(js.getString("name") + " - " + js.getInt("number"));
Picasso.get().load(js.getString("logo_url")).into(imgItem);
} catch (JSONException e) {
e.printStackTrace();
}
return vi;
}
#Override
public void add(#Nullable Object object) {
super.add(object);
list.add(object.toString());
filteredData.add(object.toString());
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
list.clear();
if (charText.length() == 0) {
list.addAll(filteredData);
} else {
for (String wp : filteredData) {
try {
JSONObject json = new JSONObject(wp);
if (json.getString("name").toLowerCase().contains(charText) || json.getString("number").contains(charText)) {
list.add(wp);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
notifyDataSetChanged();
}
}
And your class:
Adapter adapter;
ListView list;
EditText edtSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = findViewById(R.id.list);
edtSearch = findViewById(R.id.edtSearch);
adapter = new Adapter(this, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
edtSearch.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) {
adapter.filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
1) create a custom adapter for your list view and create a removeIfMatch(String s) method:
public void removeIfMatch(String s) {
for item in adapter:
if item.matches(s) {
data.removeItem(item);
notifyDataSetChanged();
break
}
}
2) create a callback for when the EditText contents change
3) invoke adapter.removeIfMatch(editText.getText())

Categories

Resources