搜索清除ListView中的所有对象

时间:2014-01-05 21:30:48

标签: android listview search filter parse-platform

我的搜索过滤器出了问题。当我开始输入时,所有对象都消失了,不执行任何搜索。只有刷新后他们才会回来。当我尝试通过Toast进行校对时,调用适配器中的if (wp.getAnimal().toLowerCase(Locale.getDefault()) .contains(text)),而不是toast视图。

你有什么想法,问题出在哪里?提前谢谢!

带有EditText侦听器的我的MainActivity类

public class MainActivity extends ActionBarActivity{
private ListView mListView;
private AnimalAdapter mAdapter;
ProgressBar mProgressBar;
EditText mEditText;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Add your initialization code here
    Parse.initialize(this, "code", "code");
    ParseObject.registerSubclass(Animal.class);
    ParseAnalytics.trackAppOpened(getIntent());
    View header = getLayoutInflater().inflate(R.layout.header, null);
    header.setPadding(2, 8, 4, 2);



    mListView = (ListView) findViewById(R.id.animal_list);
    mListView.setVisibility(View.INVISIBLE);

    mListView.addHeaderView(header);


    mProgressBar = (ProgressBar) findViewById (R.id.loading_animals);
    mProgressBar.setVisibility(View.VISIBLE);





    RemoteDataTask task = new RemoteDataTask();
    task.execute();




}








 public void updateData(){


     ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
  query.setCachePolicy(CachePolicy.CACHE_THEN_NETWORK);
query.orderByAscending("animal");
  query.findInBackground(new FindCallback<Animal>() {

      @Override
      public void done(List<Animal> animals, ParseException error) {

          if(animals != null){
              mAdapter.clear();
           mProgressBar.setVisibility(View.INVISIBLE);
          for (int i = 0; i < animals.size(); i++) {

                  mAdapter.add(animals.get(i));

              }


          }



      }
  });
}


 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


     public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_refresh:
                Intent refreshIntent = new Intent(MainActivity.this, MainActivity.class);
                refreshIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                refreshIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                startActivity(refreshIntent);
                overridePendingTransition(0,0);
                     return true; 
             } 
        return super.onOptionsItemSelected(item);
     }



     private class RemoteDataTask extends AsyncTask<Void, Void, Void> {




         @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog





            }


         @Override
            protected Void doInBackground(Void... params) {

                updateData();


                return null;
            }


         @Override
            protected void onPostExecute(Void result) {

             mListView = (ListView) findViewById(R.id.animal_list);
                // Pass the results into ListViewAdapter.java
             mAdapter = new AnimalAdapter(MainActivity.this, new ArrayList<Animal>());


                mListView.setAdapter(mAdapter);
                mListView.setVisibility(View.VISIBLE);
                mListView.setTextFilterEnabled(true);

                mEditText = (EditText) findViewById(R.id.search_animal);
                  mEditText.addTextChangedListener(new TextWatcher(){

                    @Override
                    public void afterTextChanged(Editable s) {
                        mListView.setVisibility(View.VISIBLE);

                    }

                    @Override
                    public void beforeTextChanged(CharSequence s,
                            int start, int count, int after) {
                        mListView.setVisibility(View.VISIBLE);

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start,
                            int before, int count) {
                        mListView.setVisibility(View.VISIBLE);
                        String text = mEditText.getText().toString()
                                .toLowerCase(Locale.getDefault());
                        mAdapter.filter(text);


                    }
                });
                  }

         }

     }

我的Adapter类,包含过滤方法

public class AnimalAdapter extends ArrayAdapter<Animal> implements Filterable{
private Context mContext;
private List<Animal> mAnimals;
ImageLoader imageLoader;
ArrayList<Animal> array;
DisplayImageOptions options;
Activity activity;
private Filter animalFilter;
private List<Animal> animaly;

@SuppressWarnings("deprecation")
public AnimalAdapter(Context context, List<Animal> objects) {
      super(context, R.layout.animal_row_item, objects);


      ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();

      imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);
        options = new DisplayImageOptions.Builder()
        .cacheInMemory()
        .cacheOnDisc()
        .build();

        this.mContext = context;
        this.mAnimals = objects;
        this.animaly = objects;

  }

public View getView(int position, View convertView, ViewGroup parent){
      if(convertView == null){
          LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
          convertView = mLayoutInflater.inflate(R.layout.animal_row_item, null);
      }


      final Animal animal = mAnimals.get(position);


      TextView animalView = (TextView) convertView.findViewById(R.id.animal_text);
      TextView areaView = (TextView) convertView.findViewById(R.id.area_text);

      final ImageView animalPic = (ImageView)convertView.findViewById(R.id.animal_pic);
      final ProgressBar indicator = (ProgressBar)convertView.findViewById(R.id.progress);

      indicator.setVisibility(View.VISIBLE);
      animalPic.setVisibility(View.INVISIBLE);

        //Setup a listener we can use to switch from the loading indicator to the Image once it's ready
        ImageLoadingListener listener = new ImageLoadingListener(){



            @Override
            public void onLoadingStarted(String arg0, View arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLoadingCancelled(String arg0, View arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
                indicator.setVisibility(View.INVISIBLE);
                animalPic.setVisibility(View.VISIBLE);
            }

            @Override
            public void onLoadingFailed(String arg0, View view, FailReason arg2) {


            }

        };

      imageLoader.displayImage(getItem(position).getImgUrl(), animalPic,options, listener);
      animalView.setText(animal.getAnimal());
      areaView.setText(animal.getArea());


      convertView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getContext(), MoreActivity.class);

                intent.putExtra("about", animal.getAbout());
                intent.putExtra("animal", animal.getAnimal());
                intent.putExtra("imgUrl", animal.getImgUrl());
                getContext().startActivity(intent);
            }
      });

      return convertView;
  }




 public int getCount() {}
     return mAnimals.size();




 public void filter(String text) {




        if (text.length() == 0) {
            mAnimals.addAll(animaly);
            Toast.makeText(getContext(), "text 0", Toast.LENGTH_SHORT).show();

        } else {
            mAnimals.clear();
            for (Animal wp : animaly) {
              if (wp.getAnimal().toLowerCase(Locale.getDefault())
                        .contains(text)) {
                    Toast.makeText(getContext(), "contains", Toast.LENGTH_SHORT).show();
                    mAnimals.add(wp);

            }



        }}
        notifyDataSetChanged();
    }

}

1 个答案:

答案 0 :(得分:0)

我刚刚用一点点不同的方式解决了这个问题。对于很棒的教程检查/代码:

  • 有关教程检查this
  • 对于整个代码,请检查this
祝你好运,祝你有个美好的一天!