Search code examples
androidandroid-layoutbuttonandroid-buttonsettext

setText() method resetting after user exits activity


So when the user clicks the button i want it to set the text to a future time. It works but when the user closes the activity the buttons reset. Also if someone could also guide me on creating a method that resets the button text after time is reached. Heres my code to setText on the button.

private void setReloadTime(int reload, Button btn) {
    int minutes = (reload/1000/60)%60;
    int hours = reload/1000/60/60;

    Calendar c = Calendar.getInstance();
    int min = c.get(Calendar.MINUTE);
    int hr = c.get(Calendar.HOUR_OF_DAY);
    if (reload ==0){
        btn.setTextColor(R.color.colorAccent);
        btn.setText("Ready Again In 24 Hours");
        return;

    }
    if (minutes+min>60) hr++;
    int finMin = (minutes + min) %60;
    int finHr= (hours + hr)%24;
    String fin = "Ready again at " +finHr + ":";
    if (finMin<10){
        fin = fin +"0"+finMin;
    } else{
        fin = fin + finMin;
    }
    btn.setTextColor(R.color.colorAccent);
    btn.setText(fin);


}

Solution

  • Use shared preference

    Eg:

    public static final String MyPREFERENCES = "MyPrefs" ;
       SharedPreferences sharedpreferences;
    
            sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    
      Editor editor = sharedpreferences.edit();
        editor.putString(Name, fin);
        editor.commit(); 
         if (sharedpreferences.contains(Name))
              {
    
         btn.setText(sharedpreferences.getString(Name, ""));
    
              }
    

    http://www.tutorialspoint.com/android/android_shared_preferences.htm