How to Update Data in Realm Database in Android?
In previous articles, we have seen adding and reading data from our realm database in Android. In that article, we were adding course details in our database and reading the data in the form of a list. In this article, we will take a look at updating this data in our android app.
What we are going to build in this article?
We will be working on the existing application which we build in our previous articles. In that, we will be simply creating a new activity in that we will be creating a form for updating our course details. Below is the video in which we will get to see what we are going to build in this article.
Step by Step Implementation
Step 1: Creating a new activity for updating our course
As we want to update our course, so for this process we will be creating a new activity where we will be able to update our courses in the SQLite database. To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as UpdateCourseActivity and create new Activity. Make sure to select the empty activity.
Step 2: Add google repository in the build.gradle file of the application project.
All Jetpack components are available in the Google Maven repository, include them in the build.gradle file
Step 3: Updating our CourseRVAdapter.java class
As we will be opening a new activity to update our course. We have to add on click listener for the items of our RecycleView. For adding onClickListener() to our recycler view items navigate to the app > java > your app’s package name > CourseRVAdapter class and simply add an onClickListener() for our RecyclerView item. Add the below code to your adapter class.
Below is the updated code for the CourseRVAdapter.java file after adding the above code snippet.
Step 4: Working with the activity_update_course.xml file
Navigate to the app > res > Layout > activity_update_course.xml and add the below code to it.
Step 5: Working with the UpdateCourseActivity.java file
Navigate to the app > java > your app’s package name > UpdateCourseActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail.
Now run your app and see the output of the app:
Below is the complete project file structure after performing the update operation:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.