<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Raed Ghazal on Medium]]></title>
        <description><![CDATA[Stories by Raed Ghazal on Medium]]></description>
        <link>https://medium.com/@raed-o-ghazal?source=rss-865e573cb577------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Sfsy_LQoDAxKw4Wbdpd78Q.png</url>
            <title>Stories by Raed Ghazal on Medium</title>
            <link>https://medium.com/@raed-o-ghazal?source=rss-865e573cb577------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:40:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raed-o-ghazal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Open System Settings in Compose Multiplatform]]></title>
            <link>https://raed-o-ghazal.medium.com/how-to-open-system-settings-in-compose-multiplatform-9c0545cff3ea?source=rss-865e573cb577------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c0545cff3ea</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[settings]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Raed Ghazal]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 11:24:06 GMT</pubDate>
            <atom:updated>2024-12-06T12:00:02.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqtmZP4_U-433BB2jFAXbw.png" /></figure><p>Sometimes, we need to redirect users from our app to the application system settings — when permission is denied for example, and we can’t request it again. This guide will show you how to implement a solution in Compose Multiplatform (CMP) to easily open the application’s system settings on both Android and iOS.</p><p>Here is how the final result will look like:</p><pre>@Composable<br>fun Foo() {<br>    val settingsState = rememberSettingsController()<br>    Button(<br>        onClick = { settingsState.open() }<br>    ) {<br>        Text(&quot;Open settings&quot;)<br>    }<br>}</pre><p>Let’s get right into writing code:</p><h3>First, we need to set up the SettingsController composable function</h3><h4>1. commonMain implementation:</h4><p>And the SettingsState class that will allow us to easily call open to open the settings instead of handling the boolean state ourselves</p><pre><br>class SettingsState {<br>    internal var open by mutableStateOf(false)<br><br>    fun open() {<br>        open = true<br>    }<br>}<br><br>@Composable<br>internal expect fun SettingsController(state: SettingsState)</pre><h4>2. androidMain actual implementation</h4><p>Once the state changes to true it will recompose triggering the code inside the condition to open the app’s settings, then we set the state to false, so it doesn’t reopen the settings again and again on each recomposition</p><pre>import android.content.Intent<br>import android.net.Uri<br>import android.provider.Settings<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.platform.LocalContext<br>import androidx.core.content.ContextCompat.startActivity<br><br>@Composable<br>actual fun SettingsController(state: SettingsState) {<br>    if (state.open) {<br>        val context = LocalContext.current<br>        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)<br>        val uri: Uri = Uri.fromParts(&quot;package&quot;, context.packageName, null)<br>        intent.data = uri<br>        startActivity(context, intent, null)<br><br>        state.open = false<br>    }<br>}</pre><h4>3. iosMain actual implementation</h4><p>Similar to the android’s explanation above</p><pre>import androidx.compose.runtime.Composable<br>import platform.Foundation.NSURL<br>import platform.UIKit.UIApplication<br>import platform.UIKit.UIApplicationOpenSettingsURLString<br><br>@Composable<br>actual fun SettingsController(state: SettingsState) {<br>    if (state.open) {<br>        val settingsUrl = NSURL.URLWithString(UIApplicationOpenSettingsURLString)<br><br>        if (settingsUrl != null &amp;&amp; UIApplication.sharedApplication.canOpenURL(settingsUrl)) {<br>            UIApplication.sharedApplication.openURL(settingsUrl, emptyMap&lt;Any?,Any&gt;(), {})<br>        }<br><br>        state.open = false<br>    }<br>}</pre><p>Once we are done with the above implementation, we should be ready to test, but to make it even easier to use we can create this helper function</p><pre>@Composable<br>fun rememberSettingsController(): SettingsState {<br>    val settingsState = remember { SettingsState() }<br>    SettingsController(settingsState)<br>    return settingsState<br>}</pre><p>which initiates the state and the controller for us, and returns the state so we can call open from our code directly like this:</p><pre>@Composable<br>fun Foo() {<br>    val settingsState = rememberSettingsController()<br>    Button(<br>        onClick = { settingsState.open() }<br>    ) {<br>        Text(&quot;Open settings&quot;)<br>    }<br>}</pre><p>With this implementation, <strong>you now have a reusable way to open system settings in Compose Multiplatform apps</strong>, ensuring smooth functionality across Android and iOS. Happy coding! 🚀</p><h4>Show support</h4><p>If you enjoyed the article, support me by <strong>leaving some claps 👏,</strong> and if you have any questions please let me know in the comments.</p><p><strong>Follow me for more</strong> 🙌</p><h4>Social media</h4><p><a href="https://www.linkedin.com/in/raed-o-ghazal/">LinkedIn</a>, <a href="https://twitter.com/RaedOGhazal">Twitter</a>, <a href="https://github.com/RaedGhazal">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c0545cff3ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlinx DateTime manipulation for KMP]]></title>
            <link>https://raed-o-ghazal.medium.com/kotlinx-localdatetime-manipulation-for-kmm-eacfede93aba?source=rss-865e573cb577------2</link>
            <guid isPermaLink="false">https://medium.com/p/eacfede93aba</guid>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kmp]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Raed Ghazal]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 11:45:21 GMT</pubDate>
            <atom:updated>2024-09-10T09:08:26.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4-NlOWIpcZW4qlHn" /></figure><p>Working with dates and times in a Kotlin Multiplatform (KMP) can be difficult as we don’t have access to java.time package, which is unfortunate as java.time.LocalDateTime is so powerful and has great support, while moving to kotlinx.datetime.LocalDateTime can feel like a hard task.</p><p>This article will be your full guide to working with and manipulating LocalDateTime , LocalDate , LocalTime from <a href="https://github.com/Kotlin/kotlinx-datetime">kotlinx.datetime</a> library and all the needed functionality, especially if you’re migrating from a project that uses java.time package!</p><h3>✨Update: Here is Some NEW Good News✨</h3><p>I got some feedback on why not create a library that contains all the below functionality and implementation for easier access to anyone interested in having those extension functions instead of each one implementing them on their own.</p><p>So I have created a `kotlinx.datetime` extension library, and there is no need to follow the below guide on how to implement all the functions, just check my <a href="https://github.com/RaedGhazal/kotlinx-datetime-ext">Library GitHub repo</a> and get quick access to all of them and more with zero effort and boilerplate code on your side!</p><p><strong><em>*All the details are mentioned in the repo’s Readme file</em></strong></p><p>→ <a href="https://github.com/RaedGhazal/kotlinx-datetime-ext">https://github.com/RaedGhazal/kotlinx-datetime-ext</a> ←</p><p><em>*You can continue reading if you want to know the details behind the implementation</em></p><h3>Continue to the implementation details that the library was built on</h3><h4>Dependency implementation</h4><p>To start using kotlinx datetime, write the following in (app) build.gradle and in commonMain dependencies if you’re working with KMP</p><pre>implementation(&quot;org.jetbrains.kotlinx:kotlinx-datetime:0.4.1&quot;)</pre><h4>Getting the current date and time</h4><p>To get the current date and time in kotlinx.datetime library it&#39;s not so intuitive as java.time package, where we used to just write LocalDateTime.now() .</p><p>but in Kotlin’s we have to use the system Clock and default TimeZone by writing:</p><p>Clock.System.now().<em>toLocalDateTime</em>(TimeZone.currentSystemDefault())</p><p>and then we can use the getters .date and .time to get the LocalDate and LocalTime instances.</p><p>To make it easier though, we can create some extension functions:</p><pre>import kotlinx.datetime.Clock<br>import kotlinx.datetime.LocalDate<br>import kotlinx.datetime.LocalDateTime<br>import kotlinx.datetime.LocalTime<br>import kotlinx.datetime.toLocalDateTime<br>import kotlinx.datetime.TimeZone</pre><pre>fun LocalDateTime.Companion.now(): LocalDateTime {<br>    return Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())<br>}</pre><pre>fun LocalDate.Companion.now(): LocalDate {<br>    return LocalDateTime.now().date<br>}</pre><pre>fun LocalTime.Companion.now(): LocalTime {<br>    return LocalDateTime.now().time<br>}</pre><p>then by simple writing LocalDateTime.now() , LocalDate.now() and LocalTime.now() we get quick access to now’s date or time object.</p><h4>Tweaks and date-time manipulation</h4><p>When working with date time we often need quick reach to other functions as well, like getting an instance of the minimum time of the day and maximum time of the day, especially when working with ranges, like yesterday .. now in this case, at what time would yesterday be? probably the beginning of the day.</p><p>To create our own extension methods, .min() would be easy, because it would be LocalTime(hours = 0, minutes = 0) but for .max() I had to check what values java.time use, and found this LocalTime(hours = 23, minutes = 59, seconds = 59, nanoseconds = 999999999)</p><p>so we can create those 2 extension functions</p><pre>fun LocalTime.Companion.min(): LocalTime {<br>    return LocalTime(0, 0)<br>}</pre><pre>fun LocalTime.Companion.max(): LocalTime {<br>    return LocalTime(23, 59, 59, 999999999)<br>}</pre><p>and we can use them to convert LocalDate instances to LocalDateTime instances of startOfDay and endOfDay</p><pre>fun LocalDate.atStartOfDay(): LocalDateTime {<br>    return LocalDateTime(this, LocalTime.min())<br>}</pre><pre>fun LocalDate.atEndOfDay(): LocalDateTime {<br>    return LocalDateTime(this, LocalTime.max())<br>}</pre><h4>DateTime addition and subtraction</h4><p>For addition and subtraction, unfortunately, we can’t do it directly from LocalDateTime instance, we have to convert it to Instant, do the calculation, and then convert it back to LocalDateTime, so here are some more extension functions</p><pre>import kotlinx.datetime.DateTimeUnit<br>import kotlinx.datetime.LocalDateTime<br>import kotlinx.datetime.TimeZone<br>import kotlinx.datetime.minus<br>import kotlinx.datetime.plus<br>import kotlinx.datetime.toInstant<br>import kotlinx.datetime.toLocalDateTime</pre><pre>fun LocalDateTime.plus(value: Long, unit: DateTimeUnit.TimeBased): LocalDateTime {<br>    val timeZone = TimeZone.currentSystemDefault()<br>    return this.toInstant(timeZone)<br>        .plus(value, unit)<br>        .toLocalDateTime(timeZone)<br>}</pre><pre>fun LocalDateTime.minus(value: Long, unit: DateTimeUnit.TimeBased): LocalDateTime {<br>    val timeZone = TimeZone.currentSystemDefault()<br>    return this.toInstant(timeZone)<br>        .minus(value, unit)<br>        .toLocalDateTime(timeZone)<br>}</pre><p>here are some examples of usages:</p><pre>val datetime: LocalDateTime = LocalDateTime.now()<br>val dateTimeAfterOneHour: LocalDateTime = datetime.plus(1, DateTimeUnit.HOUR)<br>val dateTimeAfterOneDay: LocalDateTime = datetime.plus(24, DateTimeUnit.HOUR)<br>val dateTime30MinEarlier: LocalDateTime = datetime.minus(30, DateTimeUnit.MINUTE)</pre><h4>Working with YearMonth</h4><p>YearMonth class existed in java.time but there is no alternative in kotlinx.datetime and sometimes it&#39;s useful when we want to point out a month of a specific year and have some helper functions, like:</p><pre>val yearMonth = YearMonth(2023, Month.APRIL)</pre><pre>val fifthOfMonth: LocalDateTime = yearMonth.atDay(5) // 2023/04/05</pre><pre>//since it&#39;s not easy to know how many days this month holds, <br>// it&#39;s nice to have a function that figures that out for you<br>val endOfMonth: LocalDateTime = yearMonth.atEndOfMonth() </pre><pre>// those are useful when working with ranges.<br>val twoMonthsEarlier: YearMonth = yearMonth.plusMonths(2)<br>val sevenMonthsForward: YearMonth = yearMonth.minusMonths(7)</pre><pre>//sample usage<br>val range = twoMonthsEarlier.atDay(0) .. sevenMonthsForward.atEndOfMonth()</pre><p>For that, we can create our own YearMonth class that’s pure Kotlin with similar functions to java.time’s</p><pre>import kotlinx.datetime.LocalDate<br>import kotlinx.datetime.Month<br>import kotlinx.datetime.number</pre><pre>data class YearMonth(val year: Int, val month: Month) {<br>    fun atDay(day: Int): LocalDate {<br>        return LocalDate(year, month, day)<br>    }</pre><pre>    fun atEndOfMonth(): LocalDate {<br>        val lastDay = month.number.monthLength(isLeapYear(year))<br>        return LocalDate(year, month, lastDay)<br>    }</pre><pre>    fun plusMonths(months: Int): YearMonth {<br>        val newMonth = month.number + months<br>        val newYear = year + (newMonth - 1) / 12<br>        val newMonthNumber = (newMonth - 1) % 12 + 1<br>        return YearMonth(newYear, newMonthNumber.toMonth())<br>    }</pre><pre>    fun minusMonths(months: Int): YearMonth {<br>        val totalMonths = year * 12 + (month.number - 1) - months<br>        val newYear = totalMonths / 12<br>        val newMonth = (totalMonths % 12) + 1 // Adding 1 because months are 1-based</pre><pre>        return YearMonth(newYear, newMonth.toMonth())<br>    }</pre><pre>    private fun Int.toMonth(): Month {<br>        return Month.values()[this - 1]<br>    }</pre><pre>    // the below 2 functions were taken from `java.time` package<br>    private fun isLeapYear(year: Int): Boolean {<br>        val prolepticYear: Long = year.toLong()<br>        return prolepticYear and 3 == 0L &amp;&amp; (prolepticYear % 100 != 0L || prolepticYear % 400 == 0L)<br>    }</pre><pre>    private fun Int.monthLength(isLeapYear: Boolean): Int {<br>        return when (this) {<br>            2 -&gt; if (isLeapYear) 29 else 28<br>            4, 6, 9, 11 -&gt; 30<br>            else -&gt; 31<br>        }<br>    }</pre><pre>    companion object {<br>        fun from(localDate: LocalDate): YearMonth {<br>            return YearMonth(localDate.year, localDate.month)<br>        }<br>    }<br>}</pre><h3>Formatting and Parsing</h3><p>Formatting and parsing don’t come out of the box with kotlinx.datetime library and we have to use platform-specific code for each platform to format and parse the dates we work with.</p><h4>Formatting LocalDateTime to string</h4><p>To format on the Android side:</p><pre>import kotlinx.datetime.LocalDateTime<br>import kotlinx.datetime.toJavaLocalDateTime<br>import java.time.format.DateTimeFormatter<br>import java.util.Locale</pre><pre>actual fun format(localDateTime: LocalDateTime): String {<br>  val str = DateTimeFormatter<br>      .ofPattern(&quot;dd/MM/yyyy - HH:mm&quot;, Locale.getDefault())<br>      .format(localDateTime.toJavaLocalDateTime())<br>}</pre><pre>// usage<br>val localDateTime = LocalDateTime(2023, 10, 7, 13, 10)<br>print(format(localDateTime))<br>// output: 07/10/2023 - 13:10</pre><blockquote>this code can’t be used in <em>commonMain</em> because it uses java <em>DateTimeFormatter</em> and <em>Locale</em></blockquote><p>However, on iOS it is a bit more difficult:</p><p>we have to first convert LocalDateTime to objective-c NSDate</p><pre>private fun LocalDateTime.toNsDate(): NSDate? {<br>    val calendar = NSCalendar.currentCalendar<br>    val components = NSDateComponents()<br>    components.year = this.year.convert()<br>    components.month = this.monthNumber.convert()<br>    components.day = this.dayOfMonth.convert()<br>    components.hour = this.hour.convert()<br>    components.minute = this.minute.convert()<br>    components.second = this.second.convert()<br>    return calendar.dateFromComponents(components)<br>}<br></pre><pre>actual fun format(localDateTime: LocalDateTime): String {<br>    val date = localDateTime.toNsDate() ?: throw IllegalStateException(&quot;Failed to convert LocalDateTime $LocalDateTime to NSDate&quot;)<br>    ...<br>}</pre><p>then create a NSDateFormatter with the specific pattern and locale</p><pre>actual fun format(localDateTime: LocalDateTime): String {<br>    val date = localDateTime.toNsDate() ?: throw IllegalStateException(&quot;Failed to convert LocalDateTime $LocalDateTime to NSDate&quot;)<br>    val formatter = NSDateFormatter().apply {<br>        dateFormat = &quot;dd/MM/yyyy - HH:mm&quot;<br>        locale = NSLocale.currentLocale<br>    } // &lt;-<br>    ...<br>}</pre><p>and then using .stringFromDate(date) to format the date</p><pre>actual fun format(localDateTime: LocalDateTime): String {<br>    val date = localDateTime.toNsDate() ?: throw IllegalStateException(&quot;Failed to convert LocalDateTime $LocalDateTime to NSDate&quot;)<br>    val formatter = NSDateFormatter().apply {<br>        dateFormat = pattern<br>        locale = NSLocale.currentLocale<br>    }<br>    return formatter.stringFromDate(date) // &lt;-<br>}</pre><h4>Parsing String to LocalDateTime</h4><p>Here we also have different implementations for Android and iOS modules.</p><p>on Android:</p><pre>actual fun parse(strDateTime: String): LocalDateTime {<br>    val formatter = DateTimeFormatter.ofPattern(&quot;dd/MM/yyyy - HH:mm&quot;, Locale.getDefault())<br>    return java.time.LocalDateTime<br>        .parse(strDateTime, formatter)<br>        .toKotlinLocalDateTime()<br>}</pre><p>on iOS:</p><pre>actual fun parse(str: String): LocalDateTime {<br>    val formatter = NSDateFormatter().apply {<br>        dateFormat = &quot;dd/MM/yyyy - HH:mm&quot;<br>        locale = NSLocale.currentLocale<br>    }<br>    return formatter<br>        .dateFromString(str)<br>        // extensions functions provided by kotlinx.datetime<br>        ?.toKotlinInstant()<br>        ?.toLocalDateTime(TimeZone.currentSystemDefault())<br>        ?: throw IllegalStateException(&quot;Failed to convert String $str to LocalDateTime&quot;)<br>}</pre><p>And that’s it, you are all good to go from here.</p><p>let me know in the comments if something is missing or if you’re struggling with other functionalities!</p><h3>Show support</h3><p>If you enjoyed the article, support me by <strong>leaving some claps (50 :) ),</strong> and <strong>follow me on Medium and social media 🙌</strong></p><h3>Social media</h3><p><a href="https://www.linkedin.com/in/raed-o-ghazal/">LinkedIn</a>, <a href="https://twitter.com/RaedOGhazal">Twitter</a>, <a href="https://github.com/RaedGhazal">GitHub</a></p><h3>References:</h3><ol><li><a href="https://github.com/Kotlin/kotlinx-datetime">https://github.com/Kotlin/kotlinx-datetime</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eacfede93aba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrate your Production app from Room DB to SQLDelight]]></title>
            <link>https://raed-o-ghazal.medium.com/migrate-your-production-app-from-room-db-to-sqldelight-c99127bbdc8?source=rss-865e573cb577------2</link>
            <guid isPermaLink="false">https://medium.com/p/c99127bbdc8</guid>
            <category><![CDATA[roomdb]]></category>
            <category><![CDATA[sqldelight]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kmm]]></category>
            <category><![CDATA[kmp]]></category>
            <dc:creator><![CDATA[Raed Ghazal]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 09:18:14 GMT</pubDate>
            <atom:updated>2023-09-20T18:16:32.876Z</atom:updated>
            <content:encoded><![CDATA[<h3>Migrate your Production app from Room to SQLDelight</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*cyN-PGgGPfWLYP10ao-5uA.png" /></figure><p>Kotlin multiplatform (KMP), previously known as (KMM), is an interesting topic for many Android developers looking forward to making their Android app run on other platforms like iOS.</p><p>But one of the first issues they encounter is the popular libraries that are used in almost every Android application that turns out to not support KMP, which have to be replaced with pure kotlin libraries to be able to start your KMP journey, one of those libraries is <strong>Room</strong> which is used to easily manage your local database.</p><p>So in this case, your only option is to migrate to another pure kotlin library, and one of the good options out there is <a href="https://cashapp.github.io/sqldelight/2.0.0/">SQLDelight</a>.</p><p>This Blog is your guide to migrating a production app with a real local database from Room to SQLDelight without losing the saved data.</p><p>Coming from a real experience of doing so in my open source project <a href="https://github.com/Prayer-Companion/PrayerCompanionAndroid">Prayer Companion</a></p><h3>1. Implement SQLDelight</h3><p>First, you should implement SQLDelight dependencies into your project.</p><p>In your app build.gradle.kts add these lines<br><em>refer to </em><a href="https://cashapp.github.io/sqldelight/2.0.0/android_sqlite/"><em>SQLDelight documentation</em></a><em> for the correct versions</em></p><pre>plugins {<br>  id(&quot;app.cash.sqldelight&quot;) version &quot;2.0.0&quot;<br>}<br><br>dependencies {<br>  implementation(&quot;app.cash.sqldelight:android-driver:2.0.0&quot;)<br>  implementation(&quot;app.cash.sqldelight:coroutines-extensions:2.0.0&quot;)<br>}</pre><p>Then sync the project, and under dependencies add the following code to initiate the Database class, the database name can be any name you find suitable, this will be the name of the generated class that you will interact with in your code, and then your app package name</p><p><em>Note: </em><em>name is not the name of the database file, this will be set later</em></p><pre>sqldelight {<br>    databases {<br>        create(&quot;MyAppDatabase&quot;) {<br>            packageName.set(&quot;com.domain.app&quot;)<br>        }<br>    }<br>}</pre><p>The package name can be found in the same grade file as the value of applicationId in the defaultConfig block</p><h3>2. Create your tables</h3><p>SQLDelight uses a different way of creating tables than Room, instead of creating an Entity class and the table is autogenerated, here you have to write the SQL code yourself, <strong>but it&#39;s simple and you get auto-complete.</strong></p><p>Luckily coming from Room makes it easier, we already have the tables creation schema generated somewhere, to find it, search in your project <strong><em>double shift³ </em></strong>for a class named [your database class name]_Impl.java the database class name is the class that inherits RoomDatabase() in your project.</p><p>You will have to build your project first to see the generated class, and it will be under java (generated) directory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*4d9XtVr3qnBD_Ic6wmGnsg.png" /></figure><p>opening the generated class you’ll find all the table creation schemas!<br>In my case here is what I see for my project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJD9YIn2HUATJonWr5kgMw.png" /><figcaption>Room Database tables creation schemas</figcaption></figure><p>Make sure to write the schemas in SQLDelight exactly as they are in Room, otherwise, you’ll most likely get errors.</p><p>Now to write the creation schemas for SQLDelight, open the project view, then under app -&gt; src -&gt; maincreate a new directory called sqldelight and then a directory inside called tables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*9MrBWIBfrKwsXFCXbW-zkQ.png" /></figure><p>In tables directory create a new file for each table with .sq extension.</p><p>The file will be for the table creation and the queries of that table example of a file name my_table.sq, the file will look something like this:</p><pre>CREATE TABLE PrayersInfo (<br>    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,<br>    prayer TEXT NOT NULL,<br>    dateTime TEXT NOT NULL,<br>    status TEXT<br>);<br><br>insert:<br>INSERT INTO PrayersInfo VALUES(:id,:prayer,:dateTime,:status);<br><br>getPrayers:<br>SELECT * FROM PrayersInfo WHERE dateTime &gt;= :startDateTime <br>AND dateTime &lt;= :endDateTime;<br><br>getPrayer:<br>SELECT * FROM PrayersInfo WHERE prayer = :prayer <br>AND dateTime &gt;= :startOfDay AND dateTime &lt;= :endOfDay;<br><br>getPrayersStatusesByDate:<br>SELECT status FROM PrayersInfo WHERE dateTime &gt;= :startDateTime <br>AND dateTime &lt;= :endDateTime AND prayer != :excludedPrayer;<br><br>updatePrayerStatus:<br>UPDATE PrayersInfo SET status = :status WHERE dateTime &gt;= :startOfDay <br>AND dateTime &lt;= :endOfDay AND prayer = :prayer;<br><br>delete:<br>DELETE FROM PrayersInfo WHERE dateTime &gt;= :startDateTime <br>AND dateTime &lt;= :endDateTime;</pre><ol><li>Table creation schema<br><em>Will only run once, you don’t need to worry about that</em></li><li>all your queries, <strong>in the below form</strong><em><br>- Note: keywords are all caps, </em><em>from won’t be recognized, it has to be written as </em><em>FROM <br>- Note2: SQLDelight will generate kotlin functions to use in your project for all these queries</em></li></ol><pre>functionName:<br>Query;</pre><p>Then build the project and you should be good to start replacing room usage.</p><h4>2.1. Before replacing Room</h4><p>if you’re working on a production app, you’re probably in a version number more than 1 now.</p><p>in SQLDelight, we don’t specify the version number like in Room,</p><p>SQLDelight generates the version number based on how many migration files there are + 1</p><p>To work that out, in the same sqldelight directory that we created above, create a new directory called migrations and create a file for each version that you’ve migrated from, in the following naming form</p><pre>[version your migrating from].sqm</pre><p>So if you are on version 3, you have to create 2 migration files 1.sqm and 2.sqmand SQLDelight will understand that you’re on version 3 now.</p><p>Make sure to write your migration statements in those files, similar to how manual migration worked with Room, except if you used AutoMigration in Room, then you will have to write that out as well</p><p>Refer to <a href="https://cashapp.github.io/sqldelight/2.0.0/android_sqlite/migrations/">SQLDelight documentation</a> if you had difficulties writing the migration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*bTva4ZM8F2avW1QCvoLjPw.png" /></figure><p>In my case, I created a new table when I migrated to version 2, so this is how 1.sqm was for me</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*9GcgfuuoS3HvEIN9dDYw2g.png" /></figure><h3>3. Replace Database initialization</h3><p>Find the place where you build your room databaseBuilder and replace it with SQLDelight, make sure to implement the Database class from the generated files (the Database class name will be the same name you wrote in build.gradle.kts file), not your old Room Database one</p><p><strong><em>IMPORTANT: use the same exact database name (in quotation e.g. “prayer-companion”) as this is your database file name, otherwise SQLDelight will create a new one with empty data.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*0ITEgU6UyyoQbRKoojucdw.png" /></figure><pre>val driver: SqlDriver = AndroidSqliteDriver(PrayerCompanionDatabase.Schema, applicationContext, &quot;prayer-companion&quot;)<br>return PrayerCompanionDatabase(driver)</pre><p>Then delete your RoomDatabase class, you don’t need this anymore.</p><h4>3.1. Migrate the Dao interface</h4><p>for me, I wanted to keep everything in the project the same, so instead of replacing the interface with a class, I just created a new Dao class inheriting from my Dao interface</p><p>So for this Dao @Dao interface PrayersInfoDao I created a new class class PrayersInfoDaoImpl: PrayersInfo then I generate all the functions exactly as they are in the interface</p><p>in the constructor, you can inject/pass the generated Database class</p><pre>class PrayersInfoDaoImpl @Inject constructor(<br>    db: PrayerCompanionDatabase<br>) : PrayersInfoDao { ... }</pre><p>then get a reference for the table queries which is generated for you by SQLDelight</p><pre>class PrayersInfoDaoImpl @Inject constructor(<br>    db: PrayerCompanionDatabase<br>) : PrayersInfoDao { <br><br>    private val queries = db.prayersInfoQueries<br>}</pre><p>then using queries is simple, the queries you wrote in .sq file are now ready to be used, to insert a row for example you will write something like this</p><pre><br>override fun insert(prayerInfo: PrayerInfoEntity) {<br>    queries.insert(<br>        id = null,<br>        prayer = prayerInfo.prayer.name,<br>        dateTime = converters.localDateToString(prayerInfo.dateTime),<br>        status = prayerInfo.status.name<br>    )<br>}</pre><p><em>Note: id is null so we can let SQLDelight do the auto-incrementing</em></p><p>But, there are some complications when working with queries</p><h4>a. Reading rows</h4><p>reading rows might not be intuitive, in the below case, calling getPrayers</p><pre><br>override fun getPrayers(<br>    startDateTime: LocalDateTime,<br>    endDateTime: LocalDateTime<br>): List&lt;PrayerInfoEntity&gt; {<br>    return queries.getPrayers(<br>        startDateTime = converters.localDateToString(startDateTime),<br>        endDateTime = converters.localDateToString(endDateTime)<br>    )<br>}</pre><p>will return a Query&lt;PrayersInfo&gt; while the expected result is a List&lt;PrayerInfoEntity&gt;, to first map the data class to my entity class, there are 2 query functions for each query, one like the above with only the needed parameters, and one with an extra mapper function parameter which you can use to map the data class to your entity class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RViwOGTUOnun1ZGeG9qv6Q.png" /></figure><p><em>*I always prefer not to use generated data classes as it becomes harder to change things in the future or add any helper functions</em></p><p>Using the second function will look something like this: <br>a normal mapper function to your preferred data class</p><pre>override fun getPrayers(<br>    startDateTime: LocalDateTime,<br>    endDateTime: LocalDateTime<br>): List&lt;PrayerInfoEntity&gt; {<br>    return queries.getPrayers(<br>        startDateTime = converters.localDateToString(startDateTime),<br>        endDateTime = converters.localDateToString(endDateTime)<br>    ) { id, prayer, dateTime, status -&gt;<br>        // mapping PrayersInfo to PrayerInfoEntity<br>        PrayerInfoEntity(<br>            id = id.toInt(),<br>            prayer = Prayer.valueOf(prayer),<br>            dateTime = converters.stringToLocalDate(dateTime),<br>            status = status?.let { status -&gt; PrayerStatus.valueOf(status) }<br>                ?: PrayerStatus.None<br>        )<br>    }<br>}</pre><p>And to turn Query&lt;T&gt; into a List&lt;T&gt; we call .executeAsList()</p><pre><br>override fun getPrayers(<br>    startDateTime: LocalDateTime,<br>    endDateTime: LocalDateTime<br>): List&lt;PrayerInfoEntity&gt; {<br>    return queries.getPrayers(<br>        startDateTime = converters.localDateToString(startDateTime),<br>        endDateTime = converters.localDateToString(endDateTime)<br>    ) { id, prayer, dateTime, status -&gt;<br>        PrayerInfoEntity(<br>            id = id.toInt(),<br>            prayer = Prayer.valueOf(prayer),<br>            dateTime = converters.stringToLocalDate(dateTime),<br>            status = status?.let { status -&gt; PrayerStatus.valueOf(status) }<br>                ?: PrayerStatus.None<br>        )<br>    }.executeAsList()<br>    // transforming Query into List 👆<br>}</pre><h4>b. Read rows as Flow</h4><p>To read rows from a table as flow make sure you’ve implemented the SQLDelight coroutines extensions dependency</p><pre>implementation(&quot;app.cash.sqldelight:coroutines-extensions:2.0.0&quot;)</pre><p>then instead of calling executeAsList we call asFlow() and then mapToList(DispatcherContext)</p><pre>override fun getPrayersFlow(<br>    startDateTime: LocalDateTime,<br>    endDateTime: LocalDateTime<br>): Flow&lt;List&lt;PrayerInfoEntity&gt;&gt; {<br>    return queries.getPrayers(<br>        startDateTime = converters.localDateToString(startDateTime),<br>        endDateTime = converters.localDateToString(endDateTime)<br>    ) { id, prayer, dateTime, status -&gt;<br>        PrayerInfoEntity(<br>            id = id.toInt(),<br>            prayer = Prayer.valueOf(prayer),<br>            dateTime = converters.stringToLocalDate(dateTime),<br>            status = status?.let { PrayerStatus.valueOf(it) } ?: PrayerStatus.None<br>        )<br>    }.asFlow().mapToList(Dispatchers.IO)<br>    // transform into a flow list 👆<br>}</pre><h4>c. Insert a list</h4><p>we usually have an insertAll function to insert multiple rows at once, unfortunately, SQLDelight doesn’t support that out of the box, so we have to handle it ourselves.</p><p>In this case, we use a queries.transaction { } to insert all the rows or none in case of an error, which will look something like this:</p><pre>override fun insertAll(prayersInfo: List&lt;PrayerInfoEntity&gt;) {<br>    queries.transaction {<br>        prayersInfo.forEach {<br>            queries.insert(<br>                id = null,<br>                prayer = it.prayer.name,<br>                dateTime = converters.localDateToString(it.dateTime),<br>                status = it.status.name<br>            )<br>        }<br>    }<br>}</pre><p>And if you want to be informed about an error, you can add this lin</p><pre>override fun insertAll(prayersInfo: List&lt;PrayerInfoEntity&gt;) {<br>    queries.transaction {<br>        // if the transaction failed and rolled back, throw an exception<br>        afterRollback { throw Exception(&quot;Failed to inserting prayers info &quot;) }<br>        prayersInfo.forEach {<br>            queries.insert(<br>                id = null,<br>                prayer = it.prayer.name,<br>                dateTime = converters.localDateToString(it.dateTime),<br>                status = it.status.name<br>            )<br>        }<br>    }<br>}</pre><p>Then all you have to do is</p><ol><li>Remove all Room Annotations from your Dao interfaces</li><li>Remove all Room Annotations from your Entities data classes</li><li>Remove all Room dependencies from your gradle.build.kts files</li><li>inject/pass the new class [Dao]Impl to the repository that used to use the Dao interface, and everything should work exactly the same.</li></ol><p>Run the app and make sure that all your data is preserved!</p><p>For the full code of the real app migration, here is a link to my PrayerCompanion² project <a href="https://github.com/Prayer-Companion/PrayerCompanionAndroid/pull/25/files">PullRequest of migrating from Room to SQLDelight</a></p><h4>Show support</h4><p>If you enjoyed the article, support me by <strong>leaving some claps,</strong> and if you have any questions please let me know in the comments.</p><p><strong>Follow me for more</strong> 🙌</p><h4>Social media</h4><p><a href="https://www.linkedin.com/in/raed-o-ghazal/">LinkedIn</a>, <a href="https://twitter.com/RaedOGhazal">Twitter</a>, <a href="https://github.com/RaedGhazal">GitHub</a></p><p>References:</p><p>[1] SQLDelight<br><a href="https://cashapp.github.io/sqldelight/2.0.0/">https://cashapp.github.io/sqldelight/2.0.0/</a></p><p>[2] Prayer Companion project on GitHub<br><a href="https://github.com/Prayer-Companion/PrayerCompanionAndroid/pull/25/files">https://github.com/Prayer-Companion/PrayerCompanionAndroid/pull/25/files</a></p><p>[3] Double shift to open “Search everywhere”<br><a href="https://www.jetbrains.com/help/idea/searching-everywhere.html">https://www.jetbrains.com/help/idea/searching-everywhere.html</a></p><p>[4] SQLDelight Migration documentation<br><a href="https://cashapp.github.io/sqldelight/2.0.0/android_sqlite/migrations/">https://cashapp.github.io/sqldelight/2.0.0/android_sqlite/migrations/</a></p><p>[5] A great video from <a href="https://www.youtube.com/@PhilippLackner">Philipp Lackner</a> about SQLDelight<br><a href="https://youtu.be/a2JbtyMPMH0?si=rvzIcIk19d1pLfj_">https://youtu.be/a2JbtyMPMH0?si=rvzIcIk19d1pLfj_</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c99127bbdc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android — Volume keys as Camera Trigger with Kotlin]]></title>
            <link>https://medium.com/jodel-engineering/android-volume-keys-as-camera-trigger-with-kotlin-e75d20838706?source=rss-865e573cb577------2</link>
            <guid isPermaLink="false">https://medium.com/p/e75d20838706</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[câmera]]></category>
            <category><![CDATA[volume-buttons]]></category>
            <category><![CDATA[volume-keys]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Raed Ghazal]]></dc:creator>
            <pubDate>Mon, 23 Aug 2021 22:18:19 GMT</pubDate>
            <atom:updated>2022-08-02T06:28:11.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpxH6tsvGvXwH451r7ZxZg.jpeg" /></figure><h3>Android — How do we use volume keys as Camera Trigger At Jodel</h3><p>Something we see as the default behavior in most apps but wonder how to implement in ours!</p><p>We probably have a button in our app to take a picture, or a video, but ever wondered how can you use the phone volume keys to take pictures and videos without touching the phone screen? that&#39;s what we are going to learn today.</p><h4>1. Why Use the Volume Button</h4><p>well, it&#39;s a better UX, because sometimes you need to take a picture but you have something on your hands and don’t want to touch the screen, so we always try to provide our users with the best experience ever, right?</p><p>It might be obvious for some people, but we can share our experience so others don’t have to suffer thinking of it and trying to fix all the bugs...</p><h4>So, let&#39;s start</h4><p>this Blog is using Kotlin language, but We are not going to share here how to implement the camera and take a picture or a video, but only, how to implement the feature of using volume keys as a trigger in your app.</p><p><strong>First</strong>, in your Activity class, we need to override the method <em>dispatchKeyEvent</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afb7702a7282243a1da9075ab9eed0c4/href">https://medium.com/media/afb7702a7282243a1da9075ab9eed0c4/href</a></iframe><p>This function is called whenever a user performs an event on any key (e.g., the volume keys).<br>the KeyEvent contains 2 primary attributes which we are going to use, KeyEvent.keyCode that represent which key the action was performed on, and KeyEvent.action represent the action made.<br>Also, we have super.dispatchKeyEvent(event), calling it performs the default functionality of the key dispatched, e.g. volume keys increase or decrease the volume.<br>So what we want to do is block this default action and perform our own.</p><p>Now we need to check the keyCode to match our desired keys (Volume keys)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae99bd8b3cb26fb5561a686d9f7fb96c/href">https://medium.com/media/ae99bd8b3cb26fb5561a686d9f7fb96c/href</a></iframe><p>This way, we hold our desired keys functionality, and if the key wasn’t our key, then it ignores the code and returns super.dispatchKeyEvent(event) to perform its default functionality.<br>Now that we have our keys, what&#39;s next?<br>we have 2 actions that we care about, KeyEvent.ACTION_DOWN and KeyEvent.ACTION_UP</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1b1cefad4c0d202af52987891ec6378/href">https://medium.com/media/a1b1cefad4c0d202af52987891ec6378/href</a></iframe><p><strong>Let&#39;s start with video recording functionality</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4c24a89aa360cc614bad70d450e28b8/href">https://medium.com/media/a4c24a89aa360cc614bad70d450e28b8/href</a></iframe><p>Oh, that&#39;s a big change!</p><p>well, don’t worry, we will walk you through it all!<br>So, recording means we will press the volume key down and keep it pressed for an amount of time (long press) to start recording and keep recording until unpressing it.</p><p>So we define a handler to handle our Handler#postDelayedcalls.</p><p>and a runnable to be executed once we say, a long press has been performed.</p><p>now on KeyEvent.<em>ACTION_DOWN </em>we call handler.postDelayed and pass our runnable to be called after a reasonable amount of time, which to us it was 300 milliseconds (can be configured).</p><p>next on KeyEvent.<em>ACTION_UP, </em>we need to check, if a long press was performed (our 300ms have been passed) and the video already started recording, we need to stop recording and with that, you successfully have a video done using the volume keys!<br>else if the video didn’t start recording, means it was a short press, then we need to remove the callbacks and cancel the video recording runnable.</p><p>now that everything is clear, what&#39;s the need for the condition next to KeyEvent.<em>ACTION_DOWN </em>which is isCameraRecording <strong>🤔</strong>?<br>Remember we have 2 volume buttons right? now if a video is recording, we don’t need to perform another call for the video to start recording again, this will cause issues that we are good without.</p><p><strong>Now</strong> let&#39;s complete to the part of taking pictures, this one is simple, we simply call takePicture() on KeyEvent.<em>ACTION_UP </em>if a video wasn’t recording, which means a short press.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63f41242299e494e923e099bf44ad212/href">https://medium.com/media/63f41242299e494e923e099bf44ad212/href</a></iframe><p>Great! we are done !!</p><p>but, don’t get excited, one more small thing to add..!<br>remember what We said earlier? we have 2 volume buttons, we handled it on KeyEvent.<em>ACTION_DOWN, and </em>now we need to handle it on KeyEvent.<em>ACTION_UP.<br></em>after performing the KeyEvent.ACTION_UP we need to block the keys for a small amount of time, so no overlapping happens, e.g. long click on both buttons, then unpress them both at the same time, this will call KeyEvent.ACTION_UP twice, first one will stop the video “good :)” second one will take a picture “not good :(”.</p><p>So to disable the keys for a time we need to have a variable isVolumeKeysDisabled</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68e9e96f4b748931794dc8e3126602da/href">https://medium.com/media/68e9e96f4b748931794dc8e3126602da/href</a></iframe><p>So on KeyEvent.<em>ACTION_UP, </em>we set the isVolumeKeysDisabled = true and call a handler.postDelayed runnable to turn them back to false isVolumeKeysDisabled = false after an amount of time, we used 400ms here, which after using seemed to be reasonable (can be configured).</p><p>and before doing anything on the volume keys action, we check, if isVolumeKeysDisabled is true, we ignore the call, if it’s false, we proceed.</p><h3>And you’re ALL GOOD now !! 🎉</h3><p>hopefully, I did good with explaining everything and introduced the best approach to implementing this feature.</p><p>please don&#39;t hesitate to leave a question if anything is not clear, or you think there is something wrong or buggy in the code, I’ll be happy to edit it!</p><p>and don’t forget to leave some feedback down in the comments 😃</p><p>— — — — — — — — — — — — — — —</p><p>my GitHub: <a href="https://github.com/RaedGhazal">https://github.com/RaedGhazal</a><br>my LinkedIn account: <a href="https://www.linkedin.com/in/raed-o-ghazal/">https://www.linkedin.com/in/raed-o-ghazal/</a> (drop me a connection request, will be happy to know you!)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e75d20838706" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jodel-engineering/android-volume-keys-as-camera-trigger-with-kotlin-e75d20838706">Android — Volume keys as Camera Trigger with Kotlin</a> was originally published in <a href="https://medium.com/jodel-engineering">jodel-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>