Search code examples
javaandroidcalendargoogle-fit

Take away a single day using Calendar in Java?


I have an application that plugs into the Google Fit Api and returns the steps for the last 7 days, the method is below. As the screen shot shows though I wish to add the day to the step count.

I have tried many options to take away one day at a time for the 7 loop but had no luck, it just says the same day. Any help would be great thank you.

private void dumpDataSet(DataSet dataSet) {
    Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
    DateFormat dateFormat = DateFormat.getTimeInstance();

    int i = 0;

    for (DataPoint dp : dataSet.getDataPoints()) {

        for(Field field : dp.getDataType().getFields()) { //loop 7 times

            int test = dp.getValue(field).asInt();

            String weekSteps= String.valueOf(test); //get weekday steps one at a time

            SimpleDateFormat sdf = new SimpleDateFormat("EEEE");



            Calendar cal = Calendar.getInstance();
            String weekday = sdf.format(cal.getTime());

            String weekStepsFinal= weekSteps + " steps on " + weekday; //set Textfield to steps and the day 

            FeedItem item = new FeedItem();
            item.setTitle(weekStepsFinal);

            feedItemList.add(item);

        }
    }

}

There are 7 datasets btw.

enter image description here


Solution

  • If by "take away one day at a time" means that you want the days going backwards, then here's how:

    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    
    System.out.println("Last 7 days (starting today):");
    Calendar cal = Calendar.getInstance(); // Initialized to today/now
    for (int i = 0; i < 7; i++) {
        System.out.println("  " + sdf.format(cal.getTime()));
        cal.add(Calendar.DAY_OF_MONTH, -1); // Update to previous day at same time-of-day
    }
    

    OUTPUT

    Last 7 days (starting today):
      Monday
      Sunday
      Saturday
      Friday
      Thursday
      Wednesday
      Tuesday