đŸȘCaching Process in Android App

Ali Osman ARSLAN
Huawei Developers
Published in
3 min readDec 29, 2023
Android Caching

Introduction

Optimizing the performance and data exchange of an Android application is a crucial priority for contemporary developers. In this context, caching techniques, particularly in the realm of network requests and data retrieval, serve as indispensable tools for enhancing application efficiency. In this article, we will provide a step-by-step guide to caching processes in an Android application using the Kotlin programming language. Our specific focus will be on caching data from API requests. Now, let’s delve into this process more closely.

Let’s Start

1.Add Dependencies

In this step, we include the Retrofit and OkHttp libraries for network operations, and the Room library for local database operations.

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'androidx.room:room-runtime:2.2.5'
kapt 'androidx.room:room-compiler:2.2.5'

2.Retrofit and Room Initialization

In this step, we create a client for network operations using Retrofit and OkHttp. Additionally, we define the database cache to be used for Room.

val cacheSize = (10 * 1024 * 1024).toLong() // 10 MB
val cache = Cache(context.cacheDir, cacheSize)
val okHttpClient = OkHttpClient.Builder()
.cache(cache)
.build()

val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()

3.Room Entity

In this step, we create an Entity class that defines the model of the data to be stored in the Room database. Here, the ‘url’ field is used as a unique key.

@Entity(tableName = "data_cache")
data class DataCache(
@PrimaryKey val url: String,
val json: String,
val timestamp: Long
)

4.Room DAO

In this step, we define a Data Access Object (DAO) for Room. DAO includes access operations to the database. We insert data with ‘insertCache’ and query data for a specific URL with ‘getCache’.

@Dao
interface DataCacheDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCache(dataCache: DataCache)

@Query("SELECT * FROM data_cache WHERE url = :url")
suspend fun getCache(url: String): DataCache?
}

5.Room Database

In this step, we define an abstract class representing the Room database and specify the DAO to be used inside.

@Database(entities = [DataCache::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun dataCacheDao(): DataCacheDao
}

6.Room Database Instantiate

In this step, we instantiate the Room database.

val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "cache-database"
).build()

7.Cache Expiry Time Definition

In this step, we define a time to determine the validity of the cache

const val CACHE_VALIDITY = 5 * 60 * 1000 // Cache validity period, for example, 5 minutes.

8.Fetch Data with Caching Logic

In this step, we create a function that attempts to fetch data from the cache. If the data is present in the cache and still valid, it immediately returns. Otherwise, it fetches data from the network and saves it to both the cache and the Room database. If an error occurs, it returns an empty string

suspend fun fetchData(url: String): String {
val cachedData = db.dataCacheDao().getCache(url)
if (cachedData != null && System.currentTimeMillis() - cachedData.timestamp < CACHE_VALIDITY) {
return cachedData.json // Return cached data if still valid.
} else {
try {
val responseBody = retrofit.create(YourApiService::class.java).getData(url).body()
if (responseBody != null) {
db.dataCacheDao().insertCache(DataCache(url, responseBody, System.currentTimeMillis()))
}
return responseBody ?: ""
} catch (e: Exception) {
e.printStackTrace()
return ""
}
}
}

Summary

Caching in Android plays a critical role in optimizing performance and data management. In this article, we detailed the cache management using the Kotlin programming language. We understood different types of caching strategies such as in-memory caching, disk caching, and network caching. Additionally, we learned to cache API responses step by step using powerful libraries like Retrofit and Room.

Applying caching strategies correctly not only improves user experience but also makes data exchange more efficient. However, there are best practices and important considerations to be mindful of in the use of these strategies.

It is crucial to adjust and monitor caching strategies based on application requirements. This ensures that the application continues to operate both quickly and reliably.

References

--

--