Why Localdate Value Did'nt Set On Today Date
Solution 1:
The problem with your code is that in each of the 7 iterations of the loop you are assigning the hints to all the buttons, so you are doing 7 assignments to each button, total 49 assignments, increasing the date after each assignment, so you reach these incorrect dates. So the result is that you see the values assigned from the last iteration which are obviously wrong. Do 1 assignment to 1 button in each iteration like this:
DateTimeFormatterdateFormater= DateTimeFormatter.ofPattern("d");
ZoneIdzone= ZoneId.of("Asia/Jakarta");
LocalDatedate= LocalDate.now(zone);
intamount=1;
intbuttonCount=7;
for (inti=0; i < buttonCount; i++){
intbuttonId= getResources().getIdentifier("hari_" + (i + 1), "id", getPackageName());
Buttonbutton= (Button) findViewById(buttonId);
button.setHint(date.format(dateFormater));
date = date.plusDays(amount);
}
With this line:
int buttonId = getResources().getIdentifier("hari_" + (i + 1), "id", getPackageName());
you get the integer id
of each button and with this line:
Buttonbutton= (Button) findViewById(buttonId);
you get a variable referencing the button.
Solution 2:
Using a stream
The Answer by forpas is correct. For fun here, let's try using a stream. I am not claiming this is better than the other first solution, just an alternative.
We use an IntStream
to count to seven. We use the produced integer to add a number of days to our current date, and to access a specific button by using naming approach shown in that other Answer.
Rather than go through a DateTimeFormatter
to get a day-of-month, we call LocalDate::getDayOfMonth
. Convert from int to string via String.valueOf
.
I've not tried running this code as I do not do Android work. But hopefully it is close to working.
ZoneIdz= ZoneId.of( "Asia/Jakarta" ) ;
LocalDatetoday= LocalDate.now( z ) ;
IntStream
.range( 0 , 7 )
.forEach(
i ->
(
(Button) findViewById(
getResources().getIdentifier( "hari_" + (i + 1), "id" , getPackageName() ) // See: https://stackoverflow.com/a/59849331/642706
)
) // Returns a `Button`.
.setHint (
String.valueOf( // Convert int (day-of-month) to text.
today
.plusDays( i ) // Produces a new `LocalDate` object rather than modifying the original (immutable objects).
.getDayOfMonth() // Returns an `int`.
)
)
;
)
;
Post a Comment for "Why Localdate Value Did'nt Set On Today Date"