Home > database >  Cannot display right result of sum data in line graph
Cannot display right result of sum data in line graph

Time:03-31

I try for fetch data from JSON which JSON structure like this

{"count" : 5,"result" : [
{"id": 1,
        "date_invoice": "2022-03-25",
        "state": "paid",
        "amount_untaxed": 25000
    },
{"id": 2,
        "date_invoice": "2022-03-26",
        "state": "paid",
        "amount_untaxed": 161500
    },
{"id": 3,
        "date_invoice": "2022-03-27",
        "state": "paid",
        "amount_untaxed": 25000
    },
{"id": 4,
        "date_invoice": "2022-03-30",
        "state": "paid",
        "amount_untaxed": 165000
    },
{"id": 5,
        "date_invoice": "2022-03-30",
        "state": "paid",
        "amount_untaxed": 70000
    }
]}

i already can fetch json data and display it to line chart, i use mpchartandroid library for display my graph. My problem i can't display result of sum data amount_untaxed when some data have same date. Here my code for sum

            detail = new HashMap<>();
            detail = new Gson().fromJson(_response, new TypeToken<HashMap<String, Object>>(){}.getType());
            str= (new Gson()).toJson(detail.get("result"), new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
            listmap_detail = new Gson().fromJson(str, new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
            listmap_Item = listmap_detail;
            price_subtotal = Float.valueOf(0);
            for (int i=0;i<listmap_detail.toArray().length;i  ){
                dateString = listmap_detail.get(i).get("date_invoice").toString().replace("-","");
                format1 = new SimpleDateFormat("yyyyMMdd");
                format1.setTimeZone(TimeZone.getTimeZone("GMT 7"));
                format2 = new SimpleDateFormat("dd");
                SimpleDateFormat format3 = new SimpleDateFormat("MMMM yyyy");
                SimpleDateFormat format4 = new SimpleDateFormat("dd-MM");
                try {
                    today = new Date();
                    current_date = format3.format(today);
                    Date date = format1.parse(dateString);
                    dateFinal = format2.format(date);
                    String dateSementara = format2.format(today);

                    if (dateSementara.equals(dateFinal)){
                        price_subtotal  = Float.valueOf(listmap_detail.get(i).get("amount_untaxed").toString());
                    }
                    line_entries.add(new Entry(Float.parseFloat(dateFinal),price_subtotal));
                }
                catch (Exception e){

                }
            }

My chart My chart display

Is there any way for solving this ?

CodePudding user response:

I am not sure why you are plotting this by day of the month (this will break if the data set spans multiple months) but the code below works for the case you have presented.

It first collects the data you want to plot into a HashMap by date, summing values if there are multiple entries on a given date, then translates that map to x-y Entries for the chart.

// no need to call Gson multiple times - once you have 
// parsed it you can just get the entries from the map
HashMap<String,Object> detail = new Gson().fromJson(jsonStr, new TypeToken<HashMap<String, Object>>(){}.getType());
List<Map<String,Object>> listmap_detail = (List<Map<String, Object>>) detail.get("result");

// Collect values per day into a map first to handle 
// summing duplicate values
Map<String,Float> daily_sum = new HashMap<>();
for(Map<String,Object> entry : listmap_detail) {
    String date = (String) entry.get("date_invoice");
    Float amt = ((Double) entry.get("amount_untaxed")).floatValue();
    if( !daily_sum.containsKey(date) ) {
        daily_sum.put(date, amt);
    }
    else {
        daily_sum.put(date, amt   daily_sum.get(date));
    }
}

// Print statements are your friend when it comes to 
// debugging code like this
System.out.println("DEBUG: daily sum = "   daily_sum);

// Sort the dates so the data is in chronological order
List<String> keys = new ArrayList<>(daily_sum.keySet());
Collections.sort(keys);

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dayOfMonthFormat = new SimpleDateFormat("dd");

// WARNING: MPAndroidChart requires entries to be ordered by x value - if your 
// data set spans multiple months this will cause a problem 
// below since the data will not be in order by day of month.
// Adjust for your use case as-needed.
for(String isoDate : keys) {
    try {
        Date date = isoFormat.parse(isoDate);
        float dayOfMonth = Float.parseFloat(dayOfMonthFormat.format(date));
        Float dailyAmt = daily_sum.get(isoDate);
        System.out.println("DEBUG: plotting "   dayOfMonth   ","   dailyAmt);
        line_entries.add(new Entry(dayOfMonth,dailyAmt));
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
        
  • Related