0

I have created a datepicker where the user can pick a from and to date using the borax12 library. This opens a dialog where the user can set a date and when they press Ok it will set the date into this method:

 @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth,int yearEnd, int monthOfYearEnd, int dayOfMonthEnd) {
        to.set(Calendar.YEAR, year);
        to.set(Calendar.MONTH, monthOfYear);
        to.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        from = Calendar.getInstance();
        from.set(Calendar.YEAR, yearEnd);
        from.set(Calendar.MONTH, monthOfYearEnd);
        from.set(Calendar.DAY_OF_MONTH, dayOfMonthEnd);

        String date = "You picked the following date: From- "+dayOfMonth+"/"+(++monthOfYear)+"/"+year+" To "+dayOfMonthEnd+"/"+(++monthOfYearEnd)+"/"+yearEnd;
        dateTextView.append(new StringBuilder().append(date) + "\n");
    }

This works fine as the dates get appended to the dateTextView. But how can I store each date into an arraylist each time and into memory on the users phone or a database?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Sam
  • 1,207
  • 4
  • 26
  • 50
  • 1
    Near duplicate by same author hours apart: [How can I continuously check if the dates entered to and from are equal to the current date for the next year?](https://stackoverflow.com/q/46025288/642706) – Basil Bourque Sep 03 '17 at 19:39

2 Answers2

2

The Calendar class is now legacy, supplanted in Java by the java.time classes. For Android, see bullets below.

For a date-only value without time-of-day and without time zone, use LocalDate.

LocalDate from = LocalDate.of( year , monthOfYear , dayOfMonth ) ;

To get a new value based on an existing value, use a TemporalAdjuster. The class TemporalAdjusters provides several handy implementations. Apparently you would want lastDayOfYear.

LocalDate to = from.with( TemporalAdjusters.lastDayOfYear() ) ;

For Java, I would suggest tracking this pair of LocalDate objects using the LocalDateRange class found in the ThreeTen-Extra project. But that code is not back-ported to Android. You might want to create your own simple version of that class to combine the pair.

package com.example.javatimestuff;

import org.threeten.bp.Duration;
import org.threeten.bp.LocalDate;

public class DateRange
{

    private LocalDate start, stop;
//    private Duration duration ;  // Cache value if calling `getDuration` frequently.
//    private String stringed ; // Cache value if calling `toString` frequently.

    public DateRange ( LocalDate startArg , LocalDate stopArg )
    {
        this.start = startArg;
        this.stop = stopArg;
    }

    public LocalDate getStart ()
    {
        return this.start;
    }

    public LocalDate getStop ()
    {
        return this.stop;
    }

    public Period toPeriod ()
    {
        Period p = Period.between( this.start , this.stop );
        return p;
    }

    @Override
    public String toString ()
    {
        // Per ISO 8601 standard.
        // https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
        String s = this.start.toString() + "/" + this.stop.toString();
        return s;
    }

    static public LocalDate parse ( String input ) {  // Obviously in real work you would make this safer: check for nulls, check for empty string, check for two parts, catch `DateTimeParseException`.
        String[] parts = input.split( "/" );
        LocalDate start = LocalDate.parse( parts[0]) ;
        LocalDate stop = LocalDate.parse( parts[1]) ;
        DateRange dr = new DateRange(start , stop ) ;
        return dr ;
    }
}

Call that class by constructor.

DateRange dr = new DateRange( from , to ) ;

Store in a List of type DateRange, our custom class.

List<DateRange> ranges = new ArrayList<>() ;
ranges.add( dr ) ;

For storage, serialize the List. See: Wikipedia & Oracle Tutorial.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Thanks for this, it looks good and what i'm looking for. I can't find it anywhere how can I compile the ThreeTen-Extra library into build.gradle on Android? Also if I serialize the Arraylist can this still be accessed if the user closes the app? – Sam Sep 03 '17 at 19:53
  • @Samantha Read the links I posted. One on How to use ThreeTenABP, and one on serializing. Also: [Wikipedia](https://en.wikipedia.org/wiki/Serialization) & [Oracle Tutorial](https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html). – Basil Bourque Sep 03 '17 at 21:07
  • Ahh thanks so ThreeTenABP is the same as ThreeTen-Extra? I read that it's basically the same as using Joda time on android. https://peirr.com/jodatime-vs-threetenabp-android-datetime-tool-comparison/ – Sam Sep 03 '17 at 21:10
  • 1
    @Samantha Again, I already addressed that in this Answer. I strongly suggest you slow down, read more, post less. For discussion, see [JavaRanch.com](https://javaranch.com). – Basil Bourque Sep 03 '17 at 21:11
0

Simply create an Arraylist (List<String> list= new Arraylist()) when initializing the class and use list.add() whenever you need. It will create multiple instances of Strings inside your list.

You can save to SharedPreferences or a DB like SqLite (or even to a file or Server), decide what you want.

Gilad Eshkoli
  • 1,253
  • 11
  • 27
  • Thanks if I use SharedPreferences and the user closes all the apps on their phone will this data still be stored? – Sam Sep 03 '17 at 13:15
  • Yes, that is the whole point of Shared Preferences, to keep data even if user closes the app and re-open. If you must keep the data even if app is uninstalled, try referring to keep the code on a file (Which can be deleted as well from File Manager on phone if it is not private) or a remote Server. – Gilad Eshkoli Sep 03 '17 at 13:19