-2

I am pretty new to programming and am currently trying to program a small app for a course at my university. So I have a first Activity that opens a second Activity by clicking on a list element. In this second Activity there are two buttons. By clicking on the first one I make them both disappear by using setVisibility(View.GONE) but the problem is that when I close the app and re-open it they both re-appear. This also happens if I press the back button and then re-open the second Activity. I tried reading about the lifecycle but it's not really clear to me how it works. Thanks in advance for any help.

strobe
  • 3
  • 2

2 Answers2

2

Try to use Shared Preference, declare it in your onCreate Method.

SharedPreferences sharedPref = 
getActivity().getPreferences(Context.MODE_PRIVATE);

Read the Boolean variable in onCreate method of your second Activity.

Boolean highScore = sharedPref.getBoolean("show", true);

Save the Boolean variable that stores whether the buttons should show or not

Boolean show = false; // Controlled by your button events

SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("show", show);
editor.commit();
Sky
  • 1,435
  • 1
  • 15
  • 24
  • Thanks. I did it slightly differently but it works now! I also managed to add a string,by clicking on the same button, to a list of strings in this second activity but the same problem presents itself, i.e. the added string disappears when closing the app. I read somewhere that it could be solved again via SharedPreferences but I'm not sure how. Can you help? Thanks in advance. – strobe Apr 24 '17 at 17:35
  • You can use Shared Preference to store the String array. Read this: http://stackoverflow.com/questions/3876680/is-it-possible-to-add-an-array-or-object-to-sharedpreferences-on-android – Sky Apr 25 '17 at 03:52
0

This happens because you are not saving the states of buttons. Best thing to do is use SharedPreferences. Have a look at this link.

hhk
  • 71
  • 4