Simple tutorial of Recycle view with kotlin and Retrofit.
Retrofit : This is type Safe Http client for Android and JAVA. We can easily connect web services through it. and it’s provides converter to easily convert response into Object. like Gson, JackSon, Moshi, Protobuf,wire and Simple XML. it’s also provide support of custom headers.
Here is basic example of Recycler view with Kotlin
-
-
- Create Simple project through Android studio and support of kotlin
- In app -> src -> main -> AndroidManifest.xml, add following line to enable Network Support
<uses-permission android:name="android.permission.INTERNET" />
- In app -> build.gradle file add following dependency. Dependency include Retrofit, RxJava ,RxAndroid and Picasso for the Image Processing.
implementation 'com.android.support:design:26.1.0' implementation "com.squareup.retrofit2:retrofit:2.4.0" implementation "com.squareup.retrofit2:adapter-rxjava2:2.4.0" implementation "com.squareup.retrofit2:converter-gson:2.4.0" implementation "io.reactivex.rxjava2:rxandroid:2.0.1" implementation 'com.squareup.picasso:picasso:2.71828'
- Setting up Retrofit classesIRetrofit.kt : This is java interface which will be turned into http api by retrofit. You can find more annotation from here
interface IRetrofit { @GET("albums/1/photos") fun getPhotos() : Observable<ArrayList>}
APIClient.kt : Implementation of retrofit service
class APIClient { companion object { fun create(): IRetrofit { val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl("https://jsonplaceholder.typicode.com/") .build() return retrofit.create(IRetrofit::class.java!!) } } }
- For the demo, we are using JsonPlaceHolder api to fetch datahttps://jsonplaceholder.typicode.com/albums/1/photos
[ { "albumId": 1, "id": 1, "title": "accusamus beatae ad facilis cum similique qui sunt", "url": "http://placehold.it/600/92c952", "thumbnailUrl": "http://placehold.it/150/92c952" }, . . . ]
- Create Object class to map to object from response
object Model { data class Photo(val albumId : Int , val id : Int,val title : String ,val url : String,val thumbnailUrl : String) }
- Add recycle view in activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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"> <android.support.v7.widget.RecyclerView android:id="@+id/rvPhotos" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v7.widget.RecyclerView> </LinearLayout>
- Create layout for recycle list item item_row_photo.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/ivImage" android:layout_width="60dp" android:layout_height="60dp" android:layout_centerVertical="true" android:padding="5dp" /> <TextView android:id="@+id/tvTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@+id/ivImage" android:padding="5dp" /> </RelativeLayout>
thumbnailUrl will load into ivImage and title will set into tvTitle
- Create recycler view Adapter to render items in Recycler view PhotoAdapter.kt
class PhotoAdapter(val items: ArrayList, val context: Context) : RecyclerView.Adapter() { override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): PhotoAdapter.ViewHolder { val view: View = LayoutInflater.from(context).inflate(R.layout.item_row_photo, parent, false) return PhotoAdapter.ViewHolder(view) } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: PhotoAdapter.ViewHolder?, position: Int) { holder!!.bindingvalues(items.get(position)) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindingvalues(get: Model.Photo) { Picasso.get().load(get.thumbnailUrl).into(itemView.ivImage) itemView.tvTitle.text = get.title } } }
Picasso library is used to load images loading library.
- In MainActivity.kt , declare APIClient as lazy
val mAPIClient by lazy { APIClient.create(); }
In On Create Method, Assign layout manager to recycle view
rvPhotos.layoutManager = LinearLayoutManager(this)
Add subscriber and observer to get the data through Retorfit
mAPIClient.getPhotos() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ it -> Log.d("size", it.size.toString()) setDataInRecyclerView(it); }, { it -> Log.d("error", "errors") })
- set data into adapter
private fun setDataInRecyclerView(it: ArrayList<Model.Photo>?) { rvPhotos.adapter = PhotoAdapter(it!!,this) }
- Finally data will be displayed like
-
Leave a Reply