mercredi 16 novembre 2016

Updating random String every day

I have ArrayList with different Strings. I would like to choose one random String from this ArrayList every day and show it in the TextView. I followed the instructions given in this link: display a random string in textview once a day for java and android studio however something is wrong. Firstly, I set the initial text in the textView.

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

Then I create 2 dates: CurrentDate always should show given time. dateTime is the date stored in SharedPreferences. At first, CurrentDate and dateTime are the same. Then, the next day the dates are not equaled so the text should be updated and dateTime should be saved so the dates are equal.

    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);
}

This code does not work because after one day, the text is not updated. It still shows "Z1". I am quite new in programming and I would appreciate any help.




Aucun commentaire:

Enregistrer un commentaire