Search code examples
android-jetpack-composeimageurlcoil

AsyncImage not loading : Coil-Jetpack Compose


I have a Jetpack Compose app that makes a call to the Picsum API (endpoint: https://picsum.photos/v2/list) and tries to display them in a LazyList using the Coil library (2.1.0). I have the typical Retrofit2 + OkHttp3 setup, and am able to get all the necessary data, including the required image URL, from the endpoint. So far so good.

However, despite having valid image URLs, I am not able to display the image in the view. I've tried both AsyncImage and Image with rememberAsyncImagePainter but to no avail. I even tried hard-coding the URL string, but it still doesn't display anything. I don't know what I'm doing wrong!

Similar posts mention the INTERNET permission, but I already have it in my AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

Here is the link to my github project, and below are snippets of relevant code:

PhotoCard.kt

@Composable
fun PhotoCard(photo: Photo, ... ) {
    ...
    Image(
        painter = rememberAsyncImagePainter(photo.url),
        ...
    )
}

PhotoListViewModel.kt

class PhotoListViewModel @Inject constructor(
    private val getPhotoListUseCase: GetPhotoListUseCase
) : ViewModel() {

    private val _pageState = MutableStateFlow(PageState<Photo>())
    val pageState = _pageState.asStateFlow()

    fun loadPhotoList(loadNextPage: Boolean = false) {
        ...
        getPhotoListUseCase.invoke().let { response ->
            if (response == null) {
                ...
            } else {
                _pageState.update {
                    it.copy(data = response, isInflight = false)
                }
            }
        }
    }

}

PhotoListRepository.kt

interface PhotoListRepository {
    suspend fun getPhotoList(): List<Photo>?
}

PhotoListApi.kt

interface PhotoListApi {
    @GET("v2/list")
    suspend fun getPhotoList(): List<Photo>?
}

Photo.kt

data class Photo(
    val id: String,
    val author: String,
    val width: Int,
    val height: Int,
    val url: String,
    val download_url: String
)

Solution

  • As I see in the API url is not the direct image link. It is basically the page url of the image.

    Use photo.download_url instead of photo.url