using sharedpreferences to remember textview hidden after it's clicked

Viewed 82

I have a textview that when user clicks it, I want it to be invisible. But I want it to stay invisible, even after user has reloaded the app, using "sharedpreferences". How to get shared preferences working and then recalled correctly?

This is my code for storing the preference when user clicks the textview:

textView.setVisibility(View.INVISIBLE);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("was_clicked", true);
editor.commit(); // commit changes

So I understand this will store a true/false boolean in shared preferences called" was_clicked".

But now how do I have it checked for "true" in the onCreate method of the activity and then have it set TextView to view.INVISIBLE if was_clicked = true?

3 Answers

Check out this article. But to answer your question specifically

if (getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE).getBoolean("was_clicked", false))
    textView.setVisibility(View.INVISIBLE);

You can check the value using this method:

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean wasClicked = pref.getBoolean("was_clicked",false);
if (wasClicked){
      textView.setVisibility(View.INVISIBLE);
}else {
      textView.setVisibility(View.VISIBLE);
}

In your onCreate method you should create preferences and read from them like this:

static final String PREFERENCES_NAME = "MyPref";
static final String WAS_CLICKED_NAME = "was_clicked";

@Override
void onCreate()
{
  SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE);
  boolean invisible = preferences.getBoolean(WAS_CLICKED_NAME, false); // 2nd argument is the default value
  if (invisible)
  {
    textView.setVisibility(View.INVISIBLE);
  }
}

getBoolean method will read value of "was_clicked" preference. 2nd argument will be returned if you haven't yet put value "was_clicked" to shared preferences, so you can return false if you haven't put this preference to show the textView.

Related