每天更新随机字符串

时间:2016-11-16 19:11:51

标签: java android date arraylist random

我有不同字符串的ArrayList。我想每天从这个ArrayList中选择一个随机字符串并在TextView中显示它。我按照此链接中的说明进行操作:display a random string in textview once a day for java and android studio但是出了点问题。 首先,我在textView中设置了初始文本。

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainscreen);
    TextView textview = (TextView) findViewById(R.id.firsttask);
    textview.setText("Z1");

然后我创建了2个日期:CurrentDate总是应该显示给定的时间。 dateTime是存储在SharedPreferences中的日期。起初,CurrentDate和dateTime是相同的。然后,第二天日期不相等,因此应更新文本并保存dateTime以使日期相等。

    Calendar c= Calendar.getInstance();

    SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
    String currentDate= df.format(c.getTime());
    String dateTime = df.format(c.getTime());
    saveDate();
    loadDate();
    if(!(dateTime.equals(currentDate))){
        updateList1();
        saveDate();
    }

    public void saveDate (){
    SharedPreferences prefs =     getApplicationContext().getSharedPreferences(MY_PREFS_DATE,         Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("date", dateTime);
    editor.apply();
    }
    public void loadDate (){
    SharedPreferences prefs =        getApplicationContext().getSharedPreferences(MY_PREFS_DATE, Context.MODE_PRIVATE);
    dateTime = prefs.getString("date","default value");
    }

    public void updateList1 (){
    ArrayList<String> task1 = new ArrayList<String>();
    task1.add("t1");
    task1.add("t2");
    task1.add("z3");
    task1.add("z4");
    Random r = new Random();
    task = task1.get(r.nextInt(task1.size()));
    TextView textview = (TextView) findViewById(R.id.firsttask);
    textview.setText(task);
}

此代码不起作用,因为在一天之后,文本不会更新。它仍显示“Z1”。我是编程新手,我很感激任何帮助。

2 个答案:

答案 0 :(得分:2)

它不起作用,因为当您运行此代码时,首先运行saveDate();,然后运行loadDate();以均衡您的值。首先加载然后保存,它应该按预期工作;

答案 1 :(得分:0)

Answer by Dochan是正确的:您始终保存当前日期,而不先加载保存的日期进行比较。

java.time

此外,您正在使用最早版本的Java中棘手的旧日期时间类。现在是遗留的,取而代之的是java.time类。

LocalDate

LocalDate类表示没有时间且没有时区的仅限日期的值。

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

ISO 8601

将日期时间值序列化为文本时,请使用标准ISO 8601格式。这些格式在人类文化中是明智的,直观的,并且是明确的。对于仅限日期的值,格式为YYYY-MM-DD,例如2016-01-23

java.time类在解析和解析时默认使用ISO 8601格式。生成字符串。

修订代码

我会将有关更新的所有逻辑移到单个方法updateMessageIfNewDay中。将消息选择逻辑分离为可以改变的(a),以及(b)if-needs-updating代码不需要知道消息的来源以及消息的选择方式。

您可以检测JVM的当前默认时区。但是,在运行时期间,任何共享该JVM的任何线程中的任何代码都可以随时更改。因此,如果正确的日期至关重要,请询问用户预期的时区。为简单起见,我们使用默认区域。

下面的代码是草稿,从未测试过。

班上的成员变量:

LocalDate messageDate ;
String messageContent ;

我不知道Android首选项实用程序,所以我使用伪代码。

void updateMessageIfNewDay() {
    // Determine the current date.
    ZoneId z = ZoneId.systemDefault() ;  // Or use time zone specified by user: ZoneId.of( "America/Montreal" )
    LocalDate today = LocalDate.now( z ) ;

    // Load from storage the date for which we previously displayed a message.
    LocalDate storedMessageDate;
    … if no saved value, leave var null.
        // No code needed here. Leave null.
    … else load string and parse.
        String s = … // load the YYYY-MM-DD string from Android prefs.
        storedMessageDate = LocalDate.parse( s ) ;
    … end if

    // Need to update if:
    // (a) no message stored in prefs, or 
    // (b) No message on this object, so not yet displayed (first encounter in this launch of the app), or
    // (c) stored message is old (not equal to today).
    if( ( null == storedMessageDate ) || 
        ( null = this.messageContent ) || 
        ( ! storedMessageDate.isEqual( today ) ) ) 
    {
            // Update values in memory.
            this.messageDate = today ;
            this.messageContent = this.fetchAnotherMessage();

            // Update values in storage.
            Prefs.save( "messageDate" , this.messageDate.toString() ) ; // pseudo-code
            Prefs.save( "messageContent" , this.messageContent );

            // Update display with contents of this.messageContent.
            … Android UI update code here
     }

}

对于随机选择,您可以使用Math.random()作为方便,而不是跟踪自己的Random对象。

private String fetchAnotherMessage() {
    // If called often, save this list as a member on the class, or as a constant. Or if slow-to-load such as database access, save this list.
    // For fast list not called often, don't bother, just instantiate each time.
    int initialCapacity = 4 ;
    List<String> messages = new ArrayList<>( initialCapacity ) ;
    messages.add( "t1" ) ;
    messages.add( "t2" ) ;
    messages.add( "z3" ) ;
    messages.add( "z4" ) ;

    // Choose a random from min to max, both inclusive.
    int min = 1 ;
    int max = messages.size() ;
    int range = ( (max - min) + 1 ) ;     
    int n = ( ( (int)(Math.random() * range) ) + min ) ;
    int index = ( n - 1 ) ; // A `List` is accessed by zero-based index number. So subtract one.
    String message = messages.get( index ) ;
    return message ;
}

关于java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和&amp; SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore