Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete sharedpreference after 60minutes

I want to store login data but I want that data to be deleted after 60 minutes. What is the proper way to do this?

The app can be closed, stopped, opened in these 60 minutes. I don't want to use an internal database.

Here is my code for accessing SharedPreferences

sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Username, usernameTxt);
editor.putString(Password, passwordTxt);
like image 300
manuel_k Avatar asked Dec 10 '15 23:12

manuel_k


1 Answers

I think the easiest and most direct way to do this is keeping expired date:

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("Username", usernameTxt);
editor.putString("Password", passwordTxt);
editor.putLong("ExpiredDate", System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(60));
editor.apply();

And then check it

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.getLong("ExpiredDate", -1) > System.currentTimeMillis()) {
    // read email and password
} else {
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.clear();
    editor.apply();
}

But, @CommonsWare is right and keeping the information just in your process is more correct.

like image 115
Igor Tyulkanov Avatar answered Sep 16 '22 20:09

Igor Tyulkanov