[英]Sort Ascending and Descending Integer
I have a POJO class which contents for sorting Integer where integer obtained from JSON.我有一个 POJO 类,它的内容用于对从 JSON 获得的整数进行排序。 When i implement it, Integer cannot sort ascending or descending.当我实现它时,Integer 不能按升序或降序排序。
Example : JSON has many data, one data has one integer.示例:JSON 有很多数据,一个数据有一个整数。 when i call all data and click for sort ascending, then integer sort ascending.当我调用所有数据并单击升序排序,然后单击整数升序排序。 But i use code like this, cannot sort integer.但是我使用这样的代码,无法对整数进行排序。
Code :代码 :
public class ModelNameProductUrutkan {
@SerializedName("price_regular")
private int price;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
// Filter Descending Integer
public static final Comparator<ModelNameProductUrutkan> sortByHighPrice = new Comparator<ModelNameProductUrutkan>() {
@Override
public int compare(ModelNameProductUrutkan o1, ModelNameProductUrutkan o2) {
return o2.getPrice() - o1.getPrice();
}
};
// Filter Ascending Integer
public static final Comparator<ModelNameProductUrutkan> sortByLowPrice = new Comparator<ModelNameProductUrutkan>() {
@Override
public int compare(ModelNameProductUrutkan o1, ModelNameProductUrutkan o2) {
return o1.getPrice() - o2.getPrice();
}
};
SortingInteger.java : SortingInteger.java :
private List<ModelNameProductUrutkan> modelNameProductUrutkans;
...............
filterHargaTerendah.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Call<JsonObject> getProduct = baseApiService.getDetailProductCategory(category_id, perPage, source_id);
getProduct.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (!response.isSuccessful()) {
Log.e(TAG, "Response Error : " + response.code());
} else {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONObject object = jsonObject.getJSONObject("data");
JSONArray jsonArray = object.getJSONArray("items");
modelNameProductUrutkans = new ArrayList<>();
for(int a = 0; a <= jsonArray.length(); a++) {
JSONObject objectData = jsonArray.getJSONObject(a);
ModelNameProductUrutkan modelNameProductUrutkan = new ModelNameProductUrutkan();
modelNameProductUrutkan.setPrice(objectData.getInt("price_regular"));
modelNameProductUrutkans.add(modelNameProductUrutkan);
Toast.makeText(getContext(), "Sort By Low Price : " + modelNameProductUrutkan.getPrice(), Toast.LENGTH_SHORT).show();
}
Collections.sort(modelNameProductUrutkans, ModelNameProductUrutkan.sortByLowPrice);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
});
更改为以下方式,它应该可以工作:
return Integer.compare(o1.getPrice(), o2.getPrice());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.