Android CustomListAdapter无法获取过滤器

时间:2015-09-02 20:27:09

标签: java android

我有这个代码工作正常,在listview上显示我的产品。现在我正在尝试在操作栏上实现搜索。

我有一个CustomListAdapter,我正在读这个How to implement getfilter()...

我更改了我的CustomListADapter,以便在我在搜索操作栏上输入时显示结果。我在输入时遇到异常:

09-02 15:45:17.153: I/System.out(2135): on text chnge text: Tec
09-02 15:45:17.205: W/Filter(2135): An exception occured during performFiltering()!
09-02 15:45:17.205: W/Filter(2135): java.lang.NullPointerException
09-02 15:45:17.205: W/Filter(2135):     at com.habitodigital.products.adapter.CustomListAdapter$1.performFiltering(CustomListAdapter.java:131)
09-02 15:45:17.205: W/Filter(2135):     at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
09-02 15:45:17.205: W/Filter(2135):     at android.os.Handler.dispatchMessage(Handler.java:102)
09-02 15:45:17.205: W/Filter(2135):     at android.os.Looper.loop(Looper.java:136)
09-02 15:45:17.205: W/Filter(2135):     at android.os.HandlerThread.run(HandlerThread.java:61)

CustomListAdapter.java

public class CustomListAdapter extends BaseAdapter implements Filterable {

public ImageView thumbNail;
TextView p_id, name;

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.showImageOnFail(R.drawable.no_image_available)
.showImageForEmptyUri(R.drawable.no_image_available)
.cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();

private Activity activity;
private LayoutInflater inflater;
private List<Product> pItems;
ImageLoader imageLoader = ImageLoader.getInstance();

private ArrayList<HashMap<String, String>> originalData;
private ArrayList<HashMap<String, String>> filteredData;

public CustomListAdapter(Activity activity, List<Product> pItems) {
    this.activity = activity;
    this.pItems = pItems;
}

@Override
public int getCount() {
    return pItems.size();
}

@Override
public Object getItem(int location) {
    return pItems.get(location);
}

@Override
public long getItemId(int position) {
    return position;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.list_row, null);

    p_id = (TextView) convertView.findViewById(R.id.p_id);
    thumbNail = (ImageView) convertView
            .findViewById(R.id.thumbnail);
    name = (TextView) convertView.findViewById(R.id.name);

    Product m = pItems.get(position);

    p_id.setText(m.getP_id());

    String url = m.getThumbnailUrl();

    Picasso.with(activity).load(url).resize(80, 80).centerCrop().into(thumbNail);

    thumbNail.setTag(url);

    name.setText(m.getName());

    return convertView;
}

@Override
public Filter getFilter() {

    return new Filter(){

        @Override
        protected FilterResults performFiltering(CharSequence charSequence){

            FilterResults results = new FilterResults();

            /* if nothing to filter, return original list results */
            if(charSequence == null || charSequence.length() == 0){
                results.values = originalData;
                results.count = originalData.size();
            }else{
                ArrayList<HashMap<String, String>> filterResultsData = new ArrayList<HashMap<String,String>>();
                for(HashMap<String, String> data : originalData){
                    if(charSequence == originalData){ 
                        filterResultsData.add(data);
                    }
                }

                results.values = filterResultsData;
                results.count = filterResultsData.size();
            }


            return results;
        }

        @Override
        protected void publishResults(CharSequence charSequence,
                FilterResults results) {
            filteredData = (ArrayList<HashMap<String,String>>) results.values;
            notifyDataSetChanged();
        }

    };

}

}

ListView活动:

public class ListProducts extends Activity {

TextView state, t_city, noProduct;
String city = "", statee = "";
ImageButton newSch;

// Log tag
    private static final String TAG = ListProducts.class.getSimpleName();

    private static final String url = "http://mywebsite.com/json.php";

    private List<Product> pList = new ArrayList<Product>();
    private ListView listView;
    private CustomListAdapter adapter;

    private static final String TAG_PID = "p_id";
    private static final String TAG_ARQUIVO = "file";
    private static final String TAG_NAME = "name";

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

    handleIntent(getIntent());

    state = (TextView) findViewById(R.id.State);
    t_city = (TextView) findViewById(R.id.City);
    noProduct = (TextView) findViewById(R.id.noProduct);
    newSch = (ImageButton) findViewById(R.id.newSch);       

    state.setText(getIntent().getExtras().getString("state"));      
    t_city.setText(getIntent().getExtras().getString("city"));

    listView = (ListView) findViewById(R.id.list);
    adapter = new CustomListAdapter(this, pList);

    new LoadAsync().execute();

    newSch.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent newS = new Intent(getApplicationContext(), SearchCity.class);
            startActivity(newS);                
        }
    });


}

public class LoadAsync extends AsyncTask<String, Boolean, Boolean>{
    public ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ListProduct.this);
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        // Creating volley request obj
        JsonArrayRequest pReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        pDialog.dismiss();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Product product = new Product();

                                product.setP_id(obj.getString("p_id"));
                                product.setName(obj.getString("name"));
                            product.setThumbnailUrl(obj.getString("file"));

                                city = obj.getString("city");
                                statee = obj.getString("state");

   if(state.getText().toString().equalsIgnoreCase(statee) && 
                            t_.getText().toString().equalsIgnoreCase(city)){

                                    pList.add(product);

                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } if(pList.size() > 0){

                            listView.setAdapter(adapter);
                            listView.setTextFilterEnabled(true);

                        }else{
                            noP.setText("Oops! No product");


                        }

                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.dismiss();

                    }
                });

        AppController.getInstance().addToRequestQueue(pReq);

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                String pID = ((TextView) view.findViewById(R.id.p_id)).getText().toString();

                ImageView pFile = ((ImageView) view.findViewById(R.id.thumbnail));
                String imgUrl = (String) pFile.getTag();

                String pName = ((TextView) view.findViewById(R.id.name)).getText().toString();

                Intent i = new Intent(getApplicationContext(), PDetails.class);

                i.putExtra(TAG_PID, pID);
                i.putExtra(TAG_ARQUIVO, imgUrl);
                i.putExtra(TAG_NAME, pName);
                startActivity(i);

            }
        }); 

        return null;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        //pDialog.dismiss();

    }   
}


@Override
protected void onNewIntent(Intent intent) {
    handleIntent(intent);
}

private void handleIntent(Intent intent) {

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        //use the query to search your data somehow
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.list_products, menu);

    SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();

searchView.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false);

    SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.getFilter().filter(newText);
            System.out.println("on text chnge text: "+ newText);
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            adapter.getFilter().filter(query);
            System.out.println("on query submit: "+query);
            return false;
        }           
    };

    searchView.setOnQueryTextListener(textChangeListener);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

我是否正确地将它与for循环进行比较?

FilterResults results = new FilterResults();

/* if nothing to filter, return original list results */
if(charSequence == null || charSequence.length() == 0){
  results.values = pItems;
  results.count = pItems.size();
}else{

for(Product data : pItems){
    if(charSequence == pItems){
        pItems.add(data);
    }
}

results.values = pItems;
results.count = pItems.size();
}

return results;

1 个答案:

答案 0 :(得分:0)

经过一些搜索后,我将过滤器更改为

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]