Search code examples
androidandroid-recyclerviewthreetenbp

How to display local date type using recycle view in android?


I'm using the Threeten time zone to store the local date in a list of the LocalDate type.

Here's my code :

private List<LocalDate> getWeekDays() {
        ZoneId z = ZoneId.of("Pacific/Auckland");  // Or ZoneId.of( "Africa/Tunis" )
        LocalDate today = LocalDate.now( z ) ;

        LocalDate localDate = today.with( org.threeten.bp.temporal.TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) ) ;
        List< LocalDate > dates = new ArrayList<>( 7 ) ;
        for( int i = 0 ; i < 7 ; i ++ ) {
            localDate = localDate.plusDays( i ) ;
            dates.add( localDate ) ;
        }
            return dates;

    }

The problem is after passing list array to recycle view. I'm getting an error while fetching it to the recycle view.

Recycle view code :

 public void onBindViewHolder(@NonNull HoldViews holder, int position) {

        holder.tx1.setText(WeekDays[position]);
        String[] date = Dates.toArray(new String[0]);// Dates is list array of type LocalDate
       holder.tx3.setText(date[position]);

    }

If though I converting into the String array. I'm getting the following error " java.lang.ArrayStoreException: source[0] of type org.threeten.bp.LocPlDate cannot be stored in destination array of type java.lang.String[]". Please help me.


Solution

  • Instead of converting the entire array of Dates to an array of Strings EVERY time a new view is bound I would suggest directly pulling the LocalDate object directly using the given position.

    Then convert the LocalDate to a String using the toString() method.

    public void onBindViewHolder(@NonNull HoldViews holder, int position) {
    
        holder.tx1.setText(WeekDays[position]);
        String dateString = dateList.get(position).toString() // I don't know what the variable name you used is
        holder.tx3.setText(dateString);
    
    }