SharedPreferences vs SQLite Database vs Room Database, which should I use for my project and why? Pros and Cons [closed]

Tags: , , , ,



I have a custom ListView of Semesters, a Semester is an object, in the MainActivity of an app I’m developing to learn more about Android developing and databases. That ListView is created by the user since the user can add an infinite amount of Semesters by pressing a button called: +New Semesters. My intention is to save that ListView of Semesters somewhere since everything the user adds is deleted after the application is closed. I’ve researched some ways on how to do this and I’ve found few options: SharedPreferences, SQLite Database, and Room Database. I need help on choosing the best one for my application and one that has sufficient documentation for someone that has never worked with any database. I appreciate the help!

Answer

You can use SharedPreferences or Room (an abstraction layer over SQLite), both will work for you. If you go with SharedPreferences, you will have to write quite less code to achieve your target, and If you go with Room, you will be writing a bit longer code to achieve your target.

đź’ˇ Room is the recommended way for these types of database, where SharedPreference is likely to be used for key-value pairs.

Programming Language – Kotlin

SharedPreference

save your list as in String form when app is going to close, just write in onPause() method

override fun onPause() {
    val listType = object : TypeToken<ArrayList<Semester>>() {}.type
    preferences.putString("SEM_LIST", Gson().toJson(customSemesterAdapter.list(), listType))
    super.onPause()
}

get your list from saved String when app is going to open, just write in onResume() method

override fun onResume() {
    val savedData = preferences.getString("SEM_LIST")
    if (!savedData.isNullOrEmpty()) {
        val listType = object : TypeToken<ArrayList<Semester>>() {}.type           
        val list: ArrayList<Semester> = Gson().fromJson(savedData, listType)
        mySemesters.clear()
        mySemesters.addAll(list)
        customSemesterAdapter.notifyDataSetChanged()
    }
    super.onResume()
}

Room

  • Add dependency then re-build or sync now

      implementation "androidx.room:room-runtime:$rootProject.roomVersion"
      kapt "androidx.room:room-compiler:$rootProject.roomVersion"
    
  • Convert your POJO with @Entity

  • Create Room Database with @Database

  • Create an interface for Data Access Object with @Dao

You can find plenty of tutorials on Room on the internet. you can check Room theory and Practical with Room



Source: stackoverflow