Saturday, June 12, 2021

【ANDROID STUDIO】 View Data Retrofit With Kotlin Coroutines

 package com.example.myapplication


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.liveData
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Response

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val retService = RetrofitInstance
.getRetrofitInstance()
.create(AlbumService::class.java)
val responseLiveData: LiveData<Response<Albums>> = liveData {
val response = retService.getAlbums()
emit(response)
}
responseLiveData.observe(this, Observer {
val albumsList = it.body()?.listIterator()
if (albumsList != null) {
while (albumsList.hasNext()) {
val albumsItem = albumsList.next()
val result = " " + "Album Title : ${albumsItem.title}" + "\n" +
" " + "Album id : ${albumsItem.id}" + "\n" +
" " + "User id : ${albumsItem.userId}" + "\n\n\n"
text_view.append(result)
}
}
})

}
}

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ScrollView
android:id="@+id/ScrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">

<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

No comments:

Post a Comment