Android recyclerview update item

Android RecyclerView: How to Insert, Update and Delete Item

RecyclerView is possibly most used View in Android development for showing list of items. There was something called ListView the use of which is now outdated. It is not deprecated but RecyclerView does much better task of managing list of thousands of items. It is because of the View Holder pattern. In this blog post we will see how we can use Android RecyclerView to insert, update and delete items in it.

Here we will be adding updating and removing some Product. So everything will be based around hypothetical Store. To follow along you must have a basic grasp of Android. With that being said let us start now.

Why use RecyclerView in the first place ?

If you have just started out with Android Development, this might be a general question on your mind.

It is because RecyclerView does a much better memory management out of the box. No matter the amount of items you have in your Adapter. RecyclerView will show only the items which the user is currently looking at.

Also it is worth noting RecyclerView is really much more straight froward once you grasp the basic idea behind it.

How to use RecyclerView

Let us first see what are the steps that we must go through in order to implement RecyclerView. Let us first see what we will be needing to make RecyclerView display items in list.

  • First, we must create a RecyclerView instance in the XML layout
  • Then, we will need to create a RecyclerView.Adapter implementation
  • RecyclerView.Adapter requires a RecyclerView.ViewHolder to isolate each row and better mange them
  • Then, we will define an Interface to add update and remove item values
  • Finally, we will need our item as a POJO or any form you like

Let us look at how to implement these things one by one. But beware this is a really simple and basic RecyclerView implementation.

Adding recyclerview dependency

We have to add the following dependency in our app > build.gradle file before we can use RecyclerView .

This will enable us to use RecyclerView in our application. I have created a simple UI like below to add Product and it’s price.

Creating layout for RecyclerView

See the code for activity_main.xml below:

The UI from the above code is something like below.

And map the views to activity like this :

Focus on the highlighted lines as you need to map RecyclerView and also add some other properties.

.setHasFixedSize(true) tells the system that we will not be manipulating row height and width dynamically. It will make the operation a little bit faster.

We have to have a LayoutManager for our RecyclerView to display items in a list. Before we can use Android RecyclerView to insert, update and delete items. Let us look at what are the available layout managers.

LayoutManager in RecyclerView

If you are quite new to Android development you might not know that there are 3 layout managers built in for us to use with RecyclerView. Which are:

  • LinearLayoutManager , when we want to show items as a simple list
  • GridLayoutManager , when we want to show items in a grid
  • StaggeredGridLayoutManager , when we want to show uneven grids

We will look at these separately but for this post we will be using only the LinearLayoutManager . And it’s usage is pretty straight forward.

We create an instance by simply doing : LinearLayoutManager(this) . Which we have already done in the highlighted text in above section.

Читайте также:  Fastboot android как включить

Preparing a ViewHolder

Let us first prepare a ViewHolder before we move forward to our Adapter. It is really very simple.

Create a layout file in your res > layout folder and name it item_product .

Eveything is straightforward except for maybe the app:srcCompat=»@drawable/ic_delete_24″ portion. You can use the image of your choice.

Or just use the available vector image from android drawable. Right click on res > drawable then new > vector asset and follow.

For the code portion create a class named ProductListAdapter and copy the code below.

You will receive errors but don’t worry. It’s because of me explaining it in portions. We will remove the errors step by step.

The ViewHolder is the inner class ProductViewHolder and not the class ProductListAdapter .

I like to nest my ViewHolder class but you can extract it into a separate file in your other projects.

Also, itemView: View is the root view for each row which we will be using later. For now everything is mapped just like in the MainActivity class.

Creating Product Model

To store our simple data we first need to define a simple model class. It is just the POJO if you are familiar with java. For the sake of simplicity I am calling it model in this post.

Create a data class with the following code.

We will be using id to uniquely identify each item in the list. This will be useful when updating item later. Alongside we will be displaying name and price .

Creating interface for CUD

C = Create, U = Update, D = Delete

We will be creating an interface to communicate between Adapter and Activity. As it is generally a bad idea to put each and every logic inside the adapter. Let us first create an interface named OnProductClickListener .

We will be using this to show new items in the list. Let us move on with our Adapter.

Those were the prerequisite for use of Android RecyclerView to insert, update and delete items in list.

Creating RecyclerView Adapter

Now that we have created our ViewHolder and almost everything for adapter to use let us implement the adapter.

We have created the class ProductListAdapter let us continue there. We need to implement certain methods before we can actually code any further.

Lets see below I have left out the ViewHolder class for the sake of simplicity.

Let me explain each method in brief.

onCreateViewHolder() is where we create a new instance of ViewHolder and return it.

onBindViewHolder() is where we will map the data to the views as it is called each time the user does something on the screen.

Do not initialize any listeners here, generally considered a bad practice as it will harm the performance.

Finally, getItemCount() is where we return the number of items the Adapter will hold at any given time. Will most likely be called when we do invoke notifyDataSetChanged() or related methods.

Let us fill in the body for each one by one. Let us start by

Declaring List to hold item detail

You must modify the ProductListAdapter ‘s constructor and change it as following.

We will be using mContext to create the view we have defined above in the view holder i.e. item_product.xml .

And we will be storing all our data in mProductList variable.

The modified constructor of the class will look something like.

mOnProductClickListener will be used when we want to perform some actions in each row i.e. update or delete. More on this later as you follow along.

getItemCount()

This method is called by the adapter to determine total items whenever a new data set is passed in.

We will return the total size of the mProductList in this method. Change the above method to make it look like below

onBindViewHolder()

Here, the data is bind to the view. As the working mechanism of RecyclerView is optimized. It will create only the visible views to user.

So every time the user scrolls or does something. It will intelligently perform binding.

You must change the code of the method to this.

Remember the ViewHolder we created above ? We will be using .setText() to set the current position’s value. The value is in product .

Читайте также:  Корейские рпг для андроид

onCreateViewHolder()

We will do a little bit of tasks here. Add some click listeners and add fairly simple logic.

Replace the method above with the code below. I will provide explanation based on line number so keep looking at code for reference.

Line 2 will create an inflater object. Which we use at Line 3 to inflate the view. And finally the ViewHolder which we defined earlier will be created at Line 4 .

Line 7 is where we have set click listener to the root view. Because when we click the row, we should pass data back to the input box.

Line 10 is where we will get the actual position of the view holder. This position is different from the onBindViewHolder() ‘s position because in onBindViewHolder() a relative position is passed in.

At Line 14 we have used .substringAfterLast() to remove the Rs. prefix from the string. Which we have set in onBindViewHolder() above.

Line 15 is where the actual magic happens. We invoke the onUpdate() method and pass in the actual position with the model . We will see to use in in later sections.

Line 19 to Line 23 is for deletion of item from the adapter. It is similar to update section described above.

We need to add certain methods in the Adapter before continuing with using the adapter.

Add item

We will need to add each items the code for looks like below. Add the method below in your adapter class.

We have used notifyItemInserted(mProductList.size) instead of the notifyDataSetChanged() method. It is because we want to update only one item and not the whole data set.

The performance difference will be noticeable when there are 1000’s of items in the list.

Update item

To update item we will be using similar method but we will be using notifyItemChanged() method instead of notifyItemInserted(mProductList.size) .

Let us look at the code below

We loop through each item and compare the id of it. If the item is found we replace the model at that position and notify that item has changed.

Remove item

Similarly we remove item with the method below. Add it too to the adapter class.

First we get the position and then remove the item from the list. And then we will notify that the item has been removed at that position with notifyItemRemoved() .

Finally we only have one more method to auto increment and get the id for each item.

Auto generating ID

It’s tiring to create one id manually each time so let us automate the process. This ID will be used to uniquely identify each item in the list. Which will help us in updating the values.

The logic is pretty straight forward. We will check if the list is empty. If it is not get the last item’s id and return it after doing +1 .

Summary

Let us take a look at final code of our RecyclerView.Adapter class including the ViewHolder .

Now that we have created the adapter. Let us use it in our activity. We are only left with final step in using Android RecyclerView for insert, update and delete.

Using the RecyclerView Adapter

Finally we have passed the most tiring bit of code and come to the almost end.

Let us see how we can use the ProductListAdapter in our application. I will break it down for you and there is a complete code below if you just want to see the code.

Creating necessary variables

Declare the following variables in the MainActivity class

Them mOnProductClickListener is the listener we had defined earlier. I have added comments above for you to easily understand it.

We also create and use a new instance of the adapter in the onCreate() method like below.

Creating the item

Let us first create the item and add it to the adapter.

Add the following click listener to the addProduct() variable in the MainActivity .

We have only done basic validation and got the next id for the list. Then we have created a new object of the ProductModel by passing in id , name and price .

And then called the addProduct() method of the adapter. Finally, we have cleared the input with .setText(«») .

Читайте также:  Черные значки для андроид

Let us see the click listener for the update portion.

Updating the item

Add a listener to the variable updateProduct() in MainActivity.

Most of the things are same from the create item. The only difference is in the model variable. Instead of creating the new variable we have taken it from the modelToBeUpdated variable we have defined earlier.

Once we have new values set we passed the model to the adapter by calling updateProduct() method.

Summary

We have the final code for our MainActivity as below cross verify if you have missed anything at all.

That is how you use the adapter after creating it. If you want to look at the full source code visit this GitHub repository.

With this we have completed using Android RecyclerView for insert, update and delete item from it.

Feel free to comment below if you have any issue with this blog post or the code in the repository about android recyclerview .

Источник

Android recyclerview update item

Add, Remove and Update RecyclerView Items In Android Studio

  • Post author:admin
  • Post published: July 7, 2019
  • Post category:ANDROID / HOME
  • Post comments:0 Comments

Android RecyclerView provides advanced and powerful features to display a large amount of data in your app. In this article, we learn How To Add, Remove, and Update Items In Android RecyclerView with the help of an example.

Here are resources, which help you to learn more about Android RecyclerView.

In this tutorial, we work for the following solution with the help of an example in Android Studio:

  • How to Add and Remove RecyclerViewItems In Android Studio.
  • How to UpdateRecyclerViewItems In Android Studio.

Features Of Application

  • Display the list of items in RecyclerView.
  • Add a New Item in RecyclerView on the click of a button.
  • Remove an item from the RecyclerView on the click of an item button.
  • Update an item of the RecyclerView on click of the update button.

Demo

Create A New Project

Before Implementing the following code first create a new project in Android Studio, go to File => then go to New => then select the New Project option. In Add an activity option select default activity(Blank Activity) and proceed.

Structure Of Code

The following image is showing the project structure. Total three java files I have created over here MainActivity, Model, and RvAdapter similarly total two XML files created one for MainActivity that is “activity_main.xml” and another for RecyclerView item that is “item_list.xml“.

Code

Code for build.gradle (Module: app )

Add the following two additional libraries in dependencies of your build.gradle (Module: app ):

  • implementation ‘com.android.support:recyclerview-v7:28.0.0’
  • implementation ‘com.google.code.gson:gson:2.8.2’

Code for AndroidManifest.xml file .

The following code is for the android application Manifest File which is available in your project root directory. The manifest file defines the project structure this is a very important part of the application.

Code for MainActivity.java file.

This is the main activity of the application where we implement the complete functionality like:

  • Android RecyclerView implementation.
  • Insert New Item in Recyclerview on click of Add button.
  • Delete Item of RecyclerView on click of cancel button of the item.
  • Enable the update option on click of RecyclerView item.
  • Update the item of RecyclerView on click of Update button.

Code for the activity_main.xml file.

The following XML code is for the main UI of the application. In this layout add the RecyclerView widget and all the views to handle the functionality.

Code for Model.java file.

Now we create a model class to hold our new inserted data and also add the getter/setter methods for all the variables which are defined in this class.

Code for RvAdapter.java file.

This source code for the adapter class which helps in render the data.

Code for the item_list.xml file.

This is your one item layout of RecyclerView which helps to display a large number of the data list. In this item UI, I have defined a TextView with id “tv_name” to display a name and an ImageView with id “img_remove” to display a cancel icon on this icon perform an action to remove that particular item of RecyclerView.

Источник

Оцените статью