安卓:排序列表视图数据 [英] Android: Sort List View data

查看:188
本文介绍了安卓:排序列表视图数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我从一台服务器拉下一些JSON数据。一个在该数据字​​段是一个距离值。我需要按距离排序从低到ListView中最高的数据。我不知道如何去吗?

I have some JSON data which I am pulling down from a server. One of the fields in this data is a distance value. I need to have the data sorted by distance from lowest to highest in the ListView. I am not sure how to go about it?

任何帮助AP preciated。

Any help appreciated.

推荐答案

我并不确切地知道你想要做什么,但有你有JSON响应后,需要几个步骤。

I don't know exactly what you want to do but there are few steps that are needed after you have the json response.


  1. 请JSON数据对象的列表

  2. 排序列表

  3. 设置列表视图与排序列表适配器

有关未来的问题,请您的问题分开到不同的小,但具体化的问题。

For future questions please separate your question to different smaller but concretized questions.

1。使JSON数据对象的列表

对象数据模型

class YourDataModel {
       int distance;
       .....
       public int getDistance(){
              return this.distance;
       }

       public void setDistance(int distance){
              this.distance = distance;
       }
}

然后让我们说getJsonResponse()与该列表中的所有数据返回的JSON。让我们作出这样的JSON名单列出:D

Then let's say getJsonResponse() returns your json with all the data for the list. And let's make that json list to List :D

String json = getJsonResponse(); // Change that line with your code
Gson gson = new Gson();
Type listType = new TypeToken<List<YourDataModel>>(){}.getType();
ArrayList<YourDataModel> data = (ArrayList<YourDataModel>) gson.fromJson(jsonOutput, listType);

2。排序列表

现在让我们做一些魔法:D数据是我的数组里面的物品

Now let's do some magic :D data is my array with the items inside.

Collections.sort(data, new Comparator<YourDataModel>() {
    @Override
    public int compare(YourDataModel data1, YourDataModel data2) {
          if( data1.getDistance() < data2.getDistance() )
             return 1;
          else
             return 0;
    }
});

3。设置列表适配器排序列表到ListView

我不知道该怎么形容这里:D

I don't know what to describe here :D

ListView lvData = (ListView) findViewById(R.id.listview1);
MyCustomAdapter adapter = new MyCustomAdapter(this, R.layout.listview_item_row, data);
lvData.setAdapter(adapter);

我不知道这是否是你想要的,但是这是怎么需要做。
如果您想直接将数据排序从列表视图阅读:排序列表视图与阵列适配器

这篇关于安卓:排序列表视图数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆