DEV Community

SunnahSource
SunnahSource

Posted on

Build a 'Hadith of the Day' Card in Kotlin + Jetpack Compose (Offline Cache, 9 Languages, RTL)

Most Muslim apps eventually get the same request: "Can we show a hadith every day?" It sounds simple, but a good version needs a few things:

  • the Arabic text plus a translation in the user's language,
  • the reference (collection, book, hadith number and narrator) shown with the text,
  • offline support, because people open these apps on the metro, in the masjid or on a flight,
  • correct right-to-left layout for Arabic and Urdu.

In this tutorial we build exactly that in Kotlin + Jetpack Compose, using the free public sample from the SunnahSource Hadith API. The same pattern works for any of the other JSON samples on SunnahSource, for example Duas or Azkar.

Code for other platforms (Flutter, JavaScript, Python) and notes on the sample files are in the GitHub repo: https://github.com/sunnahsourceofficial-droid/sunnahsource-islamic-api


1. The data

The sample file is plain static JSON:

GET https://sunnahsource.org/data/json/hadith.json
Enter fullscreen mode Exit fullscreen mode

Trimmed response (real fields, one item shown, 3 of the 9 translations kept):

{
  "title": "Hadith Collections",
  "description": "Authentic hadith with translations in 9 languages",
  "is_free": false,
  "items": [
    {
      "id": 1,
      "collection": "Sahih Bukhari",
      "book": 1,
      "hadith_number": 1,
      "arabic": "إِنَّمَا الأَعْمَالُ بِالنِّيَّاتِ",
      "narrator": "Umar ibn Al-Khattab (RA)",
      "translations": {
        "en": "Actions are judged by intentions, and every person will get what they intended.",
        "ur": "اعمال کا دارومدار نیتوں پر ہے اور ہر شخص کو وہی ملے گا جس کی اس نے نیت کی۔",
        "tr": "Ameller niyetlere göredir ve herkes niyet ettiğini bulur."
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

The translation keys are en, ur, fr, de, tr, ms, ru, zh-CN and ja. The sample is small (a couple of items). It is meant for building and testing your UI. Full collections and the production endpoint come with an API key, which you can request from the Hadith API page or the pricing / access page. If you need more books (Abu Dawud, Tirmidhi, Nasai, Ibn Majah and others), see the Hadith Books API.

Because our app code only depends on the shape of the JSON, moving from the sample to the full API later means changing one URL.


2. Project setup

Create a new Empty Activity (Compose) project, then add the dependencies to app/build.gradle.kts:

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
    id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21"
    id("org.jetbrains.kotlin.plugin.compose") version "2.0.21"
}

dependencies {
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
    // ...your usual Compose BOM / material3 dependencies
}
Enter fullscreen mode Exit fullscreen mode

And the permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
Enter fullscreen mode Exit fullscreen mode

3. Model the JSON

ignoreUnknownKeys keeps the app working if new fields are added later.

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class HadithFile(
    val title: String,
    val description: String = "",
    val items: List<Hadith> = emptyList()
)

@Serializable
data class Hadith(
    val id: Int,
    val collection: String,
    val book: Int? = null,
    @SerialName("hadith_number") val hadithNumber: Int,
    val arabic: String,
    val narrator: String = "",
    val translations: Map<String, String> = emptyMap()
) {
    /** Falls back to English if the chosen language is missing. */
    fun text(lang: String): String =
        translations[lang] ?: translations["en"] ?: ""

    /** e.g. "Sahih Bukhari, Book 1, Hadith 1" */
    val reference: String
        get() = buildString {
            append(collection)
            book?.let { append(", Book $it") }
            append(", Hadith $hadithNumber")
        }
}
Enter fullscreen mode Exit fullscreen mode

4. A repository with an offline cache

Strategy: network first, cache second. Every successful download is saved to filesDir. If the network fails, we read the last saved copy. On the very first launch without internet we show a friendly error.

import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.util.concurrent.TimeUnit

class HadithRepository(context: Context) {

    private val url = "https://sunnahsource.org/data/json/hadith.json"
    private val cacheFile = File(context.filesDir, "hadith_cache.json")
    private val json = Json { ignoreUnknownKeys = true }
    private val client = OkHttpClient.Builder()
        .callTimeout(15, TimeUnit.SECONDS)
        .build()

    suspend fun load(): Result<Pair<HadithFile, Boolean>> = withContext(Dispatchers.IO) {
        // 1) Try the network
        runCatching {
            val req = Request.Builder().url(url).build()
            client.newCall(req).execute().use { res ->
                check(res.isSuccessful) { "HTTP ${res.code}" }
                val body = res.body!!.string()
                val parsed = json.decodeFromString<HadithFile>(body) // validate before caching
                cacheFile.writeText(body)
                parsed to false          // false = not from cache
            }
        }.recoverCatching {
            // 2) Fall back to the cached copy
            check(cacheFile.exists()) { "No internet and no cached data yet" }
            json.decodeFromString<HadithFile>(cacheFile.readText()) to true
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Two small details matter here:

  • We parse before writing the cache, so a broken response (a captive-portal HTML page, for example) never replaces good data.
  • We return a Boolean flag so the UI can show a small "offline copy" label.

5. Pick "today's" hadith deterministically

We want every user to see the same hadith on the same day, and it should not change when the screen rotates. Using the day number is enough:

import java.time.LocalDate

fun hadithForToday(items: List<Hadith>, today: LocalDate = LocalDate.now()): Hadith? {
    if (items.isEmpty()) return null
    val index = (today.toEpochDay() % items.size).toInt()
    return items[index]
}
Enter fullscreen mode Exit fullscreen mode

When you switch to the full API with hundreds of hadith, the function does not change.


6. ViewModel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

sealed interface UiState {
    data object Loading : UiState
    data class Ready(val hadith: Hadith, val fromCache: Boolean) : UiState
    data class Error(val message: String) : UiState
}

class HadithViewModel(app: Application) : AndroidViewModel(app) {
    private val repo = HadithRepository(app)

    private val _state = MutableStateFlow<UiState>(UiState.Loading)
    val state = _state.asStateFlow()

    private val _lang = MutableStateFlow("en")
    val lang = _lang.asStateFlow()

    init { refresh() }

    fun setLang(code: String) { _lang.value = code }

    fun refresh() = viewModelScope.launch {
        _state.value = UiState.Loading
        repo.load()
            .onSuccess { (file, cached) ->
                val h = hadithForToday(file.items)
                _state.value = if (h != null) UiState.Ready(h, cached)
                               else UiState.Error("No hadith in the file")
            }
            .onFailure { _state.value = UiState.Error(it.message ?: "Something went wrong") }
    }
}
Enter fullscreen mode Exit fullscreen mode

7. The Compose UI (with real RTL)

Arabic is always right-to-left. Urdu translations are also right-to-left, so we switch LocalLayoutDirection for the translation block depending on the selected language. This flips alignment, punctuation placement and padding correctly instead of just right-aligning the text.

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel

private val languages = listOf(
    "en" to "English", "ur" to "اردو", "fr" to "Français", "de" to "Deutsch",
    "tr" to "Türkçe", "ms" to "Melayu", "ru" to "Русский", "zh-CN" to "中文", "ja" to "日本語"
)
private val rtlLanguages = setOf("ur")

@Composable
fun HadithOfTheDayScreen(vm: HadithViewModel = viewModel()) {
    val state by vm.state.collectAsStateWithLifecycle()
    val lang by vm.lang.collectAsStateWithLifecycle()

    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Text("Hadith of the Day", style = MaterialTheme.typography.headlineSmall)
        Spacer(Modifier.height(8.dp))
        LanguagePicker(selected = lang, onSelect = vm::setLang)
        Spacer(Modifier.height(16.dp))

        when (val s = state) {
            UiState.Loading -> CircularProgressIndicator()
            is UiState.Error -> {
                Text(s.message, color = MaterialTheme.colorScheme.error)
                TextButton(onClick = { vm.refresh() }) { Text("Retry") }
            }
            is UiState.Ready -> HadithCard(s.hadith, lang, s.fromCache)
        }
    }
}

@Composable
private fun HadithCard(h: Hadith, lang: String, fromCache: Boolean) {
    ElevatedCard(Modifier.fillMaxWidth()) {
        Column(Modifier.padding(20.dp)) {
            // Arabic: always RTL
            CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
                Text(
                    h.arabic,
                    fontSize = 26.sp,
                    lineHeight = 44.sp,
                    textAlign = TextAlign.Start,
                    modifier = Modifier.fillMaxWidth()
                )
            }
            Spacer(Modifier.height(12.dp))

            // Translation: RTL only for RTL languages
            val dir = if (lang in rtlLanguages) LayoutDirection.Rtl else LayoutDirection.Ltr
            CompositionLocalProvider(LocalLayoutDirection provides dir) {
                Text(
                    h.text(lang),
                    style = MaterialTheme.typography.bodyLarge,
                    textAlign = TextAlign.Start,
                    modifier = Modifier.fillMaxWidth()
                )
            }
            Spacer(Modifier.height(12.dp))

            // Always show the source with the text
            Text(
                "${h.reference}${if (h.narrator.isNotBlank()) " • Narrated by ${h.narrator}" else ""}",
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            if (fromCache) {
                Spacer(Modifier.height(4.dp))
                Text("Offline copy", style = MaterialTheme.typography.labelSmall)
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun LanguagePicker(selected: String, onSelect: (String) -> Unit) {
    var open by remember { mutableStateOf(false) }
    ExposedDropdownMenuBox(expanded = open, onExpandedChange = { open = it }) {
        OutlinedTextField(
            value = languages.first { it.first == selected }.second,
            onValueChange = {},
            readOnly = true,
            label = { Text("Translation") },
            modifier = Modifier.menuAnchor().fillMaxWidth()
        )
        ExposedDropdownMenu(expanded = open, onDismissRequest = { open = false }) {
            languages.forEach { (code, label) ->
                DropdownMenuItem(text = { Text(label) }, onClick = { onSelect(code); open = false })
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Finally, in MainActivity:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { MaterialTheme { Surface { HadithOfTheDayScreen() } } }
    }
}
Enter fullscreen mode Exit fullscreen mode

Run it, switch to اردو, and the translation block flips to right-to-left, while the reference line stays in place underneath.


8. Test the day-picker without an emulator

Pure functions are easy to unit test:

import org.junit.Assert.assertEquals
import org.junit.Test
import java.time.LocalDate

class HadithForTodayTest {
    private fun h(id: Int) = Hadith(id, "Test", 1, id, "", "", emptyMap())

    @Test fun sameDaySameHadith() {
        val items = listOf(h(1), h(2), h(3))
        val d = LocalDate.of(2026, 11, 20)
        assertEquals(hadithForToday(items, d), hadithForToday(items, d))
    }

    @Test fun rotatesDaily() {
        val items = listOf(h(1), h(2))
        val a = hadithForToday(items, LocalDate.of(2026, 11, 20))
        val b = hadithForToday(items, LocalDate.of(2026, 11, 21))
        assert(a != b)
    }
}
Enter fullscreen mode Exit fullscreen mode

9. Responsible display of religious text

A few habits that users (and scholars reviewing your app) will appreciate:

  1. Always show the reference (collection, book and hadith number, narrator) next to the text. Never show a hadith without it.
  2. Don't machine-translate hadith yourself. Use translations that come with the data source.
  3. Don't truncate the Arabic in a way that changes the meaning. If space is tight, let the card grow or open a detail screen.
  4. Use a font with good Arabic diacritics support. Noto Naskh Arabic is a solid default.

Where to go next

If you build something with this, share it in the comments. JazakAllahu khairan for reading!

Top comments (0)