不能够实现可扩展列表视图搜索 [英] Not able to implement search in Expandable list view

查看:184
本文介绍了不能够实现可扩展列表视图搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现在扩展列表视图搜索过滤器。

I am trying to implement Search filter in expandable list view.

但是,当我试图在EDITTEXT输入关键字,应用程序时坠毁。

But when I am trying to enter keyword in editText, application gets crashed.

下面是两个Java类 MainActivity ExpandableListAdapter

Below are two java classes of MainActivity and ExpandableListAdapter.

MainActivity类别

package com.ahmedabadjobs.dashboard;

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

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import androidhive.dashboard.R;

import com.ahmedabadjobs.expandablelistview.ExpandableListAdapter;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */

    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;
    EditText inputSearch;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get the listview
        expListView = (ExpandableListView) findViewById(R.id.lvExp);

        // preparing list data
        prepareListData();

        listAdapter = new ExpandableListAdapter(this, listDataHeader,
                listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);

        // Listview Group click listener
        expListView.setOnGroupClickListener(new OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                    int groupPosition, long id) {
                // Toast.makeText(getApplicationContext(),
                // "Group Clicked " + listDataHeader.get(groupPosition),
                // Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        inputSearch = (EditText) findViewById(R.id.inputSearch);

        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                    int arg3) {
                // ((Filter) listAdapter.getFilter()).filter(cs);
                NewsFeedActivity.this.listAdapter.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) {
                // When user changed the Text

            }
        });

    }

    /*
     * Preparing the list data
     */
    private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();

        // Adding child data
        listDataHeader.add("Company 0");
        listDataHeader.add("Company 1");
        listDataHeader.add("Company 2");

        // Adding child data
        List<String> cignex = new ArrayList<String>();
        company0.add("Address Line 1");
        company0.add("Address Line 2");
        company0.add("Address Line 3");
        company0.add("Phone number");
        company0.add("Email Address");

        List<String> company1 = new ArrayList<String>();
        company1.add("Address Line 1");
        company1.add("Address Line 2");
        company1.add("Address Line 3");
        company1.add("Phone number");
        company1.add("Email Address");

        List<String> company2 = new ArrayList<String>();
        company2.add("Address Line 1");
        company2.add("Address Line 2");
        company2.add("Address Line 3");
        company2.add("Phone number");
        company2.add("Email Address");

        listDataChild.put(listDataHeader.get(0), company0); // Header, Child
                                                            // data
        listDataChild.put(listDataHeader.get(1), company1);
        listDataChild.put(listDataHeader.get(2), company2);
    }

}

ExpandableListAdapter类

package com.ahmedabadjobs.expandablelistview;

import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidhive.dashboard.R;

public class ExpandableListAdapter extends BaseExpandableListAdapter implements
        Filterable {

    private Context _context;
    private List<String> _listDataHeader; // header titles
    // child data in format of header title, child title
    private HashMap<String, List<String>> _listDataChild;

    public ExpandableListAdapter(Context context, List<String> listDataHeader,
            HashMap<String, List<String>> listChildData) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {

        final String childText = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_item, null);
        }

        TextView txtListChild = (TextView) convertView
                .findViewById(R.id.lblListItem);

        txtListChild.setText(childText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_group, null);
        }

        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.lblListHeader);
        lblListHeader.setTypeface(null, Typeface.BOLD);
        lblListHeader.setText(headerTitle);

        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    @Override
    public Filter getFilter() {
        // TODO Auto-generated method stub
        return null;
    }

}

在EDITTEXT提供关键字时,我得到娄错误。

I am getting bellow error when providing keyword in editText.

12-09 03:37:48.080: E/InputEventSender(1139): Exception dispatching finished signal.
12-09 03:37:48.080: E/MessageQueue-JNI(1139): Exception in MessageQueue callback: handleReceiveCallback
12-09 03:37:48.161: E/MessageQueue-JNI(1139): java.lang.NullPointerException

请让我知道什么样的变化,我需要做,使之功能。

Please let me know what changes I need to make to make it functional.

推荐答案

按如下方式使用editext

use editext as follows

edit=(EditText)findViewById(R.id.editText1);
                edit.addTextChangedListener(filterTextWatcher);

写textwatcher

write a textwatcher

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) 
        {  

        }

    public void afterTextChanged(Editable s) 
        {
        // TODO Auto-generated method stub
        ((Filterable) ((ListAdapter) Adapter)).getFilter().filter(edit.getText().toString());
        }  
    };

做listadapter如下:

make a listadapter as follows

public class ListAdapter extends BaseExpandableListAdapter  implements Filterable {


        public void notifyDataSetInvalidated()
        {
            super.notifyDataSetInvalidated();
        }
          public Filter getFilter()
          {
            if(filter == null)
                  filter = new MangaNameFilter();
              return filter;
          }

Filter类如下:

a Filter class as follows

private class MangaNameFilter extends Filter
          {

              @Override
              protected FilterResults performFiltering(CharSequence constraint) {
                  // NOTE: this function is *always* called from a background thread, and
                  // not the UI thread.
                  constraint = edit.getText().toString().toLowerCase();
                  FilterResults result = new FilterResults();
                  if(constraint != null && constraint.toString().length() > 0)
                  {
                      detailsList=detailsSer.GetAlldetails();
                      dupCatList=detailsList;

                      ArrayList<detailsEntity> filt = new ArrayList<detailsEntity>();
                      ArrayList<detailsEntity> lItems = new ArrayList<detailsEntity>();
                      synchronized(this)
                      {
                          lItems.addAll(dupCatList);
                      }
                      for(int i = 0, l = lItems.size(); i < l; i++)
                      {
                          detailsEntity m = lItems.get(i);
                          if(m.description.toLowerCase().contains(constraint))
                          filt.add(m);
                      }
                      result.count = filt.size();
                      result.values = filt;
                  }
                  else
                  {
                      detailsList=detailsSer.GetAlldetails();
                      dupCatList=detailsList;
                      synchronized(this)
                      {
                          result.count = dupCatList.size();
                          result.values = dupCatList;
                      }
                  }
                  return result;
              }
              @SuppressWarnings("unchecked")
              @Override
              protected void publishResults(CharSequence constraint, FilterResults result) {
                  // NOTE: this function is *always* called from the UI thread.

                  filtered = (ArrayList<detailsEntity>)result.values;

                  ArrayList<Integer> IdList = new ArrayList<Integer>();
                IdList.clear();
                for(int i=0;i<filtered.size();i++)
                {
                    IdList.add(filtered.get(i).catID);
                }

                HashSet<Integer> hashSet = new HashSet<Integer>(IdList);
                midList = new ArrayList<Integer>(hashSet) ;
                Collections.sort(midList);
                Adapter = new CategoryListAdapter(context, R.layout.list1, R.layout.list2, filtered, midList);
                        List.setAdapter(Adapter);

}

这篇关于不能够实现可扩展列表视图搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆