【问题标题】:How to change the order of the messages from JSON?如何更改来自 JSON 的消息的顺序?
【发布时间】:2015-07-10 10:14:31
【问题描述】:

我有来自服务器的消息的 JSON 响应:

response: {
count: 74246,
items: [{
  id: 343194,
  body: 'Message 3',
  user_id: 123,
  from_id: 123,
  date: 1436513626,
  read_state: 1,
  out: 0
}, {
  id: 343190,
  body: 'Message 2',
  user_id: 123,
  from_id: 321,
  date: 1436513502,
  read_state: 1,
  out: 1
}, {
  id: 343187,
  body: 'Message 1',
  user_id: 123,
  from_id: 123,
  date: 1436513198,
  read_state: 1,
  out: 0
}]
}

我把它放到列表视图中,我有这样的顺序:

  • 消息 3
  • 消息 2
  • 消息 1

但我想得到下一个订单:

  • 消息 1
  • 消息 2
  • 消息 3

所以这意味着最新的消息应该从下到上。也许我应该从底部构建列表视图?但是怎么做? 我应该怎么做才能实现这一目标? 对不起我的英语:)

【问题讨论】:

  • a) 你是如何创建你的列表视图的? b) 谁在生成 JSON?
  • 您需要对数据进行排序...
  • 您要根据日期或消息对其进行排序吗?

标签: android json parsing listview messages


【解决方案1】:

ArrayList上设置相反的顺序

ArrayList<Your_Model> mList = new ArrayList<Your_Model>();

JSON 中设置 mList 中的数据:

当你想在reverse order上获得List时,输入下面的代码。

Collections.reverse(mList);

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    一旦你在 JsonArray 中得到你的“items”数组,那么你应该得到类似的数据,

         for(int i=array.length()-1; i<=0; i--){
             // get your messages from "items" array.  
          }
    

    【讨论】:

      【解决方案3】:

      我假设您希望根据响应中的 date 字段对消息列表进行排序。

      从此 JSON 响应中创建 MyClassArrayList,例如 mylist,并创建如下比较器类:

      public class MyComparator implements Comparator<MyClass> {
          @Override
          public int compare(MyClass lhs, MyClass rhs) {
              if (ldate.getDate() > rdate.getDate()) {
                  return 1;
              } else if (ldate.getDate() < rdate.getDate()) {
                  return -1;
              }
              return 0;
          }
      }
      

      MyClass 是上述 JSON 响应的模型类。

      使用这个Comparator 类和你ArrayList 如下:

      Collections.sort(mylist,new MyComparator());
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2021-12-10
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        • 2010-11-30
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        相关资源
        最近更新 更多