<?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 Muhammad Rehman on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Rehman on Medium]]></description>
        <link>https://medium.com/@muhammad.rehman_43047?source=rss-252bdfc5046b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hKIEsrdSL25mkV3Cj69Yiw.jpeg</url>
            <title>Stories by Muhammad Rehman on Medium</title>
            <link>https://medium.com/@muhammad.rehman_43047?source=rss-252bdfc5046b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:28:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammad.rehman_43047/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[Mastering Relational Entities in Android Room Database for Exercise Tracking Apps]]></title>
            <link>https://medium.com/@muhammad.rehman_43047/mastering-relational-entities-in-android-room-database-for-exercise-tracking-apps-3e501e1b5e3d?source=rss-252bdfc5046b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e501e1b5e3d</guid>
            <dc:creator><![CDATA[Muhammad Rehman]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 05:14:33 GMT</pubDate>
            <atom:updated>2024-01-31T05:14:33.860Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9cpgOAwa90NdmBFd8eTCQ.png" /></figure><p>In the realm of fitness and wellness, exercise tracking applications play a pivotal role in helping users achieve their fitness goals.</p><p>Behind the scenes of these apps lies a robust data management system, and Android Room Database emerges as a powerful ally.</p><p>This article delves into the intricate world of Room Database, exploring how to harness its capabilities to create a seamless and efficient exercise tracking app with relational entities</p><h3>1. Entities for Exercise Tracking:</h3><p>To build a comprehensive exercise tracking system, defining the entities is the first step.</p><p>In the Android Room Database context, entities represent the tables in the database. Let’s consider three key entities for our exercise tracking app:</p><h3>User Entity:</h3><pre>@Entity(tableName = &quot;users&quot;)<br>data class User(<br>    @PrimaryKey(autoGenerate = true)<br>    val userId: Long = 0,<br>    val userName: String,<br>    val age: Int<br>)</pre><h3>Workout Entity:</h3><pre>@Entity(tableName = &quot;workouts&quot;,<br>    foreignKeys = [ForeignKey(entity = User::class,<br>        parentColumns = [&quot;userId&quot;],<br>        childColumns = [&quot;userId&quot;],<br>        onDelete = CASCADE)])<br>data class Workout(<br>    @PrimaryKey(autoGenerate = true)<br>    val workoutId: Long = 0,<br>    val userId: Long,<br>    val date: Long<br>)</pre><h3>Exercise Entity:</h3><pre>@Entity(tableName = &quot;exercises&quot;,<br>    foreignKeys = [ForeignKey(entity = Workout::class,<br>        parentColumns = [&quot;workoutId&quot;],<br>        childColumns = [&quot;workoutId&quot;],<br>        onDelete = CASCADE)])<br>data class Exercise(<br>    @PrimaryKey(autoGenerate = true)<br>    val exerciseId: Long = 0,<br>    val workoutId: Long,<br>    val exerciseName: String,<br>    val sets: Int,<br>    val reps: Int<br>)</pre><h3>2. Defining Relationships:</h3><p>Building an exercise tracking app involves understanding and leveraging relationships between entities. In our case, we have two fundamental relationships:</p><h3>One-to-Many Relationship:</h3><ul><li>One User can have Many Workouts.</li><li>One Workout can have Many Exercises.</li></ul><h3>Many-to-Many Relationship:</h3><ul><li>Exercises are associated with Workouts.</li></ul><p>These relationships define how data is connected and retrieved from the Room Database, providing a holistic view of a user’s exercise journey.</p><h3>3. Setting Up the Room Database:</h3><p>Before diving into the database setup, ensure you have the necessary dependencies in your build.gradle file:</p><pre>implementation &quot;androidx.room:room-runtime:2.4.0&quot;<br>kapt &quot;androidx.room:room-compiler:2.4.0&quot;</pre><p>Now, let’s set up the Room Database:</p><pre>@Database(entities = [User::class, Workout::class, Exercise::class], version = 1, exportSchema = false)<br>abstract class ExerciseDatabase : RoomDatabase() {<br>    abstract fun userDao(): UserDao<br>    abstract fun workoutDao(): WorkoutDao<br>    abstract fun exerciseDao(): ExerciseDao<br>}</pre><p>This abstract class represents our Room Database and provides access to the DAO (Data Access Object) interfaces. Each DAO interface contains methods for specific database operations.</p><h3>4. Performing Relational Queries:</h3><p>Now, let’s explore how we can perform relational queries with Room Database. This involves inserting and querying data with relationships.</p><h4>Inserting Data with Relationships:</h4><pre>// Insert a user with associated workouts and exercises<br>val userWithWorkoutsAndExercises = UserWithWorkoutsAndExercises(<br>    user = User(userName = &quot;John Doe&quot;, age = 25),<br>    workouts = listOf(<br>        Workout(date = System.currentTimeMillis()),<br>        Workout(date = System.currentTimeMillis() - 86400000) // One day ago<br>    ),<br>    exercises = listOf(<br>        Exercise(exerciseName = &quot;Push-up&quot;, sets = 3, reps = 15),<br>        Exercise(exerciseName = &quot;Squats&quot;, sets = 4, reps = 12)<br>    )<br>)<br>exerciseDatabase.userDao().insertUserWithWorkoutsAndExercises(userWithWorkoutsAndExercises)</pre><h4>Querying Data with Relationships:</h4><pre>// Query all users with associated workouts and exercises<br>val usersWithWorkoutsAndExercises: LiveData&lt;List&lt;UserWithWorkoutsAndExercises&gt;&gt; =<br>    exerciseDatabase.userDao().getAllUsersWithWorkoutsAndExercises()</pre><p>These queries allow us to seamlessly navigate through relational data, providing a rich and coherent dataset for our exercise tracking app.</p><h3>5. LiveData and Room with Relationships:</h3><p>One of the significant advantages of Room Database is its seamless integration with LiveData, enabling real-time updates of database changes.</p><h4>Observing Data Changes:</h4><pre>// Observe changes in user data with associated workouts and exercises<br>usersWithWorkoutsAndExercises.observe(viewLifecycleOwner, Observer { users -&gt;<br>    // Update UI with</pre><h4>Displaying Relational Data in UI:</h4><pre>&lt;!-- Example UI layout to display users with workouts and exercises --&gt;<br>&lt;androidx.recyclerview.widget.RecyclerView<br>    android:id=&quot;@+id/recyclerView&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    app:layoutManager=&quot;androidx.recyclerview.widget.LinearLayoutManager&quot;<br>    app:adapter=&quot;@{exerciseAdapter}&quot; /&gt;</pre><p>LiveData simplifies the UI updates and ensures a smooth user experience by automatically reflecting changes in the underlying database.\</p><h3>6. Migrations for Evolving Entities:</h3><p>As your application evolves, the database schema might need to be updated. Room supports migrations to handle these changes without losing existing data.</p><h4>Adding or Modifying Relationships:</h4><pre>@Database(entities = [User::class, Workout::class, Exercise::class], version = 2, exportSchema = false)<br>abstract class ExerciseDatabase : RoomDatabase() {<br>    abstract fun userDao(): UserDao<br>    abstract fun workoutDao(): WorkoutDao<br>    abstract fun exerciseDao(): ExerciseDao<br>}</pre><h4>Handling Database Migrations:</h4><pre>// Migration from version 1 to 2<br>val MIGRATION_1_2 = object : Migration(1, 2) {<br>    override fun migrate(database: SupportSQLiteDatabase) {<br>        // Perform necessary migration steps<br>    }<br>}<br><br>ExerciseDatabase = Room.databaseBuilder(context, ExerciseDatabase::class.java, &quot;exercise_database&quot;)<br>    .addMigrations(MIGRATION_1_2)<br>    .build()</pre><p>Migrations ensure a smooth transition between different versions of the database schema, allowing for a seamless user experience during updates.</p><h3>7. Advanced Database Operations:</h3><p>Exercise tracking apps often require more advanced database operations. Let’s explore cascading deletions and transaction management.</p><h4>Cascading Deletions:</h4><pre>@Dao<br>interface UserDao {<br>    @Transaction<br>    @Query(&quot;SELECT * FROM users&quot;)<br>    fun getAllUsersWithWorkoutsAndExercises(): LiveData&lt;List&lt;UserWithWorkoutsAndExercises&gt;&gt;<br>    <br>    @Transaction<br>    @Query(&quot;SELECT * FROM users WHERE userId = :userId&quot;)<br>    fun getUserWithWorkoutsAndExercises(userId: Long): LiveData&lt;UserWithWorkoutsAndExercises&gt;<br><br>    @Transaction<br>    @Query(&quot;SELECT * FROM workouts WHERE workoutId = :workoutId&quot;)<br>    fun getWorkoutWithExercises(workoutId: Long): LiveData&lt;WorkoutWithExercises&gt;<br>}</pre><h4>Transaction Management:</h4><pre>@Dao<br>interface ExerciseDao {<br>    @Transaction<br>    @Query(&quot;SELECT * FROM exercises WHERE workoutId = :workoutId&quot;)<br>    fun getExercisesForWorkout(workoutId: Long): List&lt;Exercise&gt;<br><br>    @Transaction<br>    @Query(&quot;SELECT * FROM workouts WHERE date BETWEEN :startDate AND :endDate&quot;)<br>    fun getWorkoutsBetweenDates(startDate: Long, endDate: Long): List&lt;Workout&gt;<br><br>    @Transaction<br>    @Query(&quot;SELECT * FROM exercises WHERE exerciseId IN (:exerciseIds)&quot;)<br>    fun getExercisesByIds(exerciseIds: List&lt;Long&gt;): List&lt;Exercise&gt;<br>}</pre><p>These advanced operations provide flexibility and efficiency in managing complex relationships within the database.</p><h3>8. Testing Room Database with Relationships:</h3><p>Ensuring the reliability and correctness of the database is crucial. Room Database supports both unit testing and instrumented testing.</p><h3>10. Conclusion:</h3><p>In this journey through Android Room Database for exercise tracking apps, we’ve uncovered the intricacies of defining entities, establishing relationships, and performing relational queries.</p><p>Room Database, with its support for LiveData, migrations, and advanced operations, emerges as a powerful tool for building robust and efficient exercise tracking systems.</p><p>As you embark on your own development endeavours, keep these principles in mind, experiment with the provided code snippets, and tailor them to fit the unique requirements of your exercise tracking application.</p><p>The seamless integration of Room Database with relational entities empowers developers to create immersive and feature-rich fitness experiences for users worldwide. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e501e1b5e3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>