skip to Main Content

I want to create a game that counts the clicks made in 60 seconds and saves the record. I would like this record to be saved on the device even after the app is closed. Is there some kind of variable that allows me to do this?

2

Answers


  1. SharedPreferences is probably the place to start with this. You can view Android documentation related to it here along with code examples: Save key-value data

    There are some other options for saving data in an Android app on the left pane of that page, but SharedPreferences is probably the most applicable based on your described use case.

    Login or Signup to reply.
  2. Android’s Shared Preferences seem to be the most relevant option for you.
    Refer to the official documentation for an in depth look:
    https://developer.android.com/training/data-storage/shared-preferences

    These code samples should help you as well:
    To save a value into the Shared Preferences:

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key); //set a default/backup option 
    int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);
    

    Make sure to keep the key identical between placing values into the preferences and retrieving.

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
    int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search