Dedicated Server

Jetpack compose tutorial in Kotlin(Android) to fetch list of items from remote api

Fetching and Displaying Items with Jetpack Compose - Kotlin App

In this tutorial, we'll create a Jetpack Compose app in Kotlin that fetches a list of items from a remote API and displays them using a Compose UI.

Let's get started!

Step 1: Set up the Project

Create a new Android project in Android Studio with a minimum SDK version of 21 and select the Kotlin language. Make sure you have the latest version of the Android Gradle Plugin and Kotlin plugin installed.

Step 2: Add Dependencies

In your project's build.gradle file, add the following dependencies:


dependencies {
    // Jetpack Compose
    implementation 'androidx.activity:activity-compose:1.4.0-beta01'
    implementation 'androidx.compose.ui:ui:1.1.0-alpha05'
    implementation 'androidx.compose.material:material:1.1.0-alpha05'
    implementation 'androidx.compose.runtime:runtime:1.1.0-alpha05'
    implementation 'androidx.compose.foundation:foundation:1.1.0-alpha05'

    // Networking
    implementation 'io.ktor:ktor-client-android:1.7.0'
    implementation 'io.ktor:ktor-client-serialization-jvm:1.7.0'
    implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.1'
}

Step 3: Define the Item Model

Create a new Kotlin data class to represent the item (e.g., Post for this example):


@Serializable
data class Post(val id: Int, val userId: Int, val title: String, val body: String)

Step 4: Create the API Service

Create a new Kotlin file named ApiService.kt and add the following code:


import io.ktor.client.*
import io.ktor.client.features.json.*
import io.ktor.client.request.*
import kotlinx.serialization.Serializable

object ApiService {
    private val httpClient = HttpClient {
        install(JsonFeature) {
            serializer = KotlinxSerializer()
        }
    }

    suspend fun getPosts(): List<Post> {
        return httpClient.get("https://jsonplaceholder.typicode.com/posts")
    }
}

Step 5: Create the Composable Function

Update the existing Kotlin file containing the Composable function (e.g., MainActivity.kt) with the following code:


import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

@Composable
fun PostList(posts: List<Post>) {
    LazyColumn {
        items(posts) { post ->
            Text(text = "Post ${post.id}", style = MaterialTheme.typography.h6)
            Text(text = post.title, style = MaterialTheme.typography.body1)
            Text(text = post.body, style = MaterialTheme.typography.body2)
        }
    }
}

@Preview
@Composable
fun PreviewPostList() {
    val previewPosts = listOf(
        Post(1, 1, "Title 1", "Content 1"),
        Post(2, 2, "Title 2", "Content 2"),
        Post(3, 3, "Title 3", "Content 3")
    )
    PostList(posts = previewPosts)
}

Step 6: Create the MainActivity

Update the existing MainActivity.kt file with the following code:


import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Fetch the posts from the API
        GlobalScope.launch(Dispatchers.Main) {
            val posts = ApiService.getPosts()

            // Display the posts using Jetpack Compose
            setContent {
                PostList(posts = posts)
            }
        }
    }
}

Step 7: Run the App

Build and run your app on an Android device or emulator. You should see the list of posts fetched from the JSONPlaceholder API displayed in a Compose UI.

That's it! You've successfully created a Jetpack Compose app in Kotlin that fetches and displays a list of posts from a remote API.

I hope this tutorial was helpful. Happy coding!

No comments:

Post a Comment