0

我是 android 开发的菜鸟,我对如何使用自定义基本适配器为 ListView 实现过滤功能感到完全困惑。我觉得我已经阅读了关于这个主题的所有问题,但仍然不知道我做错了什么。目前,当调用 onTextchanged 时,我的代码不会重新填充 listveiw。任何帮助是极大的赞赏。

主要活动

public class StoresActivity extends SherlockActivity {
 ArrayList<HashMap<String, String>> storeList;
 ListView list;
 LazyAdapter adapter;
 EditText inputSearch;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stores);

    storeList = new ArrayList<HashMap<String, String>>();
    list=(ListView)findViewById(R.id.list);
    SharedPreferences preferences = getSharedPreferences("Oleref", 2);      

    String employee = preferences.getString("employee", null);
    ActionBar bar = getSupportActionBar();
    bar.setDisplayHomeAsUpEnabled(true);
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] { "http://www.bigmoney.com"+ employee});
    try {
        storeList = task.get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    adapter=new LazyAdapter(this, storeList);
    list.setAdapter(adapter);
    list.setItemsCanFocus(true);


    //Search Bar for Listview
    inputSearch = (EditText) findViewById(R.id.inputSearch); //<--search bar 
    if(adapter!=null){
    }
     inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                try{
                    StoresActivity.this.adapter.getFilter().filter(cs);  //<--Does the narrowing down
                }catch(Exception e){
                    e.printStackTrace();
                }

            }

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

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub                          
            }
        }); 



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //getMenuInflater().inflate(R.menu.activity_pickens, menu);
    menu.add(0, 2, 0,"Walk In").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    return true;
} 

@Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) 
    {        
      case android.R.id.home:
          Intent chart = new Intent();
          chart.setClass(StoresActivity.this, StoresActivity.class);


          chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

      StoresActivity.this.startActivity(chart); 
            return true;
      case 2:

          Intent chart2 = new Intent();
          chart2.setClass(StoresActivity.this, WalkInActivity.class);

          chart2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

      StoresActivity.this.startActivity(chart2); 
            return true;


    }
    return true;
  }
public class DownloadWebPageTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>> {


    private final ProgressDialog dialog = new ProgressDialog(StoresActivity.this);
    protected void onPreExecute() {
        this.dialog.setMessage("Loading...");
        this.dialog.setCancelable(false);
        this.dialog.show();
    }
    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {

        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
        }

            }

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(String... urls) {

        ArrayList<HashMap<String, String>> storeList = new ArrayList<HashMap<String, String>>();
        for (String url : urls) {

            try {
                URL twitter = new URL(url);           
                  URLConnection tc = twitter.openConnection(); 
                  InputStreamReader reader = new InputStreamReader(tc.getInputStream());
                  BufferedReader in = new BufferedReader(reader);               
                  String line;             
                  while ((line = in.readLine()) != null) {                 
                      JSONArray ja = new JSONArray(line);                   
                      for (int i = 0; i < ja.length(); i++) {                     
                          JSONObject jo = (JSONObject) ja.get(i);                     

                          HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key =&gt; value

                            map.put("Address", jo.getString("Address"));
                            map.put("Store_Num", jo.getString("Store_Num"));
                            map.put("Store", jo.getString("Store"));
                            map.put("City", jo.getString("City"));
                            map.put("State", jo.getString("State"));
                            map.put("Zip", jo.getString("Zip"));
                            storeList.add(map);
                      }             
                  }    

              }

              catch (MalformedURLException e) {             
                  // TODO Auto-generated catch block             
                  e.printStackTrace();         
              } 
              catch (IOException e) {             
                  runOnUiThread(new Runnable(){

                        @Override
                        public void run() {
                    Toast.makeText(getApplicationContext(), "Error\nConnection Error", Toast.LENGTH_LONG).show();
                        }
                    });            
                  e.printStackTrace();         
              } 
              catch (JSONException e) {             
                  // TODO Auto-generated catch block             
                  e.printStackTrace();         
              }
        }
         HashMap<String, String> mapp = new HashMap<String, String>();
            // adding each child node to HashMap key =&gt; value
        return storeList;
    }
}


}

适配器

public class LazyAdapter extends BaseAdapter implements Filterable {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public String sn;
StoresActivity storesActivity;
HashMap<String, String> stores;
HashMap<String, String> storedata;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);          

    }

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return data.size();
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return arg0;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
     View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.store_row, null);

        TextView store = (TextView)vi.findViewById(R.id.storeText); // title
        TextView store_num = (TextView)vi.findViewById(R.id.store_num); // artist name
        TextView street = (TextView)vi.findViewById(R.id.address);
        TextView city = (TextView)vi.findViewById(R.id.city);
        Button newbutton=(Button)vi.findViewById(R.id.newser);
        Button historybutton=(Button)vi.findViewById(R.id.history);
        storedata = new HashMap<String, String>();
        storedata = data.get(position);
        newbutton.setTag(position);
         newbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent chart = new Intent();         
                  chart.setClass(v.getContext(), SectionActivity.class); 
                 storedata = data.get((Integer)v.getTag());
                  sn = storedata.get("Store_Num");
                  String store = storedata.get("Store");
                  chart.putExtra("sn", sn);
                  chart.putExtra("store", store);
                  chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

                  v.getContext().startActivity(chart); 
            }
        });

         historybutton.setTag(position);
         historybutton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                     Intent chart = new Intent();         
                      chart.setClass(v.getContext(), HistoryList.class); 
                     storedata = data.get((Integer)v.getTag());
                      sn = storedata.get("Store_Num");
                      String store = storedata.get("Store");
                      chart.putExtra("sn", sn);
                      chart.putExtra("store", store);
                      chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

                      v.getContext().startActivity(chart); 
                }
            });



        // Setting all values in listview
        store.setText(storedata.get("Store"));
        store_num.setText(storedata.get("Store_Num"));
        street.setText(storedata.get("Address"));
        city.setText(storedata.get("City") + " " + storedata.get("State") + " " + storedata.get("Zip"));

        return vi;
}
public boolean onLoadClass(Class arg0) {
    // TODO Auto-generated method stub
    return false;
}

//Added for search BJR 5-16-2013
public android.widget.Filter getFilter() {

    return new android.widget.Filter() {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults Result = new FilterResults();
            // if constraint is empty return the original names
            if (TextUtils.isEmpty(constraint)){
                //Result.values = storedata;
                Result.count = data.size();
                return Result;
            }

            ArrayList<HashMap<String, String>> Filtered_Names = new ArrayList<HashMap<String, String>>();
            String filterString = constraint.toString().toLowerCase();
            String filterableString;

            for(int i = 0; i<data.size(); i++){
                HashMap<String,String> searchdata = data.get(i);
                String store = searchdata.get("Store");
                String num = searchdata.get("Store_Num");
                String address = searchdata.get("Address");
                String city = searchdata.get("City");
                String state = searchdata.get("State");
                String zip = searchdata.get("Zip");
                filterableString = store+" "+num+" "+address+" "+city+" "+state+" "+zip;
                if(filterableString.toLowerCase().contains(filterString)){
                Filtered_Names.add(data.get(i));
                Log.e("Added", String.valueOf(Filtered_Names.size()));
                }

                }
            Result.values = Filtered_Names;
            Result.count = Filtered_Names.size();
            Log.e("Results", Result.values.toString() + String.valueOf(Result.count));
            return Result;
        }

    };
}


}
4

2 回答 2

2

您没有在 Filter#publishResults() 更改列表数据

在过滤器#performFiltering()

ArrayList<HashMap<String, String>> Filtered_Names = new ArrayList<String>();
for(int i = 0; i<data.size(); i++){
    // Filtered_Names#add()
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;

在过滤器#publishResult()

// do something check

ArrayList<HashMap<String, String>> resultList = 
                    (ArrayList<HashMap<String, String>>) results.values;
LazyAdapter.this.data = resultList;
LazyAdapter.this.notifyDataSetChanged();
于 2013-05-17T02:10:12.210 回答
0

constraint该方法的参数performFiltering()可以为空。

代替

if (constraint.length() == 0) // can produce NPE (NullPointerException) 

经过

if (TextUtils.isEmpty(constraint))
于 2013-05-16T22:09:17.697 回答