3 Temmuz 2020 Cuma

Kotlin-7 (Android Kotlin GridView(Api Response) - Kotlin ile API'den veri alınıp GridView üzerinde gösterilmesi)

 

Herkese merhaba,

bu yazımda Kotlin ile bir API den veri okuyarak GridView üzerinden nasıl listeleneceiğini paylaşacağım.

 

İlk olarak Android Studio ile bir Kotlin projesi oluşturun.

Ardından uygulamanın internete çıkabilmesi için AndroidManifest.xml dosyasına gereken tanımlamayı yapın. Dosyanın son hali aşağıdaki gibi olmalıdır.



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorials.apiresponsegridview">

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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest> 


 

API den dönecek olan response'ları dönüştürmek için Photo.kt adında bir class file oluşturun.

Photo.kt class'ı aşağıdaki gibi olmalıdır.



class Photo {

var albumId: Int? = null
var id: Int? = null
var title: String? = null
var url: String? = null
var thumbnailUrl: String? = null

override fun toString(): String {
return "Photo(albumId=$albumId, id=$id, title=$title," +
" url=$url, thumbnailUrl=$thumbnailUrl)"
}
}

 

  

Photo objelerini bir list halinde GridView'e verebilmek için PhotoAdapter.kt adında bir class oluşturun.

PhotoAdapter.kt class'ının içeriği aşağıdaki gibi olmalıdır.



class PhotoAdapter : BaseAdapter {

var context: Context? = null
var photos = ArrayList<Photo>();

constructor(context: Context?, photos: ArrayList<Photo>) {
this.context = context
this.photos = photos
}

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var photo = this.photos[position]

var inflator = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
var photoView = inflator.inflate(R.layout.photo_content, null)
photoView.image.setImageResource(R.drawable.ic_launcher_background)
photoView.title.setText(photo.title!!)

Picasso.get()
.load(photo.url)
.resize(150, 150)
.centerCrop()
.into(photoView.image)


return photoView
}

override fun getItem(position: Int): Any {
return photos[position]
}

override fun getItemId(position: Int): Long {
return position.toLong()
}

override fun getCount(): Int {
return photos.size
}
}

 

 

activity_main.xml dosyası içerisine bir GridView ekleyin. Dosyasın son hali aşağıdaki gibi olmalıdır.



<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">


<GridView
android:id="@+id/photosGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="150dp"
android:horizontalSpacing="15dp"
android:numColumns="auto_fit"
android:verticalSpacing="15dp" />

</androidx.constraintlayout.widget.ConstraintLayout>


 

activity_main.xml dosyasının yanına  GridView içeriği olması için photo_content.xml adında bir xml dosyası oluşturun. Bu xml dosyası  LinearLayout içinde bir TextView ve bir ImageView barındıracaktır.

photo_content.xml dosyasının son hali aşağıdaki gibi olacaktır.



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="#ddd"
android:gravity="center"
android:orientation="vertical"
android:padding="15dp">

<ImageView
android:id="@+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
/>

<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20sp" />
</LinearLayout>

 

 

Tüm bu adımlardan sonra MainActivity'e giderek onCreate methodunda çağrılmak üzere bir doApiCall(...) methodu oluşturun. Bu method içerisinde varsayılan olarak asenkron bir şekilde yapılan HttpRequest ler countDownLatch.await() ile senkron hale getirilmiştir.

MainActivity.kt dosyasının son hali aşağıdaki gibi olmalıdır.



class MainActivity : AppCompatActivity() {
var adapter: PhotoAdapter? = null
var photos = ArrayList<Photo>()

private val client = OkHttpClient()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
doApiCall("https://jsonplaceholder.typicode.com/albums/1/photos")

adapter = PhotoAdapter(this, photos)

photosGridView.adapter = adapter
}

fun doApiCall(url: String) {
val request = Request.Builder().url(url).build()

val countDownLatch = CountDownLatch(1)
client.newCall(request).enqueue(object : Callback {

override fun onFailure(call: Call, e: IOException) {
println("Error! e : ${e.message} ")
countDownLatch.countDown();
}

override fun onResponse(call: Call, response: Response) {

println("Success...")

val responseStr = response.body?.string()
val photoList: List<Photo> =
Gson().fromJson(responseStr, Array<Photo>::class.java).toList()

println("photo : $photoList")

photos = photoList as ArrayList<Photo>
countDownLatch.countDown();
}
})

countDownLatch.await();
}
}


 

uygylamanın kaynak kodlarına aşağıdaki linkten erişebilirsiniz.

github: https://github.com/lvntyldz/tutorials/tree/master/kotlin-android-app-examples/07-api-response-grid-view

 


Hiç yorum yok:

Yorum Gönder