How to save data in an android app

You have two options, and I’ll leave selection up to you.

  1. Shared Preferences

    This is a framework unique to Android that allows you to store primitive values (such as int, boolean, and String, although strictly speaking String isn’t a primitive) in a key-value framework. This means that you give a value a name, say, “homeScore” and store the value to this key.

    SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("homeScore", YOUR_HOME_SCORE);
    
    // Apply the edits!
    editor.apply();
    
    // Get from the SharedPreferences
    SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
    int homeScore = settings.getInt("homeScore", 0);
    
  2. Internal Storage

    This, in my opinion, is what you might be looking for. You can store anything you want to a file, so this gives you more flexibility. However, the process can be trickier because everything will be stored as bytes, and that means you have to be careful to keep your read and write processes working together.

    int homeScore;
    byte[] homeScoreBytes;
    
    homeScoreBytes[0] = (byte) homeScore;
    homeScoreBytes[1] = (byte) (homeScore >> 8);  //you can probably skip these two 
    homeScoreBytes[2] = (byte) (homeScore >> 16); //lines, because I've never seen a                   
                                                  //basketball score above 128, it's
                                                  //such a rare occurance.
    
    FileOutputStream outputStream = getApplicationContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
    outputStream.write(homeScoreBytes);
    outputStream.close();
    

Now, you can also look into External Storage, but I don’t recommend that in this particular case, because the external storage might not be there later. (Note that if you pick this, it requires a permission)

Leave a Comment