I want to get values from an array every day, respectively, and set these values to a textbox. I can get values from array and set them in textbox but next day value stays same. does not set the next value in array? what can I do?
<string-array name="morning">
<item>Good Morning. Message 1.</item>
<item>Good Morning. Message 2.</item>
<item>Good Morning. Message 3.</item>
</string-array>
mTestArray = getResources().getStringArray(R.array.morning);
preference_shared = this.getSharedPreferences("PREFERENCE", MODE_PRIVATE);
text_shared = this.getSharedPreferences("TEXT", MODE_PRIVATE);
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.DAY_OF_YEAR);
if (timeOfDay >= 0 && timeOfDay < 24) {
if (preference_shared.getBoolean("isFirstRun", true)) {
dailyGreetings.setText(mTestArray[(0) % (mTestArray.length)]);
saveDate();
}else {
if (!Objects.equals(preference_shared.getString("Date", ""), dateFormat.format(date))) {
int idx = new Random().nextInt(mTestArray.length);
dailyGreetings.setText(mTestArray[idx]);
text_shared.edit().putString("TEXT", dailyGreetings.getText().toString()).apply();
saveDate();
}
else {
dailyGreetings.setText(text_shared.getString("TEXT", ""));
}
}
}
3
Answers
It’s Easy just
In this snipped of code, I’m updating shared preference by date and counter.
Date: It will be saved for next date, and if these both are not matching, shared preference will gets update with counter.
Counter: The position of your strings-arrays.
Reset: I have add another check that if in case your counter reaches to the end of array, it will be reset to ‘0’.