Search function in listView - android

I want to search for a product name in listView, but nothing displays inside the list after I key in some text inside search text field. I'm not using ArrayAdapter, but I'm using the ResourceCursorAdapter.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
helper = new ComicsData(this);
helper.open();
listSearch=(EditText)findViewById(R.id.inputSearch);
listSearch.addTextChangedListener(filterTextWatcher);
model = helper.getAllProduct(list);
startManagingCursor(model);
adapter=new ShoppingListAdapter(this, model);
listView.setAdapter(adapter);
}
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) {
//String search=listSearch.getText().toString();
//int textLength=search.length();
adapter.getFilter().filter(s);
}
};
ShoppingListAdapter
class ShoppingListAdapter extends ResourceCursorAdapter {
private final String CN = null;
public ShoppingListAdapter(Context context, Cursor c) {
super(context, R.layout.productrow, c);
// TODO Auto-generated constructor stub
}
#Override
public void bindView(View row, Context context, Cursor c) {
// TODO Auto-generated method stub
listName = (TextView) row.findViewById(R.id.produtName);
listName.setText(helper.getProductName(c));
Anybody know my mistake ?

After changing text in listSearch get items according to search text helper.getProducts(searchText); and call adapter.notifyDataSetChanged()

You need provide your adapter with an instance of FilterQueryProvider. This provider takes your filter query and returns cursor with all found items.

Related

Getting item position in AutoCompleteTextView addTextChangeListener method

I have Autocomplete textviews in my custom adapter. when i write something in onTextChange listener, i want to get item position. I it gives all items positions. Please help me regarding this issue. Thanks!
autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String)parent.getItemAtPosition(position);
//TODO Do something with the selected text
}
});
This is how you can get position of Item you typed in AutoCompleteTextView. But you have to add the full name of item like "apple" or "apples" then this code will give you the position of that particular item. But its very expensive process if you have lots of items in your list.
public class Test extends AppCompatActivity {
private AutoCompleteTextView autoCompleteTextView;
private List<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chintan_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
list = new ArrayList<>();
list.add("Apple");
list.add("Apples");
list.add("Banana");
list.add("Aunt");
list.add("Orange");
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompleteTextView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));
autoCompleteTextView.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) {
for (String string : list)
if (string.toLowerCase().equals(s.toString().toLowerCase())) {
int pos = list.indexOf(string);
Toast.makeText(Test.this, "" + pos, Toast.LENGTH_SHORT).show();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
Let me know if this code helps you.
Use textwatcher, implement it in activity class.
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
hi can you please check there is some issue
AutoCompleteTextView tv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
final ArrayList<Student> list = new ArrayList<MainActivity.Student>();
list.add(new Student("abc"));
list.add(new Student("abc"));
ArrayAdapter<Student> adapter = new ArrayAdapter<MainActivity.Student>(
this, android.R.layout.simple_dropdown_item_1line, list);
tv.setAdapter(adapter);
tv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Student selected = (Student) arg0.getAdapter().getItem(arg2);
Toast.makeText(MainActivity.this,
"Clicked " + arg2 + " name: " + selected.name,
Toast.LENGTH_SHORT).show();
}
});
for more checking you can go from here...
you can use addTextChangedListener for this purpose
yourAutoCompleteTextView.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) {
} });

Android Listview

now i am making a program in android using edittext and listview.
I want to search the listview item using edittext above.
After populate data to listview, when user type text in edittext, the listview will
scroll to the position start with that text.
Example: i have item:
apple,
application,
book,
boy,
car,
cat,
cash.....
when i type b in edittext then listview will scroll to book.
I want to use the listview.setSelection(position), but i don't know how can i get the position from my edittext search.
I hope everybody can help me. Thanks in advances !
you can make implement like the below code:
YOUR_EDITTEXT.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//LOGIC MAY DIFFER ACCORDING TO YOUR REQUIREMENT..
int POSITION = 0;
for(int i =0;i<list.size();i++) {
if(list.get(i).startsWith(s.toString()))
{
POSITION = i;
break;
}
}
listview.smoothScrollToPosition(POSITION);
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
});
Hope it will help you..!!!
try this example,
public class MainActivity extends Activity {
private ListView list1;
// private String array[] ;
EditText inputSearch;
ArrayAdapter<String> adapter;
String[] testArray = new String[] { "one", "two", "three", "etc" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputSearch = (EditText) findViewById(R.id.inputSearch);
list1 = (ListView) findViewById(R.id.ListView01);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, testArray);
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) {
Log.i("check", "" + position);
}
});
}
}

Search Listview with EditText using SimpleCursorAdapter

I am trying to implement a search of a ListView I create through SimpleCursorAdapter. I have tried various ways and below is what I have so far and it is not working. I want to be able to type in the EditText and my list adjust to the search. Any help would be greatly appreciated and below is my code:
private FoodDatabase foodDB;
private CalendarDBAdapter calendarDB;
private ListView fruitsListVIew;
private String datePassed;
private View dialogView;
private EditText search;
private SimpleCursorAdapter myCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fruits);
fruitsListVIew = (ListView)this.findViewById(R.id.fruitsListView);
search = (EditText)this.findViewById(R.id.search_box);
datePassed = GlobalVars.getDate();
openDB();
populateLV();
search.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
myCursorAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
}
});
}
private void populateLV()
{
String fruitID = "10";
final Cursor c = foodDB.getFoodByGroup(fruitID);
//allow activity to close cursor
startManagingCursor(c);
//Mapping from cursor to view fields
String[] fieldNames = new String[] {FoodDatabase.FOOD_ITEM_NAME, FoodDatabase.CALORIES, FoodDatabase.FAT,
FoodDatabase.MEASURE, FoodDatabase.TYPE_OF_MEASRE};
int[] viewIds = new int[] {R.id.foodNameTxt, R.id.calorieDB, R.id.fatDB, R.id.servingDB, R.id.measureTxt};
//create adapter to map columns to view exercise UI
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.foods_data_layout, c, fieldNames, viewIds);
//Set the adapter for the list view
fruitsListVIew.setAdapter(myCursorAdapter);
fruitsListVIew.setTextFilterEnabled(true);
fruitsListVIew.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
qtyDialog(v);
}
});
}
I am able to input text but nothing happens.
Cheers
Try this
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
myCursorAdapter.getFilter().filter(s.toString());
myCursorAdapter.notifyDataSetChanged();
}
It appears to me that you need a FilterQueryProvider :)
myCursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
String partialValue = constraint.toString();
return itemData.getAllSuggestedValues(partialValue);
}
});
Check this - Using an EditText to filter a SimpleCursorAdapter-backed ListView

How to create search functionality in listview [duplicate]

This question already has answers here:
unable to search using custom Array Adapter in Android?
(2 answers)
Closed 10 years ago.
I want to create search functionality in listview,i have a small doubt that using arraylist can we perform search functionality.Here i ahve attached the code..where the
Totalarraylist is the arraylist and from that arraylist i am passing the data to Question adapter class
code,,
searchbox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
If so then what to add here for search functionality...
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
adapterfirst = new Questionadapter(MainActivity.this,Totalarraylist);
listviewfirst = (ListView) findViewById(R.id.listquestion);
listviewfirst.setAdapter(adapterfirst);
}
public class Questionadapter extends BaseAdapter {
private ArrayList<HashMap<String, Object>> data;
public LayoutInflater inflater;
Context context;
public Questionadapter(Context context, ArrayList<HashMap<String,Object>> Totalarraylists) {
// TODO Auto-generated constructor stub
data=Totalarraylists;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
System.out.println("data="+data);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
//
}
}
could anybody help me to do this..
add a filter to your ListAdapter, and on onTextChanged apply the filter to listadapter
Try this, Compare your array list with your string you will get answer
public class MainActivity extends Activity {
ArrayList<String> list = new ArrayList<String>();
private EditText searchEdt;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// making it full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_ugsimply_beta);
list.add("Android");
list.add("Android1");
list.add("blackberry");
list.add("samsung");
list.add("LG");
searchEdt = (EditText) findViewById(R.id.searchEdt);
searchEdt.addTextChangedListener(new TextWatcher() {
private int textlength;
private ArrayList<String> arrayList_sort = new ArrayList<String>();
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 = searchEdt.getText().length();
if (arrayList_sort != null)
arrayList_sort.clear();
for (int i = 0; i < list.size(); i++) {
if (textlength <= list.get(i).toString().length()) {
if (searchEdt
.getText()
.toString()
.equalsIgnoreCase(
(String) list.get(i).toString()
.subSequence(0, textlength))) {
arrayList_sort.add(list.get(i));
Log.d("TAG", "log" + arrayList_sort.size());
}
}
}
}
});
}
}

Unable to filter a listview with 2 lines

I am trying to provide a searchable listview. Each listitem has a name & address text box but I only want to filter on the name. My current code does nothing, i.e no filtering occurs at all. Is there a way of setting the column to filter by?
//class variables
private SimpleCursorAdapter mAdapter;
private EditText filterText = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_customer_listview);
//listViewCustomers = (ListView) findViewById(R.id.list);
buildingListViewAdaptor();
setListAdapter(mAdapter);
// set up the filter
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mAdapter.getFilter().filter(s);
Log.d(GlobalTools.ErrorCodes.INFO, "Searchtext=" + s.toString());
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
};
private void buildingListViewAdaptor(){
//1. Get the data
CustomerLocationDataHandler clDataHandler = new CustomerLocationDataHandler(getContentResolver());
Cursor cursor = clDataHandler.allCustomerLocations();
clDataHandler=null;
//2. Build the adaptor
mAdapter = new SimpleCursorAdapter(this,
R.layout.list_item_custom_font, // was list_item_custom_font
cursor,
new String[]{MyobiliseData.Columns_CustomerLocations.CUSTOMER_NAME,MyobiliseData.Columns_CustomerLocations.CITY},
new int[] {R.id.text1,R.id.text2}
);
}
check out this post: ListView, SimpleCursorAdapter, an an EditText filter -- why won't it do anything?
I have added in a similar method and it is now working.
To achieve this I needed to re-query the database each time the user typed in the search box. I have included the working code here:
public class AddCustomerActivity extends ListActivity{
//constants
public static final String B4ME = "B4ME"; //Used when passing a boolean to this activity
// dialog constants
private static final int DIALOG_CHECKINSERT = 0;
//class variables
private SimpleCursorAdapter mAdapter;
private EditText filterText = null;
private boolean mInsertB4; //if false ->means insert after
private Long mRunDetailID;
private Long mCustomerLocationId;
private int mSelectedItemPosition;
private long mSelectedItemId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_customer_listview);
readVariablesPassedToThis();
//listViewCustomers = (ListView) findViewById(R.id.list);
buildingListViewAdaptor();
setListAdapter(mAdapter);
// set up the filter
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
mAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return filterRefresh(constraint);
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mAdapter.getFilter().filter(s);
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mSelectedItemPosition = position;
mSelectedItemId = id;
Log.d(GlobalTools.ErrorCodes.INFO, "Selected ItemPosition=" + mSelectedItemPosition + " and itemid ="+mSelectedItemId);
showDialog(DIALOG_CHECKINSERT);
}
private void buildingListViewAdaptor(){
//2. Build the adaptor
mAdapter = new SimpleCursorAdapter(this,
R.layout.list_item_custom_font, // was list_item_custom_font
filterRefresh(null),
new String[]{MyobiliseData.Columns_CustomerLocations.CUSTOMER_NAME,MyobiliseData.Columns_CustomerLocations.CITY},
new int[] {R.id.text1,R.id.text2}
);
}
private Cursor filterRefresh(CharSequence constraint){
//1. Get the data
CustomerLocationDataHandler clDataHandler = new CustomerLocationDataHandler(getContentResolver());
Cursor cursor = clDataHandler.customerLocationsFilteredOn(constraint);
clDataHandler=null;
return cursor;
}

Categories

Resources