如何通过它所基于的对象变量对自定义ArrayAdapter的内容进行排序?

时间:2016-10-19 23:40:24

标签: java android android-arrayadapter

我正在尝试按NewsAdapter对象上的publishedAt变量对Articles_Map数组中的每个条目进行排序。每次使用publishedAt方法添加新条目后,我都需要按addAll排序。这是我的代码:

ListNewsActivity

public class ListNewsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /* ... */

        // parameters for Sources endpoint
        String category = "sport";
        String language = "en";
        String country = "us";

        // Sources endpoint
        Sources_Interface client_sources = NewsAPI_Adapter.createService(Sources_Interface.class);
        Call<Sources_Map> call_sources = client_sources.getData(category, language, country);

        call_sources.enqueue(new Callback<Sources_Map>() {
            @Override
            public void onResponse(Call<Sources_Map> call_sources, Response<Sources_Map> response) {
                if (response.body() != null) {
                    final NewsAdapter nAdapter = new NewsAdapter(ListNewsActivity.this,
                            R.layout.article_layout);

                    for (final Sources_Content source : response.body().sources) {
                        if (source.sortBysAvailable.contains("latest")) {
                            // Articles endpoint
                            NewsAPI_Interface client = NewsAPI_Adapter.createService(NewsAPI_Interface.class);
                            Call<NewsAPI_Map> call = client.getData(source.id, "17f8ddef543c4c81a9df2beb60c2a478");

                            call.enqueue(new Callback<NewsAPI_Map>() {
                                @Override
                                public void onResponse(Call<NewsAPI_Map> call, Response<NewsAPI_Map> response) {
                                    if (response.body() != null) {
                                        ExpandableHeightGridView gv_content = (ExpandableHeightGridView) findViewById(R.id.gv_content);
                                        nAdapter.addAll(response.body().articles);
                                        gv_content.setAdapter(nAdapter);
                                        gv_content.setExpanded(true);
                                    }
                                }

                                @Override
                                public void onFailure(Call<NewsAPI_Map> call, Throwable t) {
                                    System.out.println("An error ocurred!\n" +
                                            "URL: " + call.request().url() + "\n" +
                                            "Cause: " + t.getCause().toString());
                                }
                            });
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<Sources_Map> call_sources, Throwable t) {
                System.out.println("An error ocurred!");
            }
        });
    }
}

NewsAdapter

public class NewsAdapter extends ArrayAdapter<Articles_Map> {
    Context mContext;

    public NewsAdapter(Context c, int resource) {
        super(c, resource);
        this.mContext = c;
    }

    public NewsAdapter(Context c, int resource, List<Articles_Map> articles) {
        super(c, resource, articles);
        this.mContext = c;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // get the property we are displaying
        Articles_Map article = getItem(position);

        // get the inflater and inflate the XML layout for each item
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.article_layout, null);

        ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView description = (TextView) view.findViewById(R.id.description);

        Picasso.with(mContext).load(article.urlToImage).into(thumbnail);
        title.setText(article.title);
        description.setText(article.description);

        return view;
    }
}

Articles_Map

public class Articles_Map {
    String title;
    String description;
    String url;
    String urlToImage;
    Date publishedAt;

    public Articles_Map(String title, String description, String url, String urlToImage, Date publishedAt) {
        this.title = title;
        this.description = description;
        this.url = url;
        this.urlToImage = urlToImage;
        this.publishedAt = publishedAt;
    }
}

编辑 - 已实施byPublishedAtComparator的代码:

private static final Comparator<Articles_Map> byPublishedAtComparator =
            new Comparator<Articles_Map>() {
                @Override
                public int compare(Articles_Map o1, Articles_Map o2) {
                    if (o1.publishedAt == null || o2.publishedAt == null) {
                        return 0;
                    }

                    return o1.publishedAt.compareTo(o2.publishedAt);
                }
            };

1 个答案:

答案 0 :(得分:4)

使用Collections.sort(List, Comparator)

进行排序之前对其进行排序
Collections.sort(
  myArticles_MapList, // your specific list to be sorted
  new Comparator<Articles_Map>() {
    public int compare(Articles_Map o1, Articles_Map o2) {
      // Improve this to handle null publishedAt (make it early Paleozoic?)
      return o1.getPublishedAt().compareTo(o2.getPublishedAt());
    }
  }
)

<击>

[被修改]

哈!但是ArrayAdapter已经有sort(Comparator)方法!!!

调用它:

  • 当(如果?)你知道你有所有需要排序的元素时(例如处理响应的结束);
  • 每次添加后
  • - 通过覆盖addaddAll方法(可能更耗费CPU)。

第二种方法可以这样:

public class NewsAdapter extends ArrayAdapter<Articles_Map> {
  private static final Comparator<Articles_Map> 
    byPublishedAtComparetor = new Comparator<Articles_Map>() {
        public int compare(Articles_Map o1, Articles_Map o2) {
          // Improve this to handle null publishedAt
          return o1.getPublishedAt().compareTo(o2.getPublishedAt());
        }
      }
    ;

  Context mContext;

  // snip...


  public NewsAdapter(Context c, int resource, List<Articles_Map> articles) {
    super(c, resource, articles);
    this.sort(byPublishedAtComparetor);
    this.mContext = c;
  }


  protected void doAdd(Articles_Map another) {
    suoer.add(another);
  }

  // Override to maintain the order
  void add(Articles_Map another) {
    this.doAdd(another);
    this.sort(byPublishedAtComparator);
  }
  // Overrides to maintain order and to avoid calling into
  // individual add(...) method, which will cause unnecessary
  // sorting after each element
  @Override
  public void addAll(Articles_Map... others) {
    for(Articles_Map a : others) {
      this.doAdd(a);
    }
    this.sort(byPublishedAtComparator);
  }

  @Override
  public void addAll(Collection<Articles_Map> others) {
    for(Articles_Map a : others) {
      this.doAdd(a);
    }
    this.sort(byPublishedAtComparator);
  }

  @Override
  public void insert(int i, Articles_Map article) {
    // decline to insert it at any indicated position
    // as it may break the order. Instead, treat it as any addition
    // which will automatically result in a reordering
    this.add(article);
  }

  // No override for remove - removing elements don't break
  // the order