0

I am attempting to sort this JSON object by price lowest to highest using this example How to sort JSON object in java?. But when i try to display my list it appear's unsorted. I am not sure what I am doing wrong can someone point me in the right direction. I read several post already and they all say to use collection to sort a JSON object, i attempted implementing it below, but it does not work any suggestion is appreciated.

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
},

code :-

 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;
}
  • 3
    You are comparing numbers as strings. I suggest that you convert the price to a `double` and then compare. – Abra Sep 13 '21 at 06:08
  • 1
    When asking for information that specific to a topic (in this case JSON + sorting) you should put the tags JSON and sorting on your question. This is important since not every Java/Android programmer will have experience dealing with JSON and with the right tags, the right people will look on your question. – RAVN Mateus Sep 13 '21 at 06:31
  • @Abra thanks for the suggestion but it does not work, i will keep that in mind thanks for the tip. – usertip oia Sep 13 '21 at 06:50
  • Not directly related to your question, but still a bug: In your get-sorted-data-for-loop, you're checking for nullability of the whole array, which makes no sense (since you're iterating over that already, it can't be null). Mostpropably you want to use `array[j]`. – m.reiter Sep 13 '21 at 08:11

2 Answers2

1

Referring your code and adding sorting logic

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);

}

function to sort object based on price

 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;
}
Akash Kumar
  • 121
  • 1
  • 7
  • @usertip oia Use this answer you will get your expected data. – Akash Kumar Sep 13 '21 at 07:46
  • I attempted this where would i put the code to display the sorted data? Please, see my above code i updated it with urs. Yet my data is not being sorted when i try displaying it. – usertip oia Sep 14 '21 at 07:35
  • @usertipoia I have added a bean class like yours to make it easy to understand. Check comments inside the code to know which list you need to pass in your adapter to show sorted data in recyclerView. Check my update code above – Akash Kumar Sep 16 '21 at 06:58
  • @usertipoia did you get a chance to check my updated Answer? – Akash Kumar Nov 02 '21 at 06:28
0

i think your problem was because of Override and returning 0. here try this it's work on my machine.

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;
        }
    }
});