【问题标题】:Android - Search ListView content using BaseAdapterAndroid - 使用 BaseAdapter 搜索 ListView 内容
【发布时间】:2014-01-24 05:53:47
【问题描述】:

我有一个ListView,并且我使用BaseAdapter 插入了值,但我意识到要进行搜索,我们必须使用ArrayAdapter。我尝试这样做,但搜索失败。

JAVA 文件

package com.myrecipeapp.myrecipes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.myrecipeapp.R;
import com.myrecipeapp.database.DatabaseHandler;
import com.myrecipeapp.database.MyRecipesDatabaseModel;

import android.app.Activity;
import android.app.ListActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;


public class MyRecipes extends ListActivity
{

ListView list;  
byte[] b;

TextView back, hidden_text;
EditText search;

String r_name, r_tag;
Bitmap bmp;
int id;

Button delete;

int count;

DatabaseHandler db;
List<MyRecipesDatabaseModel> model;

MyRecipesDatabaseModel m;

MyRecipes_Adapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.myrecipes);
    //list = (ListView) findViewById(R.id.myrecipes_listView1);
    db = new DatabaseHandler(this);

    count = db.getRecipesCount();

    search = (EditText) findViewById(R.id.myrecipes_edittext_search);
    hidden_text = (TextView) findViewById(R.id.myrecipes_norecipe_textView1);
    delete = (Button) findViewById(R.id.myrecipes_button_delete);

    if(count==0)
    {
        hidden_text.setVisibility(View.VISIBLE);
        delete.setVisibility(View.INVISIBLE);
        search.setVisibility(View.INVISIBLE);

    }

    model = db.getAllRecipes();

    ArrayList<Map<String, String>> values = new ArrayList<Map<String, String>>();
    ArrayList<Map<String, Integer>> id_values = new ArrayList<Map<String, Integer>>();
    ArrayList<Map<String, Bitmap>> values_img = new ArrayList<Map<String, Bitmap>>();


    for (MyRecipesDatabaseModel cn : model)
    {
        b = cn.getImage();
        r_name = cn.getName();
        r_tag = cn.getTag();
        id = cn.getID();

        bmp = BitmapFactory.decodeByteArray(b, 0, b.length);

        HashMap<String, String> recipe = new HashMap<String, String>();
        recipe.put("RNAME", r_name);
        recipe.put("RTAG", r_tag);

        HashMap<String, Bitmap> image = new HashMap<String, Bitmap>();
        image.put("RIMAGE", bmp);

        HashMap<String, Integer> id_value = new HashMap<String, Integer>();
        id_value.put("RID", id);

        values.add(recipe);
        values_img.add(image);
        id_values.add(id_value);

    }



    setListAdapter(new MyRecipes_Adapter(this, values, values_img, id_values));

    //adapter = new MyRecipes_Adapter(this, values, values_img, id_values);         
//      list.setLAdapter(adapter);


    search.addTextChangedListener(new TextWatcher()
    {

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
        {
            // TODO Auto-generated method stub

            MyRecipes.this.adapter.getFilter().filter(arg0);


        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
        {
            // TODO Auto-generated method stub

        }

        public void afterTextChanged(Editable arg0)
        {
            // TODO Auto-generated method stub

        }
    });

   }
 }

适配器文件

package com.myrecipeapp.myrecipes;

import java.util.ArrayList;
import java.util.Map;

import com.myrecipeapp.R;
import com.myrecipeapp.database.DatabaseHandler;
import com.myrecipeapp.database.MyRecipesDatabaseModel;
import com.myrecipeapp.webclip.Clip_from_web_edit;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

 public class MyRecipes_Adapter extends ArrayAdapter<ArrayList<Map<String, String>>>
 {

MyRecipes context;   
ArrayList<Map<String, String>> values;
ArrayList<Map<String, Bitmap>> values_img;
ArrayList<Map<String, Integer>> id_values;

byte[] b;

Boolean delete = false;
int delete_id;
RelativeLayout rl;

DatabaseHandler db;
MyRecipesDatabaseModel model;

public MyRecipes_Adapter(MyRecipes context,
        ArrayList<Map<String, String>> values, ArrayList<Map<String, Bitmap>> values_img,
        ArrayList<Map<String, Integer>> id_values) {
    super(context, R.layout.myrecipes_adapter);
    // TODO Auto-generated constructor stub

    this.context = context;
    this.values = values;
    this.values_img = values_img;   
    this.id_values = id_values;
}


@Override
public View getView(int arg0, View arg1, ViewGroup arg2)
{
    // TODO Auto-generated method stub

    View view;      

    if(arg1==null)
    {
        LayoutInflater inflater = (LayoutInflater) context.getLayoutInflater();
        view = inflater.inflate(R.layout.myrecipes_adapter, arg2, false);

        ImageView iv = (ImageView) view.findViewById(R.id.myrecipes_adapter_imageView1);
        TextView tv1 = (TextView) view.findViewById(R.id.myrecipes_adapter_textView1);
        TextView tv2 = (TextView) view.findViewById(R.id.myrecipes_adapter_textView2);
        final TextView tv3 = (TextView) view.findViewById(R.id.myrecipes_adapter_textView3);
        rl = (RelativeLayout) view.findViewById(R.id.myrecipes_adapter_reltivelayout);

        iv.setImageBitmap(values_img.get(arg0).get("RIMAGE"));          
        tv1.setText(values.get(arg0).get("RNAME"));
        tv2.setText("#"+values.get(arg0).get("RTAG"));
        tv3.setText(id_values.get(arg0).get("RID").toString());

    }
    else
    {
        view = arg1;
    }

    return view;
    }
   }

我想按 RecipeName 进行搜索。我错过了什么??

【问题讨论】:

  • 创建您的自定义搜索过滤器
  • 检查我的 ListActivity 代码..我已经创建了..
  • 你在哪里创建的?
  • @Mitesh 请接受其中一个答案或发布您的答案。

标签: android listview


【解决方案1】:

终于找到了解决办法。

无需更改适配器类中的任何内容。只需更改 EditText's TextChangeListener 的 Java 类

代码如下:

search.addTextChangedListener(new TextWatcher()
    {

        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
          //get the text in the EditText
           searchString=search.getText().toString();
           int textLength=searchString.length();
           ArrayList<Map<String, String>> searchResults = new ArrayList<Map<String, String>>();
           ArrayList<Map<String, Bitmap>> searchResultsImages = new ArrayList<Map<String, Bitmap>>();
           ArrayList<Map<String, Integer>> searchResultsId = new ArrayList<Map<String, Integer>>();

              for(int i=0;i<values.size();i++)
              {
                  String rname = values.get(i).get("RNAME").toString();
                  System.out.println("recipe name "+rname);
                  if(textLength<=rname.length())
                  {
                        //compare the String in EditText with Names in the ArrayList
                        if(searchString.equalsIgnoreCase(rname.substring(0,textLength)))
                        {
                                searchResults.add(values.get(i));
                                searchResultsImages.add(values_img.get(i));
                                searchResultsId.add(id_values.get(i));

                                System.out.println("the array list is "+values.get(i));
                                adapter.notifyDataSetChanged();
                                list.invalidate(); 
                                adapter=new MyRecipes_Adapter(MyRecipes.this, searchResults,  searchResultsImages, searchResultsId);
                                list.setAdapter(adapter);

                        }
                 }
              }
              if(searchResults.isEmpty())
              {
                if(count_items==0)
                {
                     //do nothing
                }
                else
                {
                      ll.setVisibility(View.INVISIBLE);
                      Toast toast= Toast.makeText(getApplicationContext(), 
                      "No Items Matched", Toast.LENGTH_SHORT);  
                      toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
                      toast.show();
                }
              }       
        }

          public void beforeTextChanged(CharSequence s, int start, int count, int after)
          {
                 System.out.println("before changed");
                 ll.setVisibility(View.VISIBLE);
                 list.invalidate();
                 adapter.notifyDataSetChanged();
          }

          public void afterTextChanged(Editable s)
          {
                 System.out.println("after changed");                    
                 list.invalidate();
                 adapter.notifyDataSetChanged();
          }          
    });

【讨论】:

    【解决方案2】:

    在您的列表活动中创建这样的过滤器:

    public static List<YourDataObject> filter(String string,
            Iterable<YourDataObject> iterable, boolean byName) {
        if (iterable == null)
            return new LinkedList<YourDataObject>();
        else {
            List<YourDataObject> collected = new LinkedList<YourDataObject>();
            Iterator<YourDataObject> iterator = iterable.iterator();
            if (iterator == null)
                return collected;
            while (iterator.hasNext()) {
                YourDataObject item = iterator.next();
    
                if (item.name.toLowerCase().contains(string.toLowerCase()))
                        collected.add(item);
    
            }
            return collected;
        }
    

    从 ontextchangelistener 调用它:

    List<YourDataObject> list = filter(s.toString(),
                                YourDataObject, true);
                        YourDataObject.addAll(list);
    

    然后再次调用 setAdapter。

    【讨论】:

    • YourDataObject 是你的 id_values。
    • 和它的HashMap..你用的是List??
    • 您正在使用 HashMap 的 ArrayList 并在过滤器中获取 hashmap 然后从该 hashmap 中获取 recipename 并比较您输入的单词。
    • 但是要写什么而不是 YourDataObject。它不允许我
    【解决方案3】:

    用这个替换自定义过滤器

    public static List<HashMap<String, String>> filter(String string,
            Iterable<HashMap<String, String>> iterable, boolean byName) {
        if (iterable == null)
            return new LinkedList<HashMap<String, String>>();
        else {
            List<HashMap<String, String>> collected = new LinkedList<HashMap<String, String>>();
            Iterator<HashMap<String, String>> iterator = iterable.iterator();
            if (iterator == null)
                return collected;
            while (iterator.hasNext()) {
                HashMap<String, String> item = iterator.next();
    
                if (item.get("recipename").toLowerCase().contains(string.toLowerCase()))
                    collected.add(item);
    
            }
            return collected;
        }
    }
    

    【讨论】:

    • 我需要粘贴到Activity类或者适配器类吗?
    • 在 Activity 类中...并从您的搜索框文本更改事件监听器中调用它
    • Dude.. 在 textafterchanged() 中写什么你已经在过滤函数中定义为迭代器.. 我只有 arraylist 和 hashmap
    猜你喜欢
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2011-09-28
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多