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) {
}
});
}
Related
I'm having difficulty updating the data of a listview, I've developed the search function in the listview and I can search the data, but I need to access the details in detail, passing to an activity, when I do that the data that is passed is those of the id 0 of the first list ... that is, only the view is being updated and not the data. Does anyone know how to fix it?
Search Activity
public class PesquisaTesteActivity extends AppCompatActivity {
public static TextView txt;
public static List<PesquisaBD> lista_produtos;
public static ListView lv;
AdapterBDLocal adapter;
private Button btn;
public static ArrayList list = new ArrayList();
private EditText searchView;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pesquisa_teste);
lv = (ListView)findViewById(R.id.lv2);
searchView = (EditText) findViewById(R.id.search);
lista_produtos = DataBaseClass.getInstance(getApplicationContext()).getAllProdutos();
txt = findViewById(R.id.textView);
adapter = new AdapterBDLocal(PesquisaTesteActivity.this, lista_produtos);
searchView.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) {
}
#Override
public void afterTextChanged(Editable s) {
final List<PesquisaBD> filtro = filter(lista_produtos,s.toString());
adapter.setFilter(filtro);
lv.setAdapter(adapter);
}
});
btn = (Button) findViewById(R.id.btn_te);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(PesquisaTesteActivity.this, Scan3Activity.class);
startActivity(i);
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent inte = new Intent(PesquisaTesteActivity.this, DetalhesPesquisaActivity.class);
inte.putExtra("nome", lista_produtos.get(i).getNome_completo());
inte.putExtra("codigo", lista_produtos.get(i).getCodigo_barras());
inte.putExtra("imagem", lista_produtos.get(i).getImagem());
inte.putExtra("unidade", lista_produtos.get(i).getUnidade());
inte.putExtra("preco", lista_produtos.get(i).getPreco());
startActivity(inte);
}
});
lv.setAdapter(adapter);
}
private List<PesquisaBD> filter(List<PesquisaBD> lista, String query){
query = query.toLowerCase();
final List<PesquisaBD> filtro = new ArrayList<>();
for(PesquisaBD p : lista){
final String texte = p.getNome_completo().toLowerCase();
if(texte.startsWith(query)){
filtro.add(p);
}
}
return filtro;
}
}
Adapter
public class AdapterBDLocal extends BaseAdapter{
private Context mContext;
private List<PesquisaBD> produtosList = new ArrayList<>();
private Filter filter;
public AdapterBDLocal(Context mContext, List<PesquisaBD> produtosList) {
this.mContext = mContext;
this.produtosList = produtosList;
}
#Override
public int getCount() {
return produtosList.size();
}
#Override
public Object getItem(int i) {
return produtosList.size();
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View listItem = view;
if(listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.item_lista_pesquisa,viewGroup,false);
final PesquisaBD p = produtosList.get(i);
ImageView img_produto_pesquisa = listItem.findViewById(R.id.img_produto_pesquisa);
TextView nome = (TextView) listItem.findViewById(R.id.txt_nome_produto2);
nome.setText(p.getNome_completo());
TextView categoria = (TextView) listItem.findViewById(R.id.txt_categoria2);
categoria.setText(p.getPreco());
TextView unidade = (TextView) listItem.findViewById(R.id.txt_unidade2);
unidade.setText(p.getUnidade());
ImageView btn_add = (ImageView)listItem.findViewById(R.id.btn_add);
ImageView btn_rem = (ImageView)listItem.findViewById(R.id.btn_rem);
if(p.getImagem() == null){
Picasso.with(mContext).load(R.drawable.ic_logo).fit().into(img_produto_pesquisa);
} else {
//Picasso.with(mContext).load(p.getImagem()).networkPolicy(NetworkPolicy.OFFLINE).fit().into(img_produto_pesquisa);
Glide.with(mContext).load(p.getImagem()).into(img_produto_pesquisa);
}
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String m = p.getCodigo_barras();
if(list.size()<=9){
list.add(m);
txt.setText(list.toString());
Toast.makeText(mContext, "Adiconado", Toast.LENGTH_SHORT).show();
if(txt.getText()!= null){
}
} else{
Toast.makeText(mContext, "Sua Lista esta grande demais!", Toast.LENGTH_SHORT).show();
}
}
});
btn_rem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String m = p.getCodigo_barras();
list.remove(m);
txt.setText(list.toString());
Toast.makeText(mContext, "Removido da lista!", Toast.LENGTH_SHORT).show();
}
});
return listItem;
}
public void setFilter(List<PesquisaBD> l) {
produtosList = new ArrayList<PesquisaBD>();
produtosList.addAll(l);
notifyDataSetChanged();
}
}
In your adapter use this :- produtosList.clear(); instead of
produtosList = new ArrayList<PesquisaBD>(); that is
public void setFilter(List<PesquisaBD> l) {
produtosList.clear();
produtosList.addAll(l);
notifyDataSetChanged(); }
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();
}
I'm trying to implement a search function in my application. I have used an adapter to because I want to display 2 textviews in listview and listview should be clickable (I don;t think it's possible to do without an adapter).
My problem is I can't use addTextChangedListener in the adapter class. it gives exception (It worked in my activity class).
search activity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_results_activity);
new SearchMenuAsyncTask(getApplicationContext(), this).execute();
listtv = (LinearLayout) findViewById(R.id.product_lv);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"]");
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
final List<String> descriptions = new ArrayList<String>();
final List<String> menudescriptions = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("5")
&& (object.getString("SubCategoryID")).equals("6")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsBev ", object.getString("Description"));
descriptions.add(object.getString("Description"));
Log.i("MenuDescription ",
object.getString("MenuDescription"));
menudescriptions
.add(object.getString("MenuDescription"));
}
adapter = new CustomListSearch(
getApplicationContext(), descriptions,
menudescriptions);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
CustomListSearch.java
public class CustomListSearch extends BaseAdapter implements Filterable {
private Context context;
private final List<String> descriptions;
private List<String>filteredData = null;
private final List<String> menudescriptions;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
ArrayAdapter<String> adapter;
public CustomListSearch(Context c, List<String> data,
List<String> menudescriptions) {
this.context = c;
this.filteredData = data ;
this.descriptions = data;
this.menudescriptions = menudescriptions;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private TextView tvMenudescriptions;
private TextView tvDescriptions;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.search_list_item, parent, false);
holder.tvDescriptions = (TextView) convertView
.findViewById(R.id.product_name);
holder.tvMenudescriptions = (TextView) convertView
.findViewById(R.id.product_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvDescriptions.setText(descriptions.get(position));
holder.tvMenudescriptions.setText(menudescriptions.get(position));
LinearLayout itemlist = (LinearLayout) convertView
.findViewById(R.id.product_lv);
itemlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Still under constructions...",
Toast.LENGTH_LONG).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = descriptions;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
I was following below answer and worked this out
Custom Listview Adapter with filter Android
I'm trying to filter a listview with arrayadapter. The arraydapter parameter is a String[][]. The problem is that anything happens. I must override the Filter interface? In that case plase, can someone provide some hints?
Every position of the array I'm trying to filter is like
galleryValues[0][0] -> "tiulo"
[0][1] -> "desc"
[0][2] -> "etc"
I tryied to filter it:
lstContinente = (ListView)findViewById(R.id.list);
lstContinente.setTextFilterEnabled(true);
adapter = new PortaitArrayAdapter(cx,galleryValues);
lstContinente.setAdapter(adapter);
ed_busqueda.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
adapter.notifyDataSetChanged();
}
});
The adapter code:
public class PortaitArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[][] values;
private List<Imagen> imagenes = null;
private LayoutInflater mInflater;
public ImageLoader imageLoader;
public PortaitArrayAdapter(Context context, String[][] values) {
super(context, R.layout.gallery_row);
this.context = context;
this.values = values;
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imagenes = new ArrayList<Imagen>();
for (int i = 0; i < 20; i++) imagenes.add(new Imagen());
Bitmap def = BitmapFactory.decodeResource(this.context.getResources(),R.drawable.ic_launcher);
imageLoader=new ImageLoader(this.context,def, imagenes);
}
#Override
public int getCount (){
return this.values.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.gallery_row, parent, false);
holder.txtTitulo = (TextView) convertView.findViewById(R.id.txt_gallery_titulo);
holder.txtDesc = (TextView) convertView.findViewById(R.id.txt_gallery_desc);
holder.txtFecha = (TextView) convertView.findViewById(R.id.txt_gallery_fecha);
holder.txtEst = (TextView) convertView.findViewById(R.id.txt_gallery_est);
holder.imageView = (ImageView)convertView.findViewById(R.id.lst_img_gallery);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
/*LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.gallery_row, parent, false);*/
//ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
Bitmap bmp;
Log.v("Position --> ",String.valueOf(position));
try {
byte b[] = imagenes.get(position).getImageData();
if (b != null) {
bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
if (bmp != null) holder.imageView.setImageBitmap(bmp);
} else {
String urlBase = galleryValues[position][0].substring(0, galleryValues[position][0].lastIndexOf("/")+1);
String urlToEncode = galleryValues[position][0].substring(galleryValues[position][0].lastIndexOf("/")+1, galleryValues[position][0].length());
urlToEncode = URLEncoder.encode(urlToEncode,"UTF-8");
String url = urlBase.concat(urlToEncode);
url = url.replace("+", "%20");
Log.v("UrlFinal --> ",url);
imageLoader.DisplayImage(String.valueOf(position),url,act,holder.imageView, position,null);
}
} catch (Exception e) {
Log.e(this.getClass().getName(),"Exception en pos = " + position + " error:" + e.getMessage());
e.printStackTrace();
}
holder.txtTitulo.setText(galleryValues[position][1] + ", " + galleryValues[position][2]);
String[] dates = galleryValues[position][4].split("/");
String date = dates [1] + "/" + dates[0] + "/" + dates[2];
Date d1 = new Date(date);
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
holder.txtDesc.setText(galleryValues[position][3]);
holder.txtFecha.setText(df.format(d1));
holder.txtEst.setText(getText(R.string.num_fotos_gallery) + galleryValues[position][5] + " - " + getText(R.string.num_videos_gallery) + galleryValues[position][6] + " - " + getText(R.string.num_exp_gallery) + galleryValues[position][7]);
return convertView;
}
}
private static class ViewHolder {
TextView txtTitulo;
TextView txtDesc;
TextView txtFecha;
TextView txtEst;
ImageView imageView;
}
Convert your String array to ArrayList and pass it to Adapter and use below code or change below code with your String[].
You need to implement Filterable to your Adapter class and Override getFilter()
Checkout this complete example for filtering custom Adapter.
public class ListFilterActivity extends ListActivity {
private List<String> list = new ArrayList<String>();
List<String> mOriginalValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MyAdapter adapter = new MyAdapter(this, getModel());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.filterText);
// Add Text Change Listener to EditText
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<String> getModel() {
list.add("Linux");
list.add("Windows7");
list.add("Suse");
list.add("Eclipse");
list.add("Ubuntu");
list.add("Solaris");
list.add("Android");
list.add("iPhone");
list.add("Windows XP");
return list;
}
}
// Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<String> arrayList;
List<String> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<String> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(arrayList.get(position));
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
arrayList = (List<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String data = mOriginalValues.get(i);
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
Here I mention the code of how We can filter the listView Data using custom Adapter
Its really help you
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
public List<AllFoodItem> allFoodItemlist;
public ArrayList<AllFoodItem> arraylist;
public ListViewAdapter(Context context, List<AllFoodItem> allFoodItemlist) {
mContext = context;
this.allFoodItemlist = allFoodItemlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AllFoodItem>();
this.arraylist.addAll(allFoodItemlist);
}
#Override
public int getCount() {
return allFoodItemlist.size();
}
#Override
public AllFoodItem getItem(int position) {
return allFoodItemlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView foodname, quantity, calorie;
}
public View getView(final int position, View view, ViewGroup parent) {
Holder holder = new Holder();
view = inflater.inflate(R.layout.program_list, null);
// Locate the TextViews in listview_item.xml
holder.foodname = (TextView) view.findViewById(R.id.textView1);
// Set the results into TextViews holder.foodname.setText(allFoodItemlist.get(position).getName().toString());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
allFoodItemlist.clear();
if (charText.length() == 0) {
allFoodItemlist.addAll(arraylist);
} else {
for (AllFoodItem wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
allFoodItemlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
MainActivity.java
use the ListViewAdapter class apply filter on EditText by using filter() method
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
foodname = (inputSearch.getText().toString()).trim();
// filter the data of edit Text using filter method in ListViewAdapter
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
userGet();
// TODO Auto-generated method stub
}
});
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;}}