Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Data Persistence in Android Development

What is Data Persistence?

Data persistence in Android refers to the ability of an application to save data and retain it even after the application is closed or the device is restarted. This is a crucial feature for many mobile applications, as it ensures that important user data is not lost between sessions.

Why is Data Persistence Important?

Data persistence is important because it enhances the user experience by maintaining state and user data across application launches. For example, user preferences, application settings, and user-generated content need to be stored persistently to ensure continuity and reliability.

Methods of Data Persistence in Android

There are several methods to achieve data persistence in Android:

  • SharedPreferences
  • Internal Storage
  • External Storage
  • SQLite Databases
  • Room Persistence Library

Using SharedPreferences

SharedPreferences is used to store simple key-value pairs. It is suitable for storing small amounts of primitive data such as user settings.

Example:

To store a value in SharedPreferences:

SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "JohnDoe");
editor.apply();
                

To retrieve a value from SharedPreferences:

SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "defaultName");
                

Using Internal Storage

Internal Storage is used to store private data on the device memory. The data is sandboxed and cannot be accessed by other applications.

Example:

To write to internal storage:

String filename = "myfile";
String fileContents = "Hello World!";
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(fileContents.getBytes());
fos.close();
                

To read from internal storage:

FileInputStream fis = openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    sb.append(line);
}
String fileContents = sb.toString();
                

Using External Storage

External Storage is used to store large amounts of data in shared storage that is accessible by other applications and users. This includes the SD card or other shared storage.

Example:

To write to external storage:

String filename = "myfile";
String fileContents = "Hello World!";
File file = new File(getExternalFilesDir(null), filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(fileContents.getBytes());
fos.close();
                

To read from external storage:

File file = new File(getExternalFilesDir(null), "myfile");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    sb.append(line);
}
String fileContents = sb.toString();
                

Using SQLite Databases

SQLite is a lightweight database used for storing structured data in Android. It is suitable for complex data and relational data storage.

Example:

To create and use an SQLite database:

public class MyDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "mydatabase.db";
    private static final int DATABASE_VERSION = 1;

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT)";
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS mytable");
        onCreate(db);
    }
}

// To insert data:
MyDatabaseHelper dbHelper = new MyDatabaseHelper(getContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John Doe");
long newRowId = db.insert("mytable", null, values);

// To read data:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query("mytable", null, null, null, null, null, null);
while (cursor.moveToNext()) {
    String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
}
cursor.close();
                

Using Room Persistence Library

The Room Persistence Library provides an abstraction layer over SQLite, making it easier to manage database operations without much boilerplate code.

Example:

To define a Room database:

@Entity
public class User {
    @PrimaryKey
    public int uid;
    @ColumnInfo(name = "first_name")
    public String firstName;
    @ColumnInfo(name = "last_name")
    public String lastName;
}

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List getAll();

    @Insert
    void insertAll(User... users);
}

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

// To use the Room database:
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "database-name").build();

UserDao userDao = db.userDao();
User user = new User();
user.uid = 1;
user.firstName = "John";
user.lastName = "Doe";
userDao.insertAll(user);

// To read data:
List users = userDao.getAll();
                

Conclusion

Data persistence is a fundamental aspect of Android development, ensuring that user data is retained between sessions. Depending on the complexity and nature of the data, developers can choose from various methods such as SharedPreferences, Internal Storage, External Storage, SQLite databases, and the Room Persistence Library.