Rahulmani
4 min readJun 28, 2021

--

How to Fetch The Data In RecyclerView Using Kotlin For Beginners

Here I Create a Recycler View to Bind the list of Product

What is RecyclerView?

RecyclerView is a container used for displaying a large number of data sets that can be scrolled very efficiently by maintaining a limited number of view

Recycler view need Adapter class and have three override methods are as follows

  • onCreateViewHolder(ViewGroup parent, int viewType)
  • onBindViewHolder(RecyclerView.ViewHolder holder, int position)
  • get item count()

onCreateViewHolder(ViewGroup, int)

This method is called when the adapter is created and is used to initialize your ViewHolder(s).

onBindViewHolder(RecyclerView.ViewHolder, int)

onBindViewHolder deals with the setting of different data and methods related to clicks on particular items of the RecyclerView.

getItemCount()

This overridden method returns the size of the collection that contains the items we want to display

Without any further delay, Let’s get into the Android studio

  1. Create the project
  2. Add the recycler view to the Activity
  3. Create another XML(Activity) for recycler view showing product details
  4. Create a Model/class
  5. Create an Adapter class to bind the product detail to the Recycler view
  6. Connect to the RecyclerView to Adapter class

1.Create Project

2.Add the recycler view to the Activity

Go to the activity_main.xml layout and add a Recycler view, It should be inside the parent layout.

Now your activity_main should look like this

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:id="@+id/relativeCart">


<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerViewCart"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/paymentDetails"
/>
</RelativeLayout>

3. Create another XML(Activity) for recycler view showing product detail

Create a new layout file called productdetails.xml, it will bind the data in RecyclerView

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginBottom="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="8dp"
app:cardBackgroundColor="@color/white">


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/layout1"
android:padding="2dp">


<ImageView
android:id="@+id/foodImage_id"
android:layout_width="90dp"
android:padding="5dp"
android:layout_height="100dp" />

<LinearLayout
android:id="@+id/layoutInner"
android:layout_width="149dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="16dp"
android:layout_weight="1"
android:orientation="vertical">


<TextView
android:id="@+id/product_name_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Product Name"
android:textColor="@color/black"
android:textSize="18sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="bottom"
android:orientation="horizontal">

<TextView
android:id="@+id/actual_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Actual Price"
android:textColor="@color/black"
android:textSize="12sp" />

<TextView
android:id="@+id/price_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="=10"
android:textColor="@color/black"
android:textSize="12sp" />

</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="bottom"
android:orientation="horizontal">

<TextView
android:id="@+id/offer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="offer = "
android:textColor="@color/black"
android:textSize="12sp" />
<TextView
android:id="@+id/offer_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10"
android:textColor="@color/black"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center">
<LinearLayout
android:layout_width="120dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button
android:id="@+id/decrease"
android:layout_width="30dp"
android:layout_height="30dp"
android:text="-"
android:background="@color/black"
android:textColor="@color/white"
android:textSize="25sp"
android:textStyle="bold"/>
<TextView
android:id="@+id/integer_number"
android:layout_width="30dp"
android:layout_height="30dp"
android:gravity="center"
android:text="0"
android:textSize="20sp"
/>
<Button
android:id="@+id/increase"
android:layout_width="30dp"
android:layout_height="30dp"
android:text="+"
android:textSize="18sp"
android:background="@color/black"
android:textColor="@color/white"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>

This will be the template of the Recycler view

4.Create a Model/class

class ProductDetail : Serializable {
var productName: String? = null
var productId: String? = null
var image: String? = null
var price: Int? = null
var offerPrice: Int? = null
var count = 0
var isActive = false
}

Create a model class that looks like this

Properties of POJO or MODEL

  1. All properties must be a public setter and getter methods
  2. All instance variables should be private
  3. Should not Extend prespecified classes.
  4. Should not Implement prespecified interfaces.
  5. Should not contain prespecified annotations.
  6. It may not have any argument constructors

5. Create an Adapter class to bind the product detail to the Recycler view

class CartAdapter( val crtInterface: CrtInterface, var details: ArrayList<ProductDetail>) : RecyclerView.Adapter<CartAdapter.MyViewHolder?>() {
interface CrtInterface {
fun increaseCost(info: ProductDetail?)
fun decreaseCost(info: ProductDetail?)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val inflater: LayoutInflater = LayoutInflater.from(parent.context)
val view: View = inflater.inflate(R.layout.productdetails, parent, false)
return MyViewHolder(view)
}

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val Current: ProductDetail = details[position]
if (Current != null) {
holder.productName.setText(Current.productName)
holder.price.setText(Current.price.toString() + "")
holder.offerPrice.setText(Current.offerPrice.toString() + "")
Picasso.get().load(Current.image).into(holder.imageView)
holder.quantity.setText(Current.count.toString()+ "")
holder.Increment.setOnClickListener { crtInterface.increaseCost(Current) }
holder.Decrement.setOnClickListener { crtInterface.decreaseCost(Current) }

}
}

override fun getItemCount():
Int = details.size

inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var productName: TextView
var productId: TextView? = null
var price: TextView
var offerPrice: TextView
var quantity: TextView
var imageView: ImageView
var Increment: Button
var Decrement: Button
lateinit var addCart: Button

init {
productName = itemView.findViewById<TextView>(R.id.product_name_id)
price = itemView.findViewById<TextView>(R.id.price_id)
offerPrice = itemView.findViewById<TextView>(R.id.offer_id)
imageView = itemView.findViewById(R.id.foodImage_id)
quantity = itemView.findViewById<TextView>(R.id.integer_number)
Increment = itemView.findViewById(R.id.increase)
Decrement = itemView.findViewById(R.id.decrease)
}
}
}

6. Connect to the Recycler view to Adapter class

class CartActivity : BaseActivity(), Serializable, CartAdapter.CrtInterface {
var proceed: Button? = null
var dialog: Dialog? = null
var recyclerView: RecyclerView? = null
var cartAdapter: CartAdapter? = null
var cartDetailsList: ArrayList<ProductDetail>? = null

override fun getViewModel(): ILifecycle.ViewModel? {
return null
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cart)
adjustFontScale(getResources().getConfiguration(), 1.0f)
recyclerView = findViewById<RecyclerView>(R.id.recyclerViewCart)
proceed = findViewById<Button>(R.id.paymentcart)
dialog = Dialog(this)
proceed!!.setOnClickListener {
dialog!!.setContentView(R.layout.progressbar)
dialog!!.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog!!.show()
}
val b: Bundle? = getIntent().getExtras()
if (b != null) {
cartDetailsList = b.getSerializable("cartDetail") as ArrayList<ProductDetail>?
} else if (b == null) {
Toast.makeText(this, "Cartis empty", Toast.LENGTH_SHORT).show()
}
amountUpdate(cartDetailsList)
if (cartDetailsList != null) {
cartAdapter = CartAdapter(this@CartActivity,cartDetailsList!!)
recyclerView!!.setHasFixedSize(true)
recyclerView!!.setLayoutManager(LinearLayoutManager(this@CartActivity))
recyclerView!!.setAdapter(cartAdapter)
cartAdapter!!.notifyDataSetChanged()
} else {
Toast.makeText(this, "cart details not available", Toast.LENGTH_SHORT).show()
}
}

the final result looks like this

Done!!!

--

--