在Android中对列表进行排序查看数据 [英] Sort List View data in Android
问题描述
我有一些要从服务器中提取的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?
推荐答案
我不确定您到底想做什么,但是在获得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.
- 将json数据制作为对象列表
- 对列表进行排序
- 使用已排序的列表设置listview的适配器
对于以后的问题,请将您的问题分为较小的但具体化的问题.
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列表添加到List: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.将具有排序列表的列表适配器设置为列表视图
我不知道在这里要描述什么: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);
我不知道这是否是您想要的,但这是需要做的. 如果您想直接从列表视图中排序数据,请阅读以下内容:使用数组适配器对列表视图进行排序
I don't know if that's what you want but this is how it need to be done. If you want to sort the data directly from the listview read this: Sort listview with array adapter
这篇关于在Android中对列表进行排序查看数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!