Where Should You Save Data in Android?

Prerequisites

  • Have knowledge of android development.
  • Have an idea about ViewModels, Preferences/Datastore and Room.

Android apps cannot be complete without data, this can either be input from the user or fetched from a server. These data needs to be saved in some place so as to be used later, android offers a couple of options you can use to save your app data. The type of data will determine the option you will use to save, in this article, I will discuss about Shared ViewModel, SharedPreferences/Datastore and Room and when to use each of them.

1. Shared ViewModel

ViewModel does not persist data, but it can be used to save data that is only needed for a short time and used once. Let's say our app collects data during signup from user in three fragments before sending them to the server, since this data is only needed once(a user can't signup multiple times using same data) we don't have to persist them for long.

Fragment A -> Fragment B -> Fragment C

The approach will be to create variables in our ViewModel then initialize them with the user's input in Fragment A and B then send all of them on the third Fragment.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope

class MainViewModel : ViewModel() {
    private val repository = UserRepository()

    //variables for input from Fragment A
    private lateinit var firstName: String
    private lateinit var lastName: String
    private lateinit var emailAddress: String

    //variables for input from Fragment B
    private lateinit var phoneNumber: String
    private lateinit var course: String
    private lateinit var idNumber: String

    // call this function in Fragment A where the user inputs data
    // the variables above will be initialized by user input
    fun saveFragmentA(firstName: String, lastName: String, emailAddress: String) {
        this.firstName = firstName
        this.lastName = lastName
        this.emailAddress = emailAddress
    }

    // call this function in Fragment B where the user inputs data
    // the variables above will be initialized by user input
    fun saveFragmentB(phoneNumber: String, course: String, idNumber: String) {
        this.phoneNumber = phoneNumber
        this.course = course
        this.idNumber = idNumber
    }

    // call this function in last Fragment where user inputs remaining information
    fun registerUser(gender: String, school: String, age: Int) {

        // send the data to server
        viewModelScope.launch {
            repository.registerUser(
                firstName = firstName,
                lastName = lastName,
                emailAddress = emailAddress,
                phoneNumber = phoneNumber,
                course = course,
                idNumber = idNumber,
                gender = gender,
                school = school,
                age = age
            )
        }
    }
}

As you can see, this data will only be used once and lost once our ViewModel is killed. This is how you can use Shared ViewModel to save data.

NB: ViewModel has other usecases, but my focus was just on saving data.

2. SharedPreferences/Datastore

These are used to save key/value pair data, this means you assign data(value) to a key which you'll use to retreive them. This can be used to save data which are not structured and have only single values, some of the data can be user profile data. After a user registers(above) they'll get a response which will contain their profile information.

// example response
{
    "firstName":"Test",
    "lastName":"Test",
    "feeBalance": 5,000,
    "graduated":false,
    "accessToken":"wertyuhgfdsasdvbtrsertyh....."
}

As you can see, we can only have single values per user(maybe an or phone). For this type of data it will be good to use SharedPreference or Datastore to save them.

3. Room

Room is a persistence library which lets you save structured data, which you can manipulate to your need. This is mostly used when you have data which needs to be displayed in a list. I won't dive into room since I already have an article about it, please check Introduction to Room.

Thanks for reading, let's connect on twitter. Happy New Year!