Introduction
Android provides several ways to store persistent data. Each of these has its use cases and advantages. You may want to use one technology instead of the other depending on your needs, starting with.
1. Room Database (SQLite)
Room is an SQLite database wrapper that makes it easy to save and retrieve data from an SQLite database. The Room library provides an object-mapping abstraction layer that allows fluent database access while harnessing the full power of SQLite.
When to use Room?
If your application requires storing bulks of structured data, go for it.
Where does this data stored?
this database is saved in the main application directory under the databases folder. (Which cannot be accessed other than application)
How to use Room Database?
Add the following dependencies to your build.gradle (Module level)
//Module level
dependencies {
// Room
implementation "androidx.room:room-runtime:2.4.3"
kapt "androidx.room:room-compiler:2.4.3"
// Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:2.4.3"
// Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'
}
Create Data Access Objects
(Dao.kt) for your database.
DAOs
are used to access your application’s persisted data. They are a better and modular way to access your database as compared to query builders or direct queries.
@Dao interface Dao { //Inserting data @Insert suspend fun insertNFTs(nft: NFTs) //Fetching data using simple SQL Query @Transaction @Query("SELECT * FROM NFTs") suspend fun getMyNFTs() : List<NFTs> }
Create abstract Room Database
class.
@Database(
entities = [
NFTs::class,
], version = 1)
abstract class database : RoomDatabase() {
abstract val dao: Dao
companion object {
@Volatile
private var instance: database? = null
fun getInstance(context: Context): database {
synchronized(this) {
return instance ?: Room.databaseBuilder(
context.applicationContext,
database::class.java,
"my_nft_collection" //DATABASE_NAME
).fallbackToDestructiveMigration()
.build().also {
instance = it
}
}
}
}
}
Create entity data NFTs.kt
class.
@Entity
data class NFTs(
@PrimaryKey(autoGenerate = false)
var token: String,
var designer : String? = null,
var desc : String? = null
)
Add Dao lateinit var and initialize in onCreate() method and call dao functions inside CoroutineScope
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var data: Dao override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) data = database.getInstance(this).dao CoroutineScope(Dispatchers.IO).async { data.insertNFTs("123Buyme","Sick?yes","Most Popular") data.getMyNFTs() } setContentView(binding.root) } }
2. Shared Preferences
Shared Preference is a simple key-value storage system for saving user preferences and app settings. It’s not suitable for large amounts of data, but it’s the easiest way to save data on Android.
To read the data from the store you have to know the key to the data. This makes reading the data very easy. Shared preferences have fast read and write time complexity if used efficiently.
When to use Shared Preferences?
The Shared Preferences allow you to read and write persistent key-value pairs of primitive data types: booleans, floats, ints, longs, strings, and parcelable objects.
How to use Shared Preference in your Project.
Create PrefRepository.kt
class PrefRepository(val context: Context) {
private val pref: SharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
private val editor = pref.edit()
private val gson = Gson()
private fun String.put(long: Long) {
editor.putLong(this, long)
editor.commit()
}
private fun String.put(int: Int) {
editor.putInt(this, int)
editor.commit()
}
private fun String.put(string: String) {
editor.putString(this, string)
editor.commit()
}
private fun String.put(boolean: Boolean) {
editor.putBoolean(this, boolean)
editor.commit()
}
//clear
private fun String.clear() {
editor.remove(this)
editor.commit()
}
private fun String.getLong() = pref.getLong(this, 0)
private fun String.getInt() = pref.getInt(this, 0)
private fun String.getString() = pref.getString(this, "")!!
private fun String.getBoolean() = pref.getBoolean(this, false)
fun setToken(token : String){
TOKEN.put(token)
}
fun getToken() = TOKEN.getString()
fun setDesigner(designer : String){
DESIGNER.put(designer)
}
fun getDesigner() = DESIGNER.getString()
fun clearData() {
editor.clear()
editor.commit()
}
}
Create Constants.kt
const val TOKEN = "TOKEN"
const val DESIGNER = "DESIGNER"
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val prefRepository by lazy { PrefRepository(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
prefRepository.setToken("buyme123")
prefRepository.setDesigner("sick?yes")
setContentView(binding.root)
}
}
My GitHub Gist URL for the above code snippets
Haris-kaispe/Understanding-Persistence-Data-Storage-in-Android
References
https://medium.com/@babul.sust.cse/understanding-of-android-storage-system-17b6134f873
https://muditsen.medium.com/choosing-persistent-storage-in-android-ba3a458d50c6
https://developer.android.com/training/data-storage
Please share your kind feedback in the comments section. For any query, feel free to contact us or email us at [email protected]