<?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 Anumshafiq on Medium]]></title>
        <description><![CDATA[Stories by Anumshafiq on Medium]]></description>
        <link>https://medium.com/@anumshafiq89?source=rss-b70ab753f24f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gTGlX_LyYriM2poH</url>
            <title>Stories by Anumshafiq on Medium</title>
            <link>https://medium.com/@anumshafiq89?source=rss-b70ab753f24f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 07:37:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anumshafiq89/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[Text Styling in Jetpack Compose]]></title>
            <link>https://medium.com/@anumshafiq89/text-styling-in-jetpack-compose-41942164c729?source=rss-b70ab753f24f------2</link>
            <guid isPermaLink="false">https://medium.com/p/41942164c729</guid>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[text-styles]]></category>
            <dc:creator><![CDATA[Anumshafiq]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 08:39:33 GMT</pubDate>
            <atom:updated>2024-07-04T08:39:33.806Z</atom:updated>
            <content:encoded><![CDATA[<p>Jetpack Compose is a powerful toolkit for building native UI in Android. One of the essential aspects of UI design is typography, which plays a critical role in the user experience by ensuring text is readable and visually appealing with generic use throughout the app. This article discusses how to define custom typography using the Jetpack Compose framework, focusing on creating a set of text styles for a fictional app.</p><h4>Defining Font Families</h4><p>First, we start by defining custom font families. A font family groups different font styles (e.g., regular, bold, italic) of the same typeface. In this example, we have two custom font families: bw_modica_hairline and open_sans_light.</p><pre>private val bw_modica_hairline = FontFamily(<br>    Font(R.font.bw_modelica_hairline)<br>)<br><br>private val open_sans_light = FontFamily(<br>    Font(R.font.open_sans_light)<br>)</pre><p>The FontFamily class is used to specify a font family and the Font function links to the actual font resources in the res/font directory.</p><h4>Creating the AppTypography Data Class</h4><p>Next, we define a data class named AppTypography to hold various text styles used throughout the application. Each TextStyle defines the appearance of text, including properties like fontFamily, color, and fontWeight.</p><pre>data class AppTypography(<br>    val textBlackBold: TextStyle = TextStyle(<br>        fontFamily = bw_modica_hairline,<br>        color = Color.Black,<br>        fontWeight = FontWeight.ExtraBold<br>    ),<br>//.....<br>  <br> val textBlackLight: TextStyle = TextStyle(<br>        fontFamily = open_sans_light,<br>        fontWeight = FontWeight.Bold,<br>        color = Color.Gray<br>    )<br>)</pre><p>In this class, we have defined several text styles, each serving a different purpose within the app. For instance, textBlackBold uses the bw_modica_hairline font family, with extra bold weight and black color, while textGreyLight uses the open_sans_light font family, bold weight, and grey color. You can define the color directly as Color. Black or you can use a hex code for any specific color. (i.e. Color.0xFF258585)</p><h4>Providing the Typography</h4><p>To make these text styles accessible throughout the application, we use staticCompositionLocalOf to create a local composition for AppTypography. This allows us to provide a default typography set that can be overridden when required.</p><pre>internal val LocalTypography = staticCompositionLocalOf { AppTypography() }<br><br>//Use of localTypography in composable screen<br>@Composable<br>Text(<br>  text = &quot;Test Text&quot;,<br>  style = LocalTypography.current.textBlackBold.copy(<br>  color = colorResource(id = R.color.semi_bold_gray)),<br>  modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 8.dp),<br>  textAlign = TextAlign.Center,<br>  fontSize = 14.sp<br>)</pre><h3>Conclusion</h3><p>By using LocalTypography, you ensure consistent text styling across your application. The flexibility to modify specific properties like color and fontSize through the copy method allows for customizations without losing the base style defined in your typography. This approach maintains a centralized style management system, making your UI more cohesive and easier to maintain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41942164c729" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrofit for API Calls with Hilt Dependency Injection]]></title>
            <link>https://medium.com/@anumshafiq89/retrofit-for-api-calls-with-hilt-dependency-injection-5c470228ba94?source=rss-b70ab753f24f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c470228ba94</guid>
            <category><![CDATA[retrofit-with-hilt]]></category>
            <category><![CDATA[android-hilt]]></category>
            <category><![CDATA[hilt-and-retrofit]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[android-retrofit]]></category>
            <dc:creator><![CDATA[Anumshafiq]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 06:31:00 GMT</pubDate>
            <atom:updated>2023-12-21T04:04:47.567Z</atom:updated>
            <content:encoded><![CDATA[<p>In the preceding article, we successfully incorporated Room accessing and storing local data using a Local repository. Now, we’ll focus on making API calls using Retrofit to establish a Remote Repository. Using a combination of Local and Remote Data Sources in your application is possible based on your needs.</p><p>In many applications, accessing data from a server via API calls is a necessity. There exist various approaches for this purpose, but we’ll adopt Retrofit and Hilt for this tutorial. Retrofit is a widely embraced HTTP client library on Android, simplifying interactions with RESTful APIs. Conversely, Hilt serves as a dependency injection library for Android, aiding in the management and injection of dependencies within your application.</p><p>Our objective will be to utilize the TMDB API as the Remote data source. Obtaining an Authentication API key is straightforward; you can easily acquire it from <a href="https://developer.themoviedb.org/reference/intro/authentication#api-key-quick-start">https://developer.themoviedb.org/reference/intro/authentication#api-key-quick-start</a>. Remember to include this key in your project as ACCESS_TOKEN within the Constant class.</p><p>Let’s begin the game, including the basic libraries in the project.</p><pre>//Hilt dependencies. Use latest versions for better experience<br>implementation(&quot;com.google.dagger:hilt-android:2.48.1&quot;)<br>kapt(&quot;com.google.dagger:hilt-compiler:2.48.1&quot;)<br>//Retrofit Dependecies.<br>implementation(&quot;com.squareup.retrofit2:retrofit:2.9.0&quot;)<br>implementation(&quot;com.squareup.retrofit2:converter-gson:2.9.0&quot;)</pre><p>Create an Application class and annotate your Application class @HiltAndroidApp to enable Hilt in your application. Then create an interface that defines your API endpoints. Here, we are only defining two of them. In functionfetchMovies() API now_playing has been called and for functiongetDetail API movie_id has been called.</p><pre>interface MyApiService {<br>    @GET(&quot;now_playing&quot;)<br>    suspend fun fetchMovies(): Response&lt;MovieResponse&gt;<br><br>    @GET(&quot;{movie_id}&quot;)<br>    suspend fun getDetail(<br>        @Path(&quot;movie_id&quot;) movieId: String,<br>        @Query(&quot;language&quot;) language: String = &quot;en-US&quot;<br>    ): Response&lt;MovieDetails&gt;<br>}</pre><p>Write your AppModule class that will be used by the Hilt that provides various dependencies required for network-related operations, like Retrofit, OkHttp, Gson, and an authentication interceptor.</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object AppModule {<br><br>    @Provides<br>    fun provideBaseUrl(): String {<br>        return Constant.BASE_URL<br>    }<br><br>    @Provides<br>    fun provideGson(): Gson {<br>        return GsonBuilder()<br>            .create()<br>    }<br><br>    @Provides<br>    fun provideOkHttpClient(): OkHttpClient {<br>        return OkHttpClient.Builder()<br>            .addInterceptor(<br>                provideAuthInterceptor()<br>            )<br>            .build()<br>    }<br><br>    @Provides<br>    fun provideAuthInterceptor(): AuthInterceptor {<br>        return AuthInterceptor(Constant.ACCESS_TOKEN)<br>    }<br><br>    @Provides<br>    fun provideRetrofit(<br>        baseUrl: String,<br>        gson: Gson,<br>        okHttpClient: OkHttpClient<br>    ): Retrofit {<br>        return Retrofit.Builder()<br>            .baseUrl(baseUrl)<br>            .client(okHttpClient)<br>            .addConverterFactory(GsonConverterFactory.create(gson))<br>            .build()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideApiService(retrofit: Retrofit): MyApiService =<br>        retrofit.create(MyApiService::class.java)<br><br>}</pre><blockquote>In the above code provideBaseUrl() Provides the base URL, provideGson()Provides a Gson instance for JSON serialization/deserialization , provideOkHttpClient()Provides an OkHttpClient instance and adds an AuthInterceptor to it for token authentication.provideAuthInterceptor() Provides an instance of AuthInterceptor with the access token provided via Constant.ACCESS_TOKEN.provideRetrofit()Constructs and provides the Retrofit instance using the base URL, Gson instance, and OkHttpClient.provideApiService() Provides an instance of the MyApiService interface using Retrofit. With authInterceptor code below:</blockquote><pre>class AuthInterceptor(private val authToken: String) : Interceptor {<br><br>    override fun intercept(chain: Interceptor.Chain): Response {<br>        val originalRequest = chain.request()<br><br>        val requestBuilder = originalRequest.newBuilder()<br>            .addHeader(&quot;accept&quot;, &quot;application/json&quot;)<br>            .addHeader(&quot;Authorization&quot;, &quot;Bearer $authToken&quot;)<br><br>        val request = requestBuilder.build()<br>        return chain.proceed(request)<br>    }<br>}</pre><p>Now define MovieRepository class which seems to encapsulate the interaction with apiService (an instance of MyApiService) to fetch movies and retrieve details of a particular movie based on its ID. The structure is typical of a repository pattern where data retrieval from an API is abstracted from the rest of the application. (<a href="https://developer.android.com/topic/architecture#single-source-of-truth">Single Source Of Truth</a>)</p><pre>class MovieRepository @Inject constructor(<br>    private val apiService: MyApiService<br>) {<br>    suspend fun fetchMovies() = apiService.fetchMovies()<br>    suspend fun getDetail(movieId: String) = apiService.getDetail(movieId)<br>}</pre><p>Finally, theMovieViewModel class uses the MovieRepository to interact with the data layer and manage the UI-related data using LiveData, where Hilt provides the movieRepository instance through@Inject . The ViewModel fetches a list of movies and retrieves details of a specific movie based on its ID, returning the List&lt;Movie&gt; and MovieDetails as the Response Objects.</p><pre>MovieViewModel @Inject constructor(<br>    private val movieRepository: MovieRepository<br>) : ViewModel() {<br><br>    private val _moviesLiveData = MutableLiveData&lt;List&lt;Movie&gt;&gt;()<br>    val moviesLiveData: LiveData&lt;List&lt;Movie&gt;&gt; get() = _moviesLiveData<br><br>    private val _movieDetailLiveData = MutableLiveData&lt;MovieDetails&gt;()<br>    val detailLiveData: LiveData&lt;MovieDetails&gt; get() = _movieDetailLiveData<br><br><br>    init {<br>        fetchMovies()<br>    }<br><br>    private fun fetchMovies() {<br>        viewModelScope.launch {<br>            try {<br>                val newItem = withContext(Dispatchers.IO) {<br>                    movieRepository.fetchMovies()<br>                }<br>                _moviesLiveData.postValue(newItem.body()?.results)<br>                Log.e(&quot;element&quot;, newItem.toString())<br>            } catch (e: Exception) {<br>                // Handle exceptions, if any<br>                Log.e(&quot;getDetail&quot;, &quot;Error fetching details: ${e.message}&quot;)<br>            }<br>        }<br>    }<br><br>    fun getDetail(movieId: String) {<br>        viewModelScope.launch {<br>            try {<br>                val response = movieRepository.getDetail(movieId)<br>                _movieDetailLiveData.value = response.body()<br><br>            } catch (e: Exception) {<br><br>            }<br>        }<br>    }</pre><p>As we are using TMDB API so baseurl and thumbnailUrlwill look like this including ACCESS_TOKEN in the Constant file of the application. For further details on the API, you can check <a href="https://developer.themoviedb.org/docs">https://developer.themoviedb.org/docs</a>.</p><pre>object Constant {<br>    const val BASE_URL = &quot;https://api.themoviedb.org/3/movie/&quot;<br>    const val THUMBNAIL_IMAGE_BASE_URL = &quot;https://image.tmdb.org/t/p/w154/&quot;<br>    const val POSTER_IMAGE_BASE_URL = &quot;https://image.tmdb.org/t/p/original&quot;<br>    const val ACCESS_TOKEN = &quot;Your Access Token for the TMDB API&quot;<br>}</pre><p>MovieResponseclass provides data classes representing the structure of movie-related data received from an API response. You can use the attributes as required and write your MovieDetail class for Movie Detail Response.</p><pre>data class MovieResponse(<br>    val dates: DateRange,<br>    val page: Int,<br>    val results: List&lt;Movie&gt;,<br>    val total_pages: Int,<br>    val total_results: Int<br>)<br><br>data class DateRange(<br>    val maximum: String,<br>    val minimum: String<br>)<br><br>data class Movie(<br>    val adult: Boolean,<br>    val backdrop_path: String?,<br>    val genre_ids: List&lt;Int&gt;,<br>    val id: Int,<br>    val original_language: String,<br>    val original_title: String,<br>    val overview: String,<br>    val popularity: Double,<br>    val poster_path: String?,<br>    val release_date: String,<br>    val title: String,<br>    val video: Boolean,<br>    val vote_average: Double,<br>    val vote_count: Int<br>)</pre><p>At the end, we have the UI Layer where we will implement the fragment or an Activity depending upon the requirement of our application. Annotate your Main Activity Class as @AndroidEntryPoint or Fragment in which you are using the ViewModel . Get the instance of the viewModel through activityViewModel or hiltViewModel depending on the use of the UI.</p><pre>@AndroidEntryPoint<br>class MainActivity : AppCompatActivity() {<br>//....<br>    private val movie: MovieViewModel by activityViewModels()</pre><p>You can continue the UI layer from this article <a href="https://medium.com/@anumshafiq89/creating-a-vertical-list-with-jetpack-compose-cb42e1d021cf">https://medium.com/@anumshafiq89/creating-a-vertical-list-with-jetpack-compose-cb42e1d021cf</a>. And you have successfully implemented the Retrofit using Hilt .</p><p>In the article, I demonstrate the utilization of the TMDB API, but the core principles can be applied to any API server by modifying the function names and endpoints. Any feedback on this approach is greatly appreciated. Enjoy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c470228ba94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Room Database + MVVM Implementation Using Kotlin: for Beginners]]></title>
            <link>https://medium.com/@anumshafiq89/android-room-database-mvvm-implementation-using-kotlin-for-beginners-e90524f536ee?source=rss-b70ab753f24f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e90524f536ee</guid>
            <category><![CDATA[model-view-viewmodel]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[android-database]]></category>
            <category><![CDATA[android-room-database]]></category>
            <dc:creator><![CDATA[Anumshafiq]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 11:33:40 GMT</pubDate>
            <atom:updated>2023-12-19T09:27:06.119Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll guide you through implementing the <a href="https://developer.android.com/jetpack/androidx/releases/room">ROOM </a>database functionality. I’ll demonstrate how to combine <a href="https://kotlinlang.org/docs/home.html">Kotlin</a>, <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModel</a>, <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a>, <a href="https://developer.android.com/kotlin/coroutines">Kotlin Coroutines</a>, and <a href="https://coil-kt.github.io/coil/">Coil </a>within the MVVM <a href="https://developer.android.com/topic/architecture">architecture</a> (Model-View-ViewModel) pattern to retrieve data from the ROOM database. We’ll cover essential CRUD (Create, Read, Update, Delete) operations on the database entities. By the end, the app will display a list showcasing the Title and Description of various entities, along with a default image. Please, read through the entire article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*WTSd7qRQ1CSlTLVokFBC5A.png" /><figcaption>Output screen of the App</figcaption></figure><p>Understanding <a href="https://kotlinlang.org/docs/home.html">Kotlin</a>, <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModel</a>, <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a>, <a href="https://developer.android.com/kotlin/coroutines">Kotlin Coroutines</a>, <a href="https://coil-kt.github.io/coil/getting_started/">Coil</a>, and <a href="https://developer.android.com/jetpack/androidx/releases/room">ROOM </a>database concepts is essential for grasping the content of this article. These elements are crucial in creating modern Android apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8F_Hh3G8uxrEmBqvgKZDOw.png" /><figcaption>Android Architecture Layers and Implementation</figcaption></figure><p>In adherence to the principles of MVVM architecture, which prioritize Single Source of Truth (SSOT) and Separation Of Concerns (SOC), we will proceed by implementing the following set of classes and packages. Let’s create these designated packages and classes to maintain architectural integrity and reinforce the best practices of MVVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*B5tXg5oiphqS2cvHX1LKiQ.png" /><figcaption>Room — MVVM architecture implementation</figcaption></figure><p>Your project grade should look like this.</p><pre>plugins {<br>    id(&quot;com.android.application&quot;) version &quot;8.1.2&quot; apply false<br>    id(&quot;org.jetbrains.kotlin.android&quot;) version &quot;1.9.0&quot; apply false<br>    id(&quot;org.jetbrains.kotlin.kapt&quot;) version &quot;1.9.20&quot;<br>}//use the current avaivale version of the plug-ins</pre><p>In the app gradle, I have written a script that is responsible for creating a directory named “schemas” within the project directory if the directory doesn’t already exist to export the database schemas. And implementing all the necessary libraries, below are the ROOM, components lifecycle, and UI libraries.</p><pre>//Include plug-ins<br><br>android {<br>  //namspace and other configuration<br><br>    defaultConfig {<br>        //applicationId = .....<br><br>        //Kapt scehma directory path when created<br>        kapt {<br>            arguments {<br>                arg(&quot;room.schemaLocation&quot;, &quot;$projectDir/schemas&quot;)<br>            }<br>        }<br><br>        // Ensure schema directory creation if doesn&#39;t exist<br>        tasks.register(&quot;createSchemaDir&quot;) {<br>            doLast {<br>                val schemaDir = File(&quot;$projectDir/schemas&quot;)<br>                if (!schemaDir.exists()) {<br>                    schemaDir.mkdirs()<br>                }<br>            }<br>        }<br><br>        tasks.withType&lt;org.jetbrains.kotlin.gradle.tasks.KotlinCompile&gt; {<br>            dependsOn(&quot;createSchemaDir&quot;)<br>        }<br>    }<br><br>    buildTypes {<br>        //....<br>    }<br><br>    compileOptions {<br>        //..<br>    }<br>    kotlinOptions {<br>        //...<br>    }<br>}<br><br>dependencies {<br><br>    val roomVersion = &quot;2.6.0&quot;<br><br>    implementation(&quot;androidx.room:room-runtime:$roomVersion&quot;)<br>    annotationProcessor(&quot;androidx.room:room-compiler:$roomVersion&quot;)<br>    implementation(&quot;androidx.room:room-ktx:$roomVersion&quot;)<br>    kapt(&quot;androidx.room:room-compiler:$roomVersion&quot;)<br>    androidTestImplementation(&quot;androidx.room:room-testing:$roomVersion&quot;)<br><br>    val lifecycleVersion = &quot;2.6.2&quot;<br><br>    implementation(&quot;com.github.bumptech.glide:glide:4.12.0&quot;)<br>    implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion&quot;)<br>    implementation(&quot;androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleVersion&quot;)<br>    implementation(&quot;androidx.fragment:fragment-ktx:1.6.2&quot;) // for Fragment<br>    implementation(&quot;androidx.activity:activity-ktx:1.8.1&quot;)<br>    implementation (&quot;de.hdodenhof:circleimageview:3.1.0&quot;)<br><br>    ....<br>}</pre><p>One of the most important components in the ROOM implementation is the Data Access Object interface or Dao, annotate your Dao class with @Dao and declare methods for database operations using SQL queries or Room annotations. As shown below.</p><pre>    @Query(&quot;SELECT * FROM movie_table&quot;)<br>    fun getAll(): Flow&lt;List&lt;MovieDb&gt;&gt;<br><br>    @Insert<br>    fun insertAll(vararg movieItems: MovieDb)<br><br>    @Query(&quot;DELETE FROM movie_table WHERE id IN (:ids)&quot;)<br>    fun delete(ids: List&lt;Int&gt;)<br><br>    @Query(&quot;UPDATE movie_table SET title = :newTitle WHERE id = :movieId&quot;)<br>    suspend fun updateTitle(movieId: Int, newTitle: String)</pre><p>The Movie class is a representation of your database entity. Annotate it with @Entity and define the table name and its fields. Your MovieDb is the entity class that has three fields i.e. title ,image_url, description and tableName = &quot;movie_table&quot;</p><pre>@Entity(tableName = &quot;movie_table&quot;)<br>data class MovieDb(<br>    @PrimaryKey(autoGenerate = true) var id: Int? = null,<br>    @ColumnInfo(name = &quot;title&quot;) val title: String,<br>    @ColumnInfo(name = &quot;image_url&quot;) val imageUrl: String = &quot;https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Myosotis_scorpioides_-_Niitv%C3%A4lja_bog.jpg/400px-Myosotis_scorpioides_-_Niitv%C3%A4lja_bog.jpg&quot;,<br>    @ColumnInfo(name = &quot;description&quot;) val description: String,<br>)</pre><p>AppDatabase is the Room database class. Annotating it with @Database and specifying the entities it contains and its version with exportSchema = true It provides an abstract function for accessing the DAO. Whereas, getDatabase is a Singleton pattern implementation to ensure only one instance of the database is created. It usesRoom.databaseBuilder to build the database instance.</p><pre>@Database(entities = [MovieDb::class], exportSchema = true, version = 1)<br>abstract class AppDatabase : RoomDatabase() {<br>    abstract fun movieDao(): MovieDao\<br><br>    companion object {<br>        @Volatile<br>        private var INSTANCE: AppDatabase? = null<br><br>        fun getDatabase(<br>            context: Context<br>        ): AppDatabase {<br>            // if the INSTANCE is not null, then return it,<br>            // if it is, then create the database<br>            return INSTANCE ?: synchronized(this) {<br><br>                val instance = Room.databaseBuilder(<br>                    context.applicationContext,<br>                    AppDatabase::class.java,<br>                    &quot;items_table&quot;<br>                )<br>                .build()<br>                INSTANCE = instance<br>                // return instance<br>                instance<br>            }<br>        }<br>    }<br>}</pre><p>The MovieLocalSource class is a local data source that interacts with a Room database using the provided MovieDao to perform various operations on movie entities. This class acts as an abstraction layer between the app&#39;s repository and the actual database operations.</p><pre>class MovieLocalSource(private val movieDao: MovieDao) {<br><br>    fun getAllMovies(): Flow&lt;List&lt;MovieDb&gt;&gt; {<br>        return movieDao.getAll()<br>    }<br><br>    fun insert(movie: MovieDb) {<br>        movieDao.insertAll(movie)<br>    }<br><br>    suspend fun updateTitle(id: Int, newTitle: String) {<br>        movieDao.updateTitle(movieId = id, newTitle = newTitle)<br>    }<br><br>    fun delete(movieId: List&lt;Int&gt;) {<br>        movieDao.delete(movieId)<br>    }<br>}</pre><p>We have reached the Repository, completing our dataLayer classes according to the MVVM clean architecture. HereMovieRepository class acts as an intermediary between the ViewModel and the local data source (MovieLocalSource). It encapsulates the logic for accessing and modifying movie data more abstractly.</p><pre>class MovieRepository(private val movieSource: MovieLocalSource) {<br>    //Get the data from the DB<br>    val allMovies: Flow&lt;List&lt;MovieDb&gt;&gt; = movieSource.getAllMovies()<br>    <br>    //Insert the element to the DB<br>    fun insetMovie(movie: MovieDb) {<br>        movieSource.insert(movie)<br>    }<br>    <br>    //Update the selected element title<br>    suspend fun updateTitle(id:Int, title:String)<br>    {<br>        movieSource.updateTitle(id = id , newTitle = title)<br>    }<br><br>    //Delete the selected item<br>    fun delete(ids: List&lt;Int&gt;) {<br>        movieSource.delete(movieId = ids)<br>    }   <br>}</pre><p>Afterward, it’s time to work on our UI layer, where the ViewModel serves as the primary state holder. Here, we are implementing a simple app so the view model is the implementation of all the methods available in the repository. This MovieViewModel is a part of the MVVM (Model-View-ViewModel) architecture and acts as a bridge between the UI (View) and the MovieRepository. It observes changes in movie data and exposes methods to interact with the repository asynchronously.</p><pre>class MovieViewModel (private val repository: MovieRepository) : ViewModel() {<br><br>    // Using LiveData and caching what allWords returns has several benefits:<br>    // - We can put an observer on the data (instead of polling for changes) and only update the<br>    //   the UI when the data actually changes.<br>    // - Repository is completely separated from the UI through the ViewModel.<br>    val allItems: LiveData&lt;List&lt;MovieDb&gt;&gt; = repository.allMovies.asLiveData()<br><br>    /**<br>     * Launching a new coroutine to insert the data in a non-blocking way<br>     */<br>    fun insert(dbItem: MovieDb) = viewModelScope.launch {<br>        withContext(Dispatchers.IO) {<br>            repository.insetMovie(dbItem)<br>        }<br>    }<br><br>    fun delete(ids: List&lt;Int&gt;) = viewModelScope.launch {<br>        withContext(Dispatchers.IO) {<br>            repository.delete(ids)<br>        }<br>    }<br><br>    fun updateTitle(id:Int, title:String) = viewModelScope.launch {<br>        withContext(Dispatchers.IO)<br>        {<br>            repository.updateTitle(id = id, title = title)<br>        }<br>    }<br>}</pre><p>In the main activity when the data changes, it updates the dataList (ArrayList used to store the movies/entities) and submits the updated list to the RecyclerView adapter using recyclerViewAdapter.submitList(dataList). This triggers a UI update to display the updated list of movies/entities.</p><pre>//Defining the viewModel and passing the global instance of the repository defined in Application class.<br>private val viewModel: MovieViewModel by viewModels {<br>        ViewModelFactory((application as MyApplication).movieRepository)<br>    }<br><br>//Setting the recyclerview and sending data to it.<br>//LiveData observer for the data coming from the viewmodel<br>        viewModel.allItems.observe(<br>            this<br>        ) { items -&gt;<br>            dataList = ArrayList(items)<br>            recyclerViewAdapter.submitList(dataList)<br>        }<br><br>//UI elements <br><br>        //Button to add movie/entity to the Database<br>        addButton.setOnClickListener {<br>            val title = editTextTitle.text.toString()<br>            val description = editTextDescription.text.toString()<br>            if (title.isNotEmpty()) {<br>                val movie = MovieDb(title = title, description = description)<br>                viewModel.insert(movie)<br>            }<br>        }  <br><br>        //Button to Delete the selected element from teh list and the DB<br>        deleteButton.setOnClickListener {<br>            if (selectedItems.isNotEmpty()) {<br>                viewModel.delete(selectedItems)<br>                recyclerViewAdapter.notifyItemRemoved(selectedPosition)<br>            }<br>        }<br><br>        //Button to update the element of the list and the DB<br>        updateButton.setOnClickListener {<br>            if (selectedItems.isNotEmpty()) {<br>                    viewModel.updateTitle(<br>                        id,<br>                        editTextTitle.text.toString()<br>                    )<br>                }<br>                recyclerViewAdapter.notifyItemChanged(selectedPosition)  <br>        }<br>// More UI controllers...<br>}</pre><p>In your MyApplicationclass the AppDatabase is initialized using getDatabase() method, which in turn initializes the MovieLocalSource with the appropriate MovieDao. Finally, the MovieRepository is instantiated, utilizing the MovieLocalSource previously initialized. This enables global access to crucial components like the database and repository throughout the application, adhering to the singleton pattern and facilitating efficient data management across different parts of the app.</p><pre>class MyApplication : Application() {<br>    private val applicationScope = CoroutineScope(SupervisorJob())<br><br>    private val dataBase by lazy { AppDatabase.getDatabase(this, applicationScope) }<br>    private val movieLocalSource by lazy { MovieLocalSource(dataBase.movieDao()) }<br>    val movieRepository by lazy { MovieRepository(movieLocalSource) }<br>}</pre><p>You’ve successfully implemented the MVVM clean architecture and can expand this approach for other entities in your app. Additionally, you can enhance your app by incorporating a RemoteDataSource using Retrofit, which will be the focus of the upcoming article. Stay tuned for more on this topic!Retrofit implementation with Hilt <a href="https://medium.com/p/5c470228ba94">https://medium.com/p/5c470228ba94</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e90524f536ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merging Jetpack Compose with Existing XML Layouts: A Beginner’s Guide]]></title>
            <link>https://medium.com/@anumshafiq89/merging-jetpack-compose-with-existing-xml-layouts-a-beginners-guide-51662a94c552?source=rss-b70ab753f24f------2</link>
            <guid isPermaLink="false">https://medium.com/p/51662a94c552</guid>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-jetpack-compose]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <dc:creator><![CDATA[Anumshafiq]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 07:12:20 GMT</pubDate>
            <atom:updated>2023-11-24T07:12:20.535Z</atom:updated>
            <content:encoded><![CDATA[<p>In this beginner’s guide, we’ll delve into merging Jetpack Compose — a toolkit that encourages a more intuitive way of creating UIs — with your established XML-based layouts. We’ll explore the step-by-step guide to integrating Compose components into your existing projects, empowering you to harness the capabilities of Compose without having to overhaul your entire UI structure.</p><p>Let’s embark on this journey to understand how Jetpack Compose can complement your existing XML layouts and elevate your Android app development experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*8hfmZUOdn0BXXMPLZkqxYA.jpeg" /><figcaption>A simple Compose Text component in the XML layout</figcaption></figure><p>To start using Compose, you need to add some build configurations to your project. Add the following definition to your app’s build.gradle file:</p><pre>android {<br>    buildFeatures {<br>        compose = true<br>    }<br><br>    composeOptions {<br>        kotlinCompilerExtensionVersion = &quot;1.5.4&quot;<br>    }<br>}</pre><blockquote>As per the document you have to enable the jetpack compose and specify the Kotlin compiler extension version for compose, compatible with your project’s Kotlin version. <a href="https://developer.android.com/jetpack/compose/setup">https://developer.android.com/jetpack/compose/setup</a></blockquote><p>In addition, include the BOM and compose libraries for your project.</p><pre>//This dependency integrates Jetpack Compose with the Activity class, enabling the use of Compose in Android activities.<br>implementation(&quot;androidx.activity:activity-compose:1.8.1&quot;) <br>//Compose Bill of Materials (BOM), which helps manage versions of Compose libraries. In this case, it&#39;s using version 2023.03.00 for Compose dependencies.<br>implementation(platform(&quot;androidx.compose:compose-bom:2023.03.00&quot;))<br>//This dependency includes the fundamental UI elements and features provided by Jetpack Compose.<br>implementation(&quot;androidx.compose.ui:ui&quot;)<br>//This includes tooling and preview functionalities for Compose, assisting with development and debugging UI components.<br>implementation(&quot;androidx.compose.ui:ui-tooling-preview&quot;)<br>//This dependency includes the Material Design 3 components and styles adapted for Jetpack Compose, allowing the implementation of Material Design principles in your app&#39;s UI<br>implementation(&quot;androidx.compose.material3:material3&quot;)</pre><p>Create or open an existing XML layout file (e.g., my_layout.xml). Use a layout of your choice (e.g., ConstraintLayout) as the root layout. Add ComposeView within it, as shown below.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;!-- Other views and widgets can be placed here --&gt;<br><br>    &lt;!-- Placeholder for Compose UI --&gt;<br>    &lt;androidx.compose.ui.platform.ComposeView<br>        android:id=&quot;@+id/compose_view&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>In your associated activity or fragment, access ComposeView and attach a Composable function or UI content using setContent.</p><p>For example, in an Activity:</p><pre> override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.my_layout)<br><br>        val composeView = findViewById&lt;ComposeView&gt;(R.id.compose_view)<br>        val myComposeContent: @Composable () -&gt; Unit = {<br>            // Your Compose UI elements go here<br>            Text(text = &quot;Hello from Jetpack Compose!&quot;)<br>        }<br><br>        composeView.setContent {<br>            myComposeContent()<br>        }<br>    }</pre><p>You can add any view to the setContent through findViewById or using dataBinding in your project.</p><p>Build and run your Android app. The ComposeView within XML layout should display the Jetpack Compose UI content which is a Text for now. You can change the Text to the entire list or grid.</p><p>This guide helps you incorporate a ComposeView within a traditional XML layout, enabling you to mix Jetpack Compose UI elements within your existing XML-based layouts. Adjust the Composable content as needed to suit your app&#39;s UI requirements.</p><p><strong>Tips: All Compose functions are invoked from </strong><strong>@Composable annotated functions. You cannot directly call them within </strong><strong>onCreate or any other non-Composable function. Instead, use </strong><strong>setContent to assign the Composable function or UI to the view.</strong></p><p>Hope it helped. Queries and suggestions are welcome. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51662a94c552" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a vertical list with Jetpack Compose]]></title>
            <link>https://medium.com/@anumshafiq89/creating-a-vertical-list-with-jetpack-compose-cb42e1d021cf?source=rss-b70ab753f24f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb42e1d021cf</guid>
            <category><![CDATA[android-jetpack-compose]]></category>
            <category><![CDATA[jetpack-compose-tutorial]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose-ui]]></category>
            <dc:creator><![CDATA[Anumshafiq]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 10:57:38 GMT</pubDate>
            <atom:updated>2023-11-24T04:55:10.203Z</atom:updated>
            <content:encoded><![CDATA[<p>Android is one of the most popular and widely used operating systems in the world, powering billions of devices ranging from smartphones to smartwatches. As an experienced Android developer, I have witnessed the evolution of this platform and learned a lot from its challenges and opportunities. However, writing articles is a new skill for me, and I want to share my knowledge and insights with other developers and enthusiasts interested in Android development. This article is not just a documentation of my initial steps with Jetpack Compose; it’s a narrative of exploration, challenges encountered, insights gained, and the synthesis of my extensive Android development journey with this innovative UI toolkit.</p><p>We are going to implement the list using jetpack compose the final result will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*hjGKxEkvGmHf12nJEbYHoA.gif" /><figcaption>Final app look</figcaption></figure><p>Starting from scratch, Jetpack composes views and provides runtime rendering and creation. For creating a list using Compose, we don’t need the XML layout at all. So, Let’s create a blank activity project and start writing code for the listing using Compose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*DNbRQWGyIg299STqyoL4Zw.jpeg" /><figcaption>Create an empty activity so Android can automatically set up the Jetpack Compose. Note:<strong> Minimum API level should be 21 or higher.</strong></figcaption></figure><p>Empty activity will provide you with the Greeting method in MainActivity. You will now remove the Greetings method and implement the Customize list. In the basic list, there are two Text holders for the Title and Description and an Image holder (previously known as TextView and ImageView, respectively) for the image of the item. You can customize your list once you understand its implementation.</p><pre>//Call the LazyColumnInit from your Surface method where the Greeting method was placed<br>@Composable<br>fun LazyColumnInit() {<br>//Accessing the context from the composable to show the Toast<br>val context = LocalContext.current<br><br>//Declaring the list using remember will help in remembering the stae of the list <br>//generateListData populate the exampleItem to the mutablelist in seperate function<br>val data by rememberUpdatedState(generateListData())<br><br>//Replace numberInInt to any int you want<br>LazyColumn(Modifier.fillMaxSize()) {<br>    items(data.size) { index -&gt;<br>        SetListItem(data[index])<br><br>        if (index != data.lastIndex) {<br>            Divider(<br>                modifier = Modifier<br>                    .padding(vertical = numberInInt.dp)<br>                    .height(numberInInt.dp),<br>                color = MaterialTheme.colorScheme.primary,<br>                thickness = numberInInt.dp<br>            )<br>        }<br>    }<br><br>//Change Toast to make your customize functions or remove item to remove buttons from list end<br>    item {<br>        LazyRowInit(<br>            onButton1Click = {<br>                Toast.makeText(<br>                    context, &quot;Button One Clicked&quot;, Toast.LENGTH_LONG<br>                ).show()<br>            },<br>            onButton2Click = {<br>                Toast.makeText(<br>                    context, &quot;Button Two Clicked&quot;, Toast.LENGTH_LONG<br>                ).show()<br>            }<br>        )<br>    }<br>}<br>}</pre><p>The above code consists of a LazyColumn that displays a list of items using SetListItem(a method defined later in the article), and between these items, it adds a Divider.</p><p>The LazyColumn is a Composable that is typically used for displaying vertically scrolling lists of items efficiently. Each item in the list is created using the items function based on the size of the provided data list.</p><p>The Divider separates the items in the list, and its appearance is customized using modifiers like padding, height, color, and thickness.<br>Finally, there’s an item block containing a LazyRowInit composable that has buttons and callback functions. These callbacks create toast messages when they are clicked.</p><p>Now define the SetListItem method implementation for setting each element in the list.</p><pre><br>@Composable<br>fun SetListItem(exampleItem: ExampleItem) {<br>    Row(<br>        modifier = Modifier<br>            .fillMaxWidth()<br>            .padding(16.dp)<br>    ) {<br>        Image(<br>            painter = // You can customize image loading parameters here if needed<br>            rememberAsyncImagePainter(<br>                ImageRequest.Builder(LocalContext.current).data(data = exampleItem.imageUrl)<br>                    .apply(block = fun ImageRequest.Builder.() {<br>                        // You can customize image loading parameters here if needed<br>                        crossfade(true)<br>                    }).build()<br>            ), contentDescription = null, // Decorative image<br>            modifier = Modifier<br>                .size(numberInInt.dp) // Set the size of Image as per your requirement<br>                .clip(CircleShape)<br>                .background(MaterialTheme.colorScheme.primary)<br>        )<br><br>        Spacer(modifier = Modifier.width(numberInInt.dp))// Set value in integer<br><br>        Column {<br>            Text(text = exampleItem.title, style = MaterialTheme.typography.bodyLarge)<br>            Text(text = exampleItem.description, style = MaterialTheme.typography.bodyMedium)<br><br>        }<br>    }<br>}</pre><blockquote>In the above code Row Composable is used to arrange items horizontally whereas anImage Composable is used to display an image fetched from Urlusing Coillibrary to load the image asynchronously. A Spacer Composable is added to create space between the Image and the Column using a width. The Column Composable is used to arrange items vertically. It contains two Text composable displays exampleItem.title and exampleItem.description with different typography styles (bodyLarge and bodyMedium) from the current MaterialTheme.</blockquote><p>Now define the data class that you want to load in your view as this article includes <em>exampleItem</em> data class.</p><pre>data class ExampleItem(<br>    val id: Int, // Id of the element<br>    val title: String, // Title for the element<br>    val description: String, // Description or any other field<br>    val imageUrl: String //Image url of the element<br>)</pre><p>In the end, create a method generateListData() and populate your data to the view by adding <em>exampleItem in the mutablelist and passing it in the </em>val data by rememberUpdatedState() as written in the previous code.</p><pre>private fun generateListData(): List&lt;ExampleItem&gt; {<br>    for (index in 1..10) {<br>        list.add(<br>            ExampleItem(<br>                id = index,<br>                title = &quot;test $index&quot;,<br>                description = &quot;test description $index&quot;,<br>                 // you can use in testing : https://freepngimg.com/thumb/animation/4-2-animation-png-pic.png<br>                imageUrl = &quot;&quot;<br>            )<br>        )<br>    }<br>    return list<br>}</pre><p>Hurray! You have successfully implemented the vertical list using Compose Jetpack. Please feel free to provide feedback and ask any queries related to the article. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb42e1d021cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>