Add search functionality to custom list view - android

I create custom listView for contacts and EditText for search contents.
Here is search code.
Main Activity
EditText contactSearch = (EditText) findViewById(R.id.contactSearch);
contactSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
contentAdapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
contentAdapter is static variable which is define in another class which is in different file this class is extend from AysnTask
BackgroundWorker
public static ContentAdapter contentAdapter;
// other code
contentAdapter = new ContentAdapter(context, names, phones);
listView.setAdapter(contentAdapter);
I make it static variable because I want to access it from mainActivity class as define above.
There is no error But search functionality does not work properly. I try to search contact but it can't search. I don't know what the problem is. There is no error but searching is not working fine.
UPDATE ContentAdapter Class
public class ContentAdapter extends ArrayAdapter<String> {
private Context context;
private String[] names;
private String[] phones;
public static Dialog dialog;
ContentAdapter(Context ctx, String[] name, String[] phone){
super(ctx, R.layout.contact_row,R.id.txtName,name);
context = ctx;
names = name;
phones = phone;
dialog = new Dialog(context);
}
private class ViewHolder{
TextView name, phone;
ViewHolder(View view){
name = (TextView) view.findViewById(R.id.txtName);
phone = (TextView) view.findViewById(R.id.txtPhoneNumber);
view.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(context, "Item click", Toast.LENGTH_SHORT).show();
String phoneNumber = phone.getText().toString();
String userName = name.getText().toString();
//final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle(userName);
EditText etxtContactNumber = (EditText) dialog.findViewById(R.id.etxtContactNumber);
etxtContactNumber.setText(phoneNumber);
dialog.show();
}
});
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder viewHolder = null;
if(row == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.contact_row, parent, false);
viewHolder = new ViewHolder(row);
row.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) row.getTag();
}
viewHolder.name.setText(names[position]);
viewHolder.phone.setText(phones[position]);
return row;
}
}

Use this code in adapter.
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
names.clear();
if (charText.length() == 0) {
names.addAll(arraylist);
} else {
for (Names wp : arraylist) {
if (wp.toLowerCase(Locale.getDefault())
.contains(charText)) {
names.add(wp);
}
}
}
notifyDataSetChanged();
}

Related

Listview search does not show search results

First, please bear with me as I am just a beginner in learning Android.
What I want is that when the user adds an item from another activity, the details will be shown from my listview in the MainActivity (I am using a regular expression for my search results). And when the user tries to search an item, I want the search results to show.
From my code below, only the added items are shown and the search results will not display.
Here is a snippet of my code from MainActivity.java
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.notifyDataSetChanged();
}//end if
}
//update the listview
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
Student.java
public class Student {
Uri uriImage;
String studlname, studfname, studcourse;
//constructor
public Student(Uri uriImage, String studlname, String studfname, String studcourse) {
super();
this.uriImage = uriImage;
this.studlname = studlname;
this.studfname = studfname;
this.studcourse = studcourse;
}
//getters and setters
public Uri getUriImage() {
return uriImage;
}
public void setUriImage(Uri uriImage) {
this.uriImage = uriImage;
}
public String getStudlname() {
return studlname;
}
public void setStudlname(String studlname) {
this.studlname = studlname;
}
public String getStudfname() {
return studfname;
}
public void setStudfname(String studfname) {
this.studfname = studfname;
}
public String getStudcourse() {
return studcourse;
}
public void setStudcourse(String studcourse) {
this.studcourse = studcourse;
}
}
Update your code as below
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.refreshList(findlist)
}//end if
}
//update the listview
anotheradapter.refreshList(findlist)
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
Add refresh List method in adapter
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
public void refreshList(ArrayList<Student> list){
this.list = list;
notifyDataSetChanged()
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
You need to update your adapter initialization as below.
Update in the onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
// initialize the findlist to show all student list by default
findlist.addAll(studentArrayList);
anotheradapter = new CustomAdapter(this, findlist);
// ----- Remove these lines - as you don't need multiple adapters
//adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
//adapter.notifyDataSetChanged();
//lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
// Remove the below line as you don't need to update the list multipletimes
//anotheradapter.notifyDataSetChanged();
}
}
// Add these lines to show the list of all student when the searchbox is empty. This will reset the findList to initial state.
if (txtsearch.getText().length() == 0 && findlist.isEmpty()) {
findlist.addAll(studentArrayList);
}
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}

Display ListView of selected data to next Activity in textView

In ListView here i have all my contacts with check box. When i select 2 contacts from list and hit a button then selected list's value should be display in next activity. How can i do this?
Its my Activity class :
public class ContactListActivity extends Activity implements OnItemClickListener {
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
ContanctAdapter objAdapter = new ContanctAdapter(ContactListActivity.this, R.layout.alluser_row, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position, long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
showCallDialog(bean.getName(), bean.getPhoneNo());
}
private void showCallDialog(String name, final String phoneNo) {
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("Call?");
alert.setMessage("Are you sure want to call " + name + " ?");
alert.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String phoneNumber = "tel:" + phoneNo;
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phoneNumber));
startActivity(intent);
}
});
alert.show();
}
And My Adapter Class to Hold Data is
public class ContanctAdapter extends ArrayAdapter<ContactBean> {
private Activity activity;
private List<ContactBean> items;
private int row;
private LayoutInflater inflater = null;
public ContanctAdapter(Activity act, int row, List<ContactBean> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(row, null);
holder.tvname = (TextView) convertView.findViewById(R.id.tvname);
holder.tvPhoneNo = (TextView) convertView.findViewById(R.id.tvphone);
holder.checkbox = (ImageView) convertView.findViewById(R.id.img_checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return convertView;
ContactBean objBean = items.get(position);
holder.checkbox.setSelected((objBean.getIsSelected() == 1) ? true : false);
if (holder.tvname != null && null != objBean.getName() && objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo() && objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
holder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
items.get(position).isSelected = (v.isSelected()) ? 0 : 1;
notifyDataSetChanged();
}
});
return convertView;
}
public class ViewHolder {
public TextView tvname, tvPhoneNo;
private ImageView checkbox;
}
}
There is multiple ways to achieve that :
Method 1:
Use static class setter and getter method:
create static class and set values from first activity and get value from second activity
Method 2:
Post your values through the intent
Method 3:
Use database to store data from one activity and get data from other activity
Method 4:
Use Shared preference
Example:
Post values using Intent like this
Post values in Shared preference
Another tutorial for Shared preference
Try this, It may Help you
Add this code in your onitemClicklistener Listview Page
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
String TVNameitem = ((TextView) view.findViewById(R.id.tvname)).getText().toString();
String TVPhoneitem = ((TextView) view.findViewById(R.id.tvphone)).getText().toString();
Intent intent1 = new Intent(this,NextActivity.class);
intent1.putExtra("STRING_I_NEED_From_TVNAME", TVNameitem );
intent1.putExtra("STRING_I_NEED_From_TVPHONE",TVPhoneitem );
startActivity(intent1);
}
Add this code in your Nextactivty Oncreate for Getting Values, Then Show in Textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.find);
Bundle extras = getIntent().getExtras();
String VALUE_1= extras.getString("STRING_I_NEED_From_TVNAME");
String Value_2 =extras.getString("STRING_I_NEED_From_TVPHONE");
TextView Textview1=(TextView)findViewById(R.id.CompanyText);
Textview1.setText(VALUE_1+":"+Value_2);
}
Create getter and setter to share contact details.
public class GetContacts {
private String contactNumber;
private String contactName;
GetContacts(){}// constructor without parameter.
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
}
Now set contact values to the setters in GetContact class
create an instance of GetContact class in your first Activity.
GetContact getContact= new GetContact();
And Set Parameters.
getContact.setContactNumber(phoneNumber);
getContact.setContactName(name);
Now its time to get those values in second activity.
create an instance of GetContact class in your second Activity like you did before.
And Get Parameters, and display into TextView.
textView1.setText(getContact.getContactNumber(phoneNumber));
textView2.setText(getContact.getContactName(name));

Implement a getFilter() in ArrayAdapter android listview

In my list view have a four Text View and Images.
I want to set filter on txtcompany text view
I am trying to implement a getFilter() but it provide a wrong result
Please help me how can implement getFilter() in listview
List View ArrayAdapter source code
class Data extends ArrayAdapter
{
Button imageView;
TextView txtcompany;
TextView txtDesc;
TextView txtPosition;
TextView txtState;
TextView txtCity;
String[] companyarray;
String[] positonarray;
String[] cityarray;
String[] statearray;
String[] Descarray;
String[] contry;
String[] pass;
ArrayList<String> receiceValueOfAdapter=new ArrayList<String>(6);
ArrayList<String> time=new ArrayList<String>(6);
Context context;
Data(Context c, String[] company, String[] position, String[] city, String[] state,ArrayList<String> receiveValue, String[] Desc,ArrayList<String> time1,
String[] pass,String[] contry)
{
super(c,R.layout.list_item,R.id.txt_company,company);
this.context=c;
this.pass=pass;
this.companyarray=company;
this.positonarray=position;
this.cityarray=city;
this.statearray=state;
this.receiceValueOfAdapter=receiveValue;
this.Descarray=Desc;
this.time=time1;
this.contry=contry;
}
public View getView(int position, View convertView, ViewGroup parent) {
final String description;
String upperString="";
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View row;
row=mInflater.inflate(R.layout.list_item, parent,false);
txtcompany = (TextView) row.findViewById(R.id.txt_company);
imageView = (Button) row.findViewById(R.id.img);
//imageView.setVisibility(View.INVISIBLE);
txtPosition= (TextView) row.findViewById(R.id.txt_position);
txtCity= (TextView) row.findViewById(R.id.txt_city);
txtState= (TextView) row.findViewById(R.id.txt_state);
if(companyarray[position].toString().length()>0)
upperString = companyarray[position].substring(0,1).toUpperCase() + companyarray[position].substring(1);
txtcompany.setText(" "+upperString);
txtPosition.setText(" "+positonarray[position]);
Log.d("City",statearray[position]+"City "+cityarray[position]);
if(cityarray[position].toString().length()==0)
{
txtCity.setText(statearray[position]);
}
if(statearray[position].toString().trim().length()==0)
{
txtCity.setText(" "+cityarray[position]);
}
if(statearray[position].toString().trim().length()<2 && cityarray[position].toString().trim().length()<2)
{
txtCity.setText(" "+contry[position]);
}
if(statearray[position].toString().trim().length()>=2 && cityarray[position].toString().trim().length()>=2)
{
txtCity.setText(" "+cityarray[position]+", "+statearray[position]);
}
txtState.setText(""+time.get(position));
imageView.setTag(receiceValueOfAdapter.get(position));
description= Descarray[position];
final int l=position;
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
// Toast.makeText(contect, ""+ txtPosition.getText().toString(), Toast.LENGTH_LONG).show();
try{
String strurl1=pass[l].trim();
String strurl= strurl1.trim();
if (!strurl.trim().startsWith("https://") && !strurl.trim().startsWith("http://")){
strurl = "http://"+ strurl;
}
Intent ii = new Intent(Intent.ACTION_VIEW);
ii.setData(null);
ii.setData(Uri.parse(strurl));
startActivity(ii);
}
catch(Exception e)
{
}
}
});
return row;
}
}
EditText change Listener java code
lstsearch.addTextChangedListener(new TextWatcher()
{
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
Main_listview.this.datadap.getFilter().filter(charSequence);
}
public void afterTextChanged(Editable editable)
{
}
});
You can create custom method like this.
public void filter(String charText,int flag)
{
if(flag==0){
charText = charText.toLowerCase(Locale.getDefault());
if (charText.length() == 0)
{
ListofDetails.addAll(arraylist);
}
else
{
for (ListofDetails wp : arraylist)
{
if (wp.getCountry().toLowerCase(Locale.getDefault()).contains(charText))
{
NewList.add(wp);
}
}
}
elseif
{
///do some code
}
}

Android - AutoCompleteTextView as search box doesn't work

I would like to enable search functionality to AutoCompleteTextView. My requirement is like this: when someone types with some letter, suppose the user types 'a', then it should show all the words which starts with 'a' should be shown as a drop down list. For example, if I first typed "copy" in the AutoCompleteTextView, if again, I cleared the AutoCompleteTextView and tried to type "co", then it should show the drop-down list "copy","come","cow".... I want to enable this feature to my AutoCompleteTextView view. It worked when I had a ListView with only a textview inside, but now that I have two textview in my ListView it doesn't work.
This is my activity:
public class sedactivity extends Activity {
ListView lview;
ListViewAdapter lviewAdapter;
AutoCompleteTextView acTV;
private static final String first[] = {
"America",
"Busta",
"Cactus",
"Fire",
"Garden",
"Hollywood",
"King",};
private static final String second[] = {
"Uniti",
"Chiusa",
"Verde",
"Fiamme",
"Aperto",
"Boulevard",
"Kong",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
acTV = (AutoCompleteTextView)findViewById(R.id.acTV);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, first, second);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setTextFilterEnabled(true);
acTV.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) {
textlength=acTV.getText().length();
arr_sort.clear();
for(int i=0;i<first.length;i++)
{
if(textlength<=first[i].length())
{
if(acTV.getText().toString().equalsIgnoreCase((String) first[i].subSequence(0,textlength)))
{
arr_sort.add(first[i]);
}
}
}
}});}}
And this is my custom ListView Adapter:
public class ListViewAdapter extends BaseAdapter{
Activity context;
String title[];
String description[];
public ListViewAdapter(Activity context, String[] title, String[] description) {
super();
this.context = context;
this.title = title;
this.description = description;}
public int getCount() {
// TODO Auto-generated method stub
return title.length;}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;}
public View getView(int position, View convertView, ViewGroup parent){
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
return convertView;}}

Android - EditText as search box doesn't work

I would like to enable search functionality to EditText. My requirement is like this:
when someone types with some letter, suppose the user types 'a', then it should show all the words which starts with 'a' should be shown as a drop down list. For example, if I first typed "copy" in the EditText, if again, I cleared the EditText and tried to type "co", then it should show the drop-down list "copy","come","cow"....
I want to enable this feature to my EditText view. It worked when I had a ListView with only a textview inside, but now that I have two textview in my ListView it doesn't work.
This is my activity:
public class sedactivity extends Activity {
ListView lview;
ListViewAdapter lviewAdapter;
EditText ed;
private static final String first[] = {
"America",
"Busta",
"Cactus",
"Fire",
"Garden",
"Hollywood",
"King",};
private static final String second[] = {
"Uniti",
"Chiusa",
"Verde",
"Fiamme",
"Aperto",
"Boulevard",
"Kong",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText)findViewById(R.id.EditText1);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, first, second);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setTextFilterEnabled(true);
ed.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) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<first.length;i++)
{
if(textlength<=first[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) first[i].subSequence(0, textlength)))
{
arr_sort.add(first[i]);
}
}
}
}});}
}
And this is my ListView Adapter
public class ListViewAdapter extends BaseAdapter{
Activity context;
String title[];
String description[];
public ListViewAdapter(Activity context, String[] title, String[] description) {
super();
this.context = context;
this.title = title;
this.description = description;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
return convertView;
}
}
I think an AutoCompleteTextView might be more suitable to implement this feature.
Check out this example to create your own Listener to check the values inside Edittext on key press event - How to implement your own Listener
Instead of extending BaseAdapter you extend ArrayAdapter. It implements the Filterable interface for you. In TextWatcher call getFilter().filter(text); method.
public void afterTextChanged(Editable s) {
listview.getAdapter().getFilter().filter(s);
}

Categories

Resources