0

私はAndroid開発の初心者であり、カスタムベースアダプターを使用してListViewのフィルタリング機能を実装する方法について完全に混乱しています。このトピックに関するSOのすべての質問を読んだような気がしますが、何が間違っているのかまだわかりません。現在、私のコードは 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() でリストのデータを変更していません

in Filter#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;

Filter#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

メソッドのパラメーターconstraintperformFiltering()null にすることができます。

交換

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

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