-2

I'm developing a level-based app, and I want to be able to save the user's level number (1, 2, 3 etc..) and then when the app starts get the level number and do something with it. How can I do it?

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
Vessilate
  • 3
  • 2

3 Answers3

0

If you read up in the documentation here you can see that to save data like a level number, you can use SharedPreferences. First, you'll need a SharedPreferences object, which you can obtain using

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

Then to save a piece of data, use:

SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("level", level);
editor.commit();

And finally, to get that level back later, use:

sharedPref.getInt("level", 0);

Good luck!

Freddy Tuxworth
  • 396
  • 1
  • 4
  • 9
0

Use Shared Preferences like so:

Create these methods for use, or just use the content inside of the methods whenever you want:

public int getLevel()
{
   SharedPreferences sp = getSharedPreferences("prefName", 0);
   int level = sp.getInt("levelReference", 1);
   return level;
}

public void setLevel(String level)
{
   SharedPreferences.Editor editor = getSharedPreferences("prefName", 0).edit();
   editor.putInt("levelReference", level);
   editor.commit();
}

The 1 in sp.getInt("levelReference", 1); means that the method will return 1 if the preference is not found, so the default level is 1.

You can call them like this:

int level = getLevel(); // level is now the level that the user is on

setLevel(4); // user is now on level 4
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97