0

I'm making a game that if he/she finished the first level, the level 2 button (invisible)will appear and save the visibility of level 2 button if I exit the game.

2 Answers2

1

Do this after completion of LEVEL 1:

btn_LEVEL2.setVisibility(View.VISIBLE); //making Level 2 button visible

Saving to Shared Prefs:-

SharedPreferences pref = 
getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
Editor editor = pref.edit();
editor.putBoolean("level2Visibility", true);  //saving boolean
// Save the changes in SharedPreferences
editor.commit(); // commit changes

Retreiving Shared Pref Data:-

boolean visibility = pref.getBoolean("level2Visibility",false); //here false is the default value

More Examples : Shared Prefs Examples

Nadeem Shaikh
  • 883
  • 7
  • 15
  • sorry Im beginner here in android studio and I dont know the codes how to save visibility in shared preference thanks – MercyLiza Malobago Sep 08 '19 at 14:24
  • boolean visibility = pref.getBoolean("level2Visibility",false); how can I connect this to btn_LEVEL2? – MercyLiza Malobago Sep 08 '19 at 15:00
  • btn_LEVEL2 is the variable for Level 2 button and level2Visibility is the key for storing the status of level 2 button you can name it anything as per your choice. As soon as the level 1 is over make level 2 visible and call shared pref function. – Nadeem Shaikh Sep 08 '19 at 19:51
0

To change the visibility you use <your view>.setVisiblity(either of View.VISIBLE , View.INVISIBLE and View.GONE);

To store simple data (not large one), you use shared preferences. To store data you need to use a key to identify it

for example:

public static final String LEVEL = "level";
public static final String PREFERENCES = "preferences";

in onCreate method of MainActivity you can use like this:

//to store level
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE).edit().putInt(LEVEL, 2).apply();
//to get stored level
int level = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE).getInt(LEVEL, 1);//note that 1 is default value here it will be used if you have not stored any value to it. It will be used by default. 

that's all you need to know about storing data. You can check this link if you want to know more. It has a good tutorial.

Mehul Pamale
  • 138
  • 1
  • 10