BCA / B.Tech 13 min read

Data Persistence: Preferences and Files

Data Persistence: Preferences and Files

Data Persistence means saving data to a non-volatile memory (like the device storage) so that the data remains available even after the app is closed.

1: Saving and Loading User Preferences

What are SharedPreferences?

SharedPreferences is Android's framework that allows you to save and retrieve simple data in key-value pairs. It is ideal for saving a small amount of data, such as user settings (e.g., "Dark Mode" enabled/disabled), high scores, or the app's state.

This data persists on the device until the app is uninstalled.

Example of SharedPreferences in Java:


public class MainActivity extends AppCompatActivity {
    EditText nameEditText;
    TextView savedNameTextView;
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nameEditText = findViewById(R.id.name_edit_text);
        savedNameTextView = findViewById(R.id.saved_name_tv);

        // 1. Loading Data
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // 0 = Private Mode
        String savedName = settings.getString("userName", "No Name"); // "userName" is the key
        savedNameTextView.setText("Saved Name: " + savedName);
    }

    // Method to be called on a button click
    public void saveData(View view) {
        // 2. Saving Data
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        
        String currentName = nameEditText.getText().toString();
        editor.putString("userName", currentName); // Set the key-value pair
        
        // Apply the changes
        editor.apply(); // apply() works in the background (recommended)
        // editor.commit(); // commit() works on the UI thread
        
        Toast.makeText(this, "Name Saved!", Toast.LENGTH_SHORT).show();
        savedNameTextView.setText("Saved Name: " + currentName);
    }
}

2: Persisting Data to Files

To save more complex data than simple key-value pairs (like a JSON object, user-generated content, or log files), you can use the device's file system. Android provides two main locations to save data:

1. Internal Storage

  • What it is: This is a part of the device's memory that is private to your app.
  • Advantages:
    • Secure: Other apps or the user cannot access this data.
    • Always Available: It is always available.
    • Clean Uninstall: This data is automatically deleted when the user uninstalls your app.

2. External Storage

  • What it is: This is shared storage (like an SD card or an internal shared space).
  • Advantages: Good for saving large files (like photos, videos) that the user or other apps might need to access.

Example of Writing to and Reading from Internal Storage:


public class FileActivity extends AppCompatActivity {
    EditText fileContentEditText;
    TextView loadedContentTextView;
    private final String FILENAME = "my_private_file.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
        
        fileContentEditText = findViewById(R.id.file_content_et);
        loadedContentTextView = findViewById(R.id.loaded_content_tv);
    }
    
    // Button click method to save the file
    public void saveToFile(View view) {
        String string = fileContentEditText.getText().toString();
        try (FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE)) {
            fos.write(string.getBytes());
            Toast.makeText(this, "Saved to " + getFilesDir() + "/" + FILENAME, Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Button click method to load the file
    public void loadFromFile(View view) {
        try (FileInputStream fis = openFileInput(FILENAME);
             InputStreamReader inputStreamReader = new InputStreamReader(fis);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("
");
            }
            loadedContentTextView.setText(stringBuilder.toString());
            
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "File not found or error reading", Toast.LENGTH_SHORT).show();
        }
    }
}