为啥我的数组未显示为已过滤?
Posted
技术标签:
【中文标题】为啥我的数组未显示为已过滤?【英文标题】:Why is my array not displaying as filtered?为什么我的数组未显示为已过滤? 【发布时间】:2021-11-08 11:10:30 【问题描述】:我正在尝试使用此示例按价格从最低到最高排序此 JSON 对象 How to sort JSON object in java?。但是当我尝试显示我的列表时,它似乎没有排序。我不确定我做错了什么,有人能指出我正确的方向。我已经阅读了几篇文章,他们都说要使用集合对 JSON 对象进行排序,我尝试在下面实现它,但它不起作用任何建议都值得赞赏。
json :-
[
"symbol" : "SAN",
"companyName" : "Banco Santander, S.A.",
"marketCap" : 62296657920,
"sector" : "Financial Services",
"industry" : "Banks—Diversified",
"beta" : 1.74298500000000000653699316899292171001434326171875,
"price" : 3.5800000000000000710542735760100185871124267578125,
"lastAnnualDividend" : 0.24899999999999999911182158029987476766109466552734375,
"volume" : 4284228,
"exchange" : "New York Stock Exchange",
"exchangeShortName" : "NYSE",
"country" : "ES",
"isEtf" : false,
"isActivelyTrading" : true
,
"symbol" : "ABEV",
"companyName" : "Ambev S.A.",
"marketCap" : 48729493504,
"sector" : "Consumer Defensive",
"industry" : "Beverages—Brewers",
"beta" : 0.93046200000000001129052407122799195349216461181640625,
"price" : 3.0099999999999997868371792719699442386627197265625,
"lastAnnualDividend" : 0.0970000000000000028865798640254070051014423370361328125,
"volume" : 24947634,
"exchange" : "New York Stock Exchange",
"exchangeShortName" : "NYSE",
"country" : "BR",
"isEtf" : false,
"isActivelyTrading" : true
,
"symbol" : "LYG",
"companyName" : "Lloyds Banking Group plc",
"marketCap" : 41814462464,
"sector" : "Financial Services",
"industry" : "Banks—Regional",
"beta" : 1.483138999999999985135445967898704111576080322265625,
"price" : 2.310000000000000053290705182007513940334320068359375,
"lastAnnualDividend" : 0.07022699999999999775912584709658403880894184112548828125,
"volume" : 5825636,
"exchange" : "New York Stock Exchange",
"exchangeShortName" : "NYSE",
"country" : "GB",
"isEtf" : false,
"isActivelyTrading" : true
,
代码:-
public void downloadChangePercentage(String api)
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
api,
null,
new Response.Listener<JSONArray>()
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onResponse(JSONArray response)
// ArrayList<JSONObject> array = new ArrayList<JSONObject>();
ArrayList<JSONObject> jsonStockList = new ArrayList<>();
for (int i = 0; i < response.length(); i++)
// LOOP over JSON objects and added it to mode/ Stocklist arraylist..
try
stockInfo = response.getJSONObject(i);
stockDetail = new StockDetails(stockInfo.getString("changesPercentage"), stockInfo.getString("symbol"), stockInfo.getString("price"), stockInfo.getString("name"));
stockListArrayList.add(stockDetail);
jsonStockList.add(response.getJSONObject(i));
searchStockAdapter.notifyDataSetChanged();
ArrayList<JSONObject> sortedStockList = sortJSONObject(jsonStockList);
for (int j = 0; j < sortedStockList.size(); j++)
logText("sortedData", String.valueOf(sortedStockList.get(j)));
catch (JSONException e)
e.printStackTrace();
,
new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
Log.i("error", error.toString());
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
ArrayList<JSONObject> sortJSONObject(ArrayList<JSONObject> jsonStockList)
Collections.sort(jsonStockList, new Comparator<JSONObject>()
@Override
public int compare(JSONObject o1, JSONObject o2)
try
return Double.compare(o1.getDouble("price"), o2.getDouble("price"));
catch (JSONException e)
e.printStackTrace();
return 0;
);
return jsonStockList;
【问题讨论】:
您将数字作为字符串进行比较。我建议你将价格转换为double
,然后进行比较。
当询问特定主题的信息(在本例中为 JSON + 排序)时,您应该将标签 JSON 和排序放在您的问题上。这一点很重要,因为并非每个 Java/android 程序员都有处理 JSON 和使用正确标签的经验,正确的人会查看您的问题。
@Abra 感谢您的建议,但它不起作用,我会记住这一点,感谢您的提示。
与您的问题没有直接关系,但仍然是一个错误:在您的 get-sorted-data-for-loop 中,您正在检查整个数组的可空性,这是没有意义的(因为您' 已经对其进行了迭代,它不能为空)。大多数情况下你想使用array[j]
。
【参考方案1】:
引用您的代码并添加排序逻辑
void callApis()
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
api,
null,
new Response.Listener<JSONArray>()
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onResponse(JSONArray response)
/******** Do exactly like below **********/
ArrayList<JSONObject> jsonStockList = new ArrayList<>();
for (int i = 0; i<response.length();i++)
try
jsonStockList.add(response.getJSONObject(i));
catch (JSONException e)
e.printStackTrace();
/** pass this stockListArrayList(sorted Data) in view/adapter */
for (JSONObject stockInfo : sortJSONObject(jsonInfosList))
// assigning sorted data in data model
StockDetails stockDetail = new StockDetails();
stockDetail.setCompanyName(stockInfo.getString("companyName"));
stockDetail.setIndustry(stockInfo.getString("industry"));
stockDetail.setPrice(stockInfo.getDouble("price"));
stockDetail.setMarketCap(stockInfo.getLong("marketCap"));
stockDetail.setSector(stockInfo.getString("sector"));
stockDetail.setSymbol(stockInfo.getString("symbol"));
// below (stockListArrayList) is the list which you need to pass in your adapter and notifyDataSetChanged()
stockListArrayList.add(stockDetail);// stockListArrayList is already decleare in your code
/*********** end **********/
,
new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
// Do something when error occurred
Log.i("error", error.toString());
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
根据价格对对象进行排序的功能
ArrayList<JSONObject> sortJSONObject(ArrayList<JSONObject> jsonStockList)
Collections.sort(jsonStockList, new Comparator<JSONObject>()
@Override
public int compare(JSONObject o1, JSONObject o2)
try
return Double.compare(o1.getDouble("price"), o2.getDouble("price"));
catch (JSONException e)
e.printStackTrace();
return 0;
);
return jsonStockList;
【讨论】:
@usertip oia 使用此答案,您将获得预期的数据。 我试过这个,我会把代码放在哪里来显示排序的数据?请看我上面的代码,我用 urs 更新了它。然而,当我尝试显示它时,我的数据没有被排序。 @usertipoia 我已经添加了一个像你这样的 bean 类,以便于理解。检查代码中的 cmets 以了解您需要在适配器中传递哪个列表以在 recyclerView 中显示已排序的数据。检查我上面的更新代码 @usertipoia 你有机会查看我更新的答案吗?【参考方案2】:我认为您的问题是因为 Override 并返回 0。 在这里试试这个它在我的机器上工作。
Collections.sort(array, new Comparator<JSONObject>()
public int compare(JSONObject lhs, JSONObject rhs)
try
return (lhs.getString("price").compareTo(rhs.getString("price")));
catch (JSONException e)
e.printStackTrace();
return 1;
);
【讨论】:
它对我不起作用,我的数据仍然未排序。以上是关于为啥我的数组未显示为已过滤?的主要内容,如果未能解决你的问题,请参考以下文章