在我的CustomListAdapter

时间:2015-11-04 18:48:48

标签: android listview android-listview baseadapter android-search

我在这里有两个问题。

  • 第一个问题是:: 在我的CustomListAdapter中实现Filterable接口以启用列表数据搜索后,我意识到每次尝试重新加载列表视图时,它拒绝填充列表视图,即使我能够从我的服务器获取数据。 (我的ListView总是在设备方向更改时重新加载,我还添加了一个重新加载按钮来重新加载listView onclick)

  • 第二个问题是:: 我的搜索EditView非常好地填充了我的listView但是我意识到当我清空EditView时,ListView中的先前数据不会还原/来 - 回到之前的内容

以下是我的活动代码

public class MainActivity extends Activity {

   private ListView mList;
   private List<Movie> movieList = new ArrayList<Movie>();
   EditText inputSearch;
       private CustomListAdapter adapter;
   private ImageView  reload_img;


    protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
           setContentView(R.layout.activity_main);

       mList = (ListView) findViewById(R.id.list);
       inputSearch = (EditText) findViewById(R.id.inputSearch);
           reload_img = (ImageView) findViewById(R.id.reload_list);


           adapter = new CustomListAdapter(this, movieList);
           mList.setAdapter(adapter);

        //FETCH Movie-Data FROM SERVER TO LIST
         fetchMovie();

        //Reload image click
             reload_img.setOnClickListener(new View.OnClickListener() {
             public void onClick(View arg0) {

                    reload_list();
                    }
            });

        //SEARCH TEXTCHANGE
        inputSearch.addTextChangedListener(new TextWatcher() {

             @Override
             public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                   // When user changed the Text
                  MainActivity.this.adapter.getFilter().filter(cs.toString());
                //FLAGS Cannot resolve method 'getFilter()' here
                }

             @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
             }
          });




    }


    //RELOAD LISTVIEW METHOD
            private void reload_list()
            {

                pDialog = new ProgressDialog(MainActivity.this);
                // Showing progress dialog before making http request
                pDialog.setMessage("Synchronising....");
                pDialog.show();
                pDialog.setCancelable(false);
                pDialog.setCanceledOnTouchOutside(false);


                flag_loading = true;
                offSet = 0;
                inputSearch.setText("");
                movieList.clear();

                fetchMovie();
                //adapter.notifyDataSetChanged();



            }


    //LOAD DATA FROM SERVER TO LISTVIEW USING VOLLEY
    private void fetchMovie()
            {

                // showing refresh animation before making http call
                //swipeRefreshLayout.setRefreshing(true);

                // appending offset to url
               String url = Config.URL_TOP_250_URL + offSet;
                //String url = Config.MOVIE_JSON_URL;
               //String url = Config.MOVIE_JSON_URL_SHORT;

               // Toast.makeText(MainActivity.this,
                 //       "::Json loaded:: ", Toast.LENGTH_SHORT).show();

                JsonArrayRequest movieReq = new JsonArrayRequest(url,
                        new Response.Listener<JSONArray>() {
                            @Override
                            public void onResponse(JSONArray response) {
                                // Log.d(TAG, response.toString());
                                hidePDialog();

                                if (response.length() > 0) {

                                    //Toast.makeText(MainActivity.this,
                                      //     "Json String : \n"+ response.toString(), Toast.LENGTH_LONG).show();

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

                                            JSONObject obj = response.getJSONObject(i);

                                            int rank = obj.getInt("rank");

                                            Movie movie = new Movie();

                                            // movie.setRank(obj.getInt("rank"));

                                            movie.setTitle(obj.getString("title"));
                                            movie.setThumbnailUrl(obj.getString("image"));
                                            movie.setRating(((Number) obj.get("rating"))
                                                    .doubleValue());

                                            movie.setYear(obj.getInt("releaseYear"));

                                            // Genre is json array
                                            JSONArray genreArry = obj.getJSONArray("genre");
                                            ArrayList<String> genre = new ArrayList<String>();
                                            for (int j = 0; j < genreArry.length(); j++) {
                                                genre.add((String) genreArry.get(j));
                                            }
                                            movie.setGenre(genre);

                                            // adding movie to movies array
                                            movieList.add(movie);

                                            // updating offset value to highest value
                                            if (rank >= offSet)
                                                offSet = rank;
                                            flag_loading = false;
                                        } catch (JSONException e) {
                                            e.printStackTrace();

                                            Toast.makeText(MainActivity.this,
                                                    "Network connection error \n "+  e.getMessage(), Toast.LENGTH_LONG).show();
                                        }

                                    }
                                    /**/

                                    // notifying list adapter about data changes
                                    // so that it renders the list view with updated data
                                    adapter.notifyDataSetChanged();

                                }
                                else {
                                    Toast.makeText(MainActivity.this,
                                            "End of movie-list" , Toast.LENGTH_LONG).show();

                                }


                            }




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


                    }

                });

                // Adding request to request queue
                MyApplication.getInstance().addToRequestQueue(movieReq);
            }


}

这是我的CustomListAdapter中的代码

public class CustomListAdapter extends BaseAdapter {

         private Activity activity;
     private LayoutInflater inflater;
     private List<Movie> movieItems;
      private List<Movie> originalMovieList;
         private String[] bgColors;
     private List<String>originalData = null;
     private List<String>filteredData = null;
     private ItemFilter mFilter = new ItemFilter();
         ImageLoader imageLoader = MyApplication.getInstance().getImageLoader();


         public CustomListAdapter(Activity activity, List<Movie> movieItems) {
             this.activity = activity;
             this.movieItems = movieItems;
        this.originalMovieList = movieItems;
             bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
         }
         @Override
         public int getCount() {
                return movieItems.size();
         }

         @Override
        public Object getItem(int location) {
             return movieItems.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_image, null);

             if (imageLoader == null)
              imageLoader = MyApplication.getInstance().getImageLoader();
            NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);

             TextView serial = (TextView) convertView.findViewById(R.id.serial);
            TextView title = (TextView) convertView.findViewById(R.id.title);
            TextView rating = (TextView) convertView.findViewById(R.id.rating);
            TextView genre = (TextView) convertView.findViewById(R.id.genre);
            TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

            // getting movie data for the row
            Movie m = movieItems.get(position);

            // thumbnail image
            thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

            // title
            title.setText(m.getTitle());

            // rating
             rating.setText("Rating: " + String.valueOf(m.getRating()));

            // genre
            String genreStr = "";
            for (String str : m.getGenre()) {
              genreStr += str + ", ";
              }
            genreStr = genreStr.length() > 0 ? genreStr.substring(0,
                 genreStr.length() - 2) : genreStr;
             genre.setText(genreStr);

            // release year
             year.setText(String.valueOf(m.getYear()));

             String color = bgColors[position % bgColors.length];
            serial.setBackgroundColor(Color.parseColor(color));




            return convertView;
     }




            public Filter getFilter() {
                return mFilter;
            }

            private class ItemFilter extends Filter {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {

                    String filterString = constraint.toString().toLowerCase();

                    FilterResults results = new FilterResults();

                    //final List<String> list = originalData;
                    final List<Movie> list = movieItems;

                    int count = list.size();
                   // final ArrayList<String> nlist = new ArrayList<String>(count);
                    final ArrayList<Movie> nlist = new ArrayList<Movie>(count);

                    String filterableString ;

                    for (int i = 0; i < count; i++) {
                        filterableString = list.get(i).getTitle();
                        if (filterableString.toLowerCase().contains(filterString)) {
                           // nlist.add(filterableString);
                            nlist.add(list.get(i));
                        }
                    }

                    results.values = nlist;
                    results.count = nlist.size();

                    return results;
                }

                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    //filteredData = (ArrayList<String>) results.values;
                    movieItems = (ArrayList<Movie>) results.values;
                    notifyDataSetChanged();
                }

            }


}

如你所见,我真的花了很多时间将整个代码放在一起,但在这个交界处,我的头脑旋转,因为我无法弄清楚为什么

  • 关于方向更改,在我将可过滤引入我的 CustomListAdapter 之后,用于重新填充的listView数据会突然停止填充课程以及

  • 当我清除搜索EditView 时,ListView中的内容不会返回

  • 当我点击重新加载按钮时,列表中的内容不会重新加载,就像设备方向更改时一样。

我真的很感激能帮助我,因为我现在非常困难。 Thanks in Advance

- 已编辑的CustomListAdapter 我所做的更改

               @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    //filteredData = (ArrayList<String>) results.values;
                    //movieItems = (ArrayList<Movie>) results.values;
                    movieItems.clear();
                    movieItems.addAll((ArrayList<Movie>) results.values);
                    notifyDataSetChanged();
                }

            }

也编辑了这个。添加了this.originalMovieList = new ArrayList<Movie>(movieItems);

public CustomListAdapter(Activity activity, List<Movie> movieItems) {
    this.activity = activity;
    this.movieItems = movieItems;
   // this.originalMovieList = movieItems;
    this.originalMovieList = new ArrayList<Movie>(movieItems);
    bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}

将此方法添加到CustomListAdapter

//Add Below Method
public void reloadData(){
    this.originalMovieList = new ArrayList<Movie>(movieItems);
    notifyDataSetChanged();
}

还使用此

替换了MainActivity Class中的notifyDataSetChanged()
                     `// notifying list adapter about data changes
                    // so that it renders the list view with updated data
                     //adapter.notifyDataSetChanged();
                      adapter.reloadData();`

-Reload Button现在工作正常,方向更改可以很好地重新加载页面,但搜索不会填充ListView。 因此,搜索尚未开始

2 个答案:

答案 0 :(得分:0)

以下是您的问题的答案:
1。 ListView未重新加载?在函数中查看代码后:

@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
         //filteredData = (ArrayList<String>) results.values;
         movieItems = (ArrayList<Movie>) results.values;
         notifyDataSetChanged();
}

上述功能使您的适配器无法重新加载。为什么?因为这一行:movieItems = (ArrayList<Movie>) results.values;。您将适配器中的movieItems引用到另一个List,因此movieList.add(movie);中的MainActivity d不再更新adapter中的任何内容。如何克服它?改变如下:

movieItems.clear();
movieItems.addAll((ArrayList<Movie>) results.values);
notifyDataSetChanged();

但是,您的Search功能仍无效。为什么?因为您在performFiltering中尝试搜索movieItems而不是您的备份数据。 - &GT;您应该搜索备份数据:originalMovieList,然后通过添加movieItems进行发布。

//change final List<Movie> list = movieItems;
//to belowed line in peformFiltering
final List<String> list = originalData;
  1. 为什么你的适配器没有恢复?因为你控制它,但你不会还原它。您应该在peformFiltering函数中恢复它:

    protected FilterResults performFiltering(CharSequence constraint) {
          String filterString = constraint.toString().toLowerCase();
          if(TextUtils.isEmpty(filterString)){
                // do restore backup data here
          }else{
               // do filter here.
          }
    }
    

答案 1 :(得分:0)

这就是我能够解决搜索代码痛苦的方法。

在我的 MainActivity

public class MainActivity extends Activity {

 private List<Movie> currentMovieList = new ArrayList<Movie>();
 private List<Movie> originalMovieList = new ArrayList<Movie>();
 private CustomListAdapter adapter;
 private ListView mList;
 // Search EditText
 EditText inputSearch;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_main);

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

adapter = new CustomListAdapter(this, currentMovieList);
    mList.setAdapter(adapter);


    inputSearch.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text

            String filterString = cs.toString().toLowerCase();
            Log.e("TAG", "filterString:" + filterString);
            currentMovieList.clear();
            if (TextUtils.isEmpty(filterString)) {
                currentMovieList.addAll(originalMovieList);
            }

            String filterableString;
            for (Movie movie : originalMovieList) {
                if (movie.getTitle().toLowerCase().contains(filterString)) {
                    currentMovieList.add(movie);
                }
                else if (String.valueOf(movie.getYear()).toLowerCase().contains(filterString))
                {
                    currentMovieList.add(movie);
                }
                else if (String.valueOf(movie.getRating()).toLowerCase().contains(filterString))
                {
                    currentMovieList.add(movie);
                }
                else if (movie.getGenre().toString().toLowerCase().contains(filterString))
                {
                    currentMovieList.add(movie);
                }
            }
            adapter.notifyDataSetChanged();
            //FLAGS Cannot resolve method 'getFilter()' here
        }

        @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
        }
    });


}
}

并将其添加到 CustomListAdapter

public class CustomListAdapter extends BaseAdapter implements Filterable {

    private Activity activity;
 private LayoutInflater inflater;

 private List<String>originalData = null;
 // private List<String>filteredData = null;

 private List<Movie> movieItems;
 private List<Movie> originalMovieList;
 private String[] bgColors;
 ImageLoader imageLoader = MyApplication.getInstance().getImageLoader();
 private ItemFilter mFilter = new ItemFilter();


 public CustomListAdapter(Activity activity, List<Movie> movieItems) {
       this.activity = activity;
        this.movieItems = movieItems;
      // this.originalMovieList = movieItems;
      this.originalMovieList = new ArrayList<Movie>(movieItems);
      bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
        }

    //Add Below Method
    public void reloadData(){
       this.originalMovieList = new ArrayList<Movie>(movieItems);
     notifyDataSetChanged();
        }
     @Override
 public int getCount() {
     return movieItems.size();
        }

 @Override
    public Object getItem(int location) {
        return movieItems.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_image, null);

    if (imageLoader == null)
        imageLoader = MyApplication.getInstance().getImageLoader();
    NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);

    TextView serial = (TextView) convertView.findViewById(R.id.serial);
    TextView title = (TextView) convertView.findViewById(R.id.title);
    TextView rating = (TextView) convertView.findViewById(R.id.rating);
    TextView genre = (TextView) convertView.findViewById(R.id.genre);
    TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

    // getting movie data for the row
    Movie m = movieItems.get(position);

    // thumbnail image
    thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

    // title
    title.setText(m.getTitle());

    // rating
    rating.setText("Rating: " + String.valueOf(m.getRating()));

     // genre
     String genreStr = "";
        for (String str : m.getGenre()) {
          genreStr += str + ", ";
     }
     genreStr = genreStr.length() > 0 ? genreStr.substring(0,
            genreStr.length() - 2) : genreStr;
        genre.setText(genreStr);

        // release year
     year.setText(String.valueOf(m.getYear()));

     String color = bgColors[position % bgColors.length];
        serial.setBackgroundColor(Color.parseColor(color));




      return convertView;
 }


            public Filter getFilter() {
                return mFilter;
            }

            private class ItemFilter extends Filter {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {

                    String filterString = constraint.toString().toLowerCase();

                    FilterResults results = new FilterResults();


                    //results.values = nlist;
                    //results.count = nlist.size();
                    results.values = originalMovieList;
                    results.count = originalMovieList.size();

                    return results;
                }

                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    //filteredData = (ArrayList<String>) results.values;
                    //movieItems = (ArrayList<Movie>) results.values;
                    movieItems.clear();
                    movieItems.addAll((ArrayList<Movie>) results.values);
                    notifyDataSetChanged();
                }

            }



}

现在这是一个WRAP。 感谢@DhavalPatel 那家伙是Android大师。 He made all this happen. -Happy Coding