当前位置: 首页 > 知识库问答 >
问题:

如何根据它所基于的对象的变量对自定义Array适配器的内容进行排序?

雷方伟
2023-03-14

我正在尝试根据在Articles_Map对象上找到的PublishedAT变量对News适配器数组中的每个条目进行排序。每次使用addAll方法添加新条目后,我都需要根据PublishedAT对其进行排序。这是我的代码:

列表新闻活动:

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!");
            }
        });
    }
}

新闻适配器:

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

EDIT-通过PublishedAt比较器的代码实现

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个答案

井洲
2023-03-14
匿名用户

<罢工> 使用前对其进行排序 Collections.sort(列表,比较器) 罢工

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

<罢工>

[已编辑]

哈!但是Array适配器已经有了一个排序(比较器)方法!!!

要么调用它:

    < li >何时(如果?)你知道你有所有需要排序的元素(例如处理一个响应的结尾);或者 < li >每次添加后-通过覆盖< code>add和< code>addAll方法(可能会占用更多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 

 类似资料:
  • 问题内容: 如何根据自定义属性排序ArrayList中的对象? 问题答案: 从实现,它就有一个像方法一样的方法。 因此,你的自定义设置应如下所示: 该方法必须返回一个,因此无论如何你都无法直接返回一个你计划中的。 你的排序代码几乎就像你写的那样: 如果你不需要重用比较器,则编写所有这些内容的一种更短的方法是将其编写为内联匿名类: 自从Java-8 现在,你可以通过使用lambda表达式来以较短的形

  • 按学生成绩的先后顺序,按“不及格”、“及格”、“不可用”(不按字母顺序)排序,成绩不及格的学生应排在名单的首位。然后是“通过”,然后是“不可用” 如果多个学生的结果相同,则按卷号升序排序。 最终结果应该如下所示。

  • 假设我有一个自定义对象的ArrayList,例如 如何按路径、格式、大小或日期添加对其进行排序? 谢了!

  • 问题内容: 我正在为我的通讯录应用程序实现排序功能。 我想排序一个。是一个包含四个字段的类:姓名,家庭电话,手机号码和地址。我想继续。 如何编写自定义排序功能来做到这一点? 问题答案: 这是有关订购对象的教程: Java教程-集合-对象排序 尽管我会举一些例子,但我还是建议你阅读它。 有多种排序方式。如果要定义自然的(默认)排序,则需要让实现。假设你想默认在上进行排序name,然后执行(为简单起见

  • 问题内容: 我正在创建一个JSON对象,其中添加了一个键和一个数组值。键和值的值都来自TreeSet,该树具有排序形式的数据。但是,当我在json对象中插入数据时,它会随机存储,没有任何顺序。当前是我的json对象: 我的代码是: 有什么方法可以将数据存储到while循环本身中的json对象中? 问题答案: 它与Google Gson API一起使用。试试看。

  • 问题内容: 我的探针示例: 我们有Apple的对象类型。苹果有一些成员变量: 种子对象如下所示。 现在,当我得到一个苹果物体时,一个苹果可能有多个种子,或者可能有一个种子,或者可能没有种子! 带有一个种子的示例JSON苹果: 带有两个种子的示例JSON苹果: 现在的问题是,第一个示例是用于种子的JSONObject,第二个示例是用于种子的JSONArray。现在,我知道它的JSON不一致,并且最简