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.
Asked
Active
Viewed 116 times
-2
-
save their state somewhere. Like in the file, or in SharedPreferences. And check if the state is show - then show them. If it is hide - hide them. – Vladyslav Matviienko Apr 24 '17 at 09:22
2 Answers
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