CodingKotlinRecycler ViewRetorfit

Android Recycler view with Kotlin and Retrofit

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

      1. Create Simple project through Android studio and support of kotlin
      2. In  app -> src -> main -> AndroidManifest.xml, add following line to enable Network Support
        <uses-permission android:name="android.permission.INTERNET" />
      3. 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'

         

      4. 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!!)
        }
        }
        }
      5. 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"
          },
        .
        .
        .
        ]
        

         

      6. 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)
        }
      7. 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>
        
      8. 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

      9. 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.

      10. 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")
                        })
        
      11. set data into adapter
        private fun setDataInRecyclerView(it: ArrayList<Model.Photo>?) {
            rvPhotos.adapter = PhotoAdapter(it!!,this)
        }
      12. Finally data will be displayed like

Leave a Reply

avatar
  Subscribe  
Notify of