Search code examples
androidandroid-studiosaving-data

Where to store app data?


I'm building relatively simple app/game which consists of tasks and subtasks. The user's progression should be saved. User also have small amount of settings.

For now app doesn't connect to external services, but in the future the goal is to use Facebook or something similar for user registration and add a feature to share progressinon/accomplishment with other users.

I'm new in app development and I don't know which data storage method to choose. If I've not mistaken there's key-value sets, saving in a file and database option.

To get things done fast and maybe even release the v. 1.0 I'd like to go with the most simple solution. So, I'd like to know is there a downside to choose the key-value or saving in a file option and how difficult is it to switch to database-based saving? Or should I just use the database from the start?

I salute You for taking the time to answer this!

-Timo


Solution

  • I recommend for you the SharedPreferences. This is an in Android simple class, that stores you data in Key-Value sets.

    Here is the code:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    

    This initialize your SharedPreferences. If you want to write/change a value, do this:

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

    You also can put in there other types of values, but than you need to call putString or putBoolean or even other types.

    To read the value do this:

    int a = prefs.getInt("KEY_TO_VALUE", 0);
    

    This code need like always your parameter your Key and a the second parameter a default value.

    Another tip for you is, that if you want to use this in a normal app with an easy UI there is something called PreferenceScreen.