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?
-
Start here: http://developer.android.com/guide/topics/data/data-storage.html – RED_ Jan 26 '14 at 17:57
-
Have the answers helped you? – Michael Yaworski Jan 26 '14 at 18:29
3 Answers
Use SharedPreferences for storing level number:
http://developer.android.com/reference/android/content/SharedPreferences.html
http://android-er.blogspot.ru/2011/01/example-of-using-sharedpreferencesedito.html

- 2,113
- 1
- 13
- 14
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!

- 396
- 1
- 4
- 9
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

- 13,410
- 19
- 69
- 97