How to Update Data in Realm Database in Android? - GeeksforGeeks

19 Aug, 2021
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. 
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 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.
buildscript {
  repositories {
      google()
      mavenCentral()
 }
All Jetpack components are available in the Google Maven repository, include them in the build.gradle file
allprojects {
  repositories {
      google()
     mavenCentral()
  }
}
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. 
Java
// adding on click listener for item of recycler view.holder.itemView.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // on below line we are creating a new intent.                Intent i = new Intent(context, UpdateCourseActivity.class);                // on below line we are passing all the data to new activity.                i.putExtra("courseName", modal.getCourseName());                i.putExtra("courseDescription", modal.getCourseDescription());                i.putExtra("courseDuration", modal.getCourseDuration());                i.putExtra("courseTracks", modal.getCourseTracks());                i.putExtra("id", modal.getId());                // on below line we are starting a new activity.                context.startActivity(i);       }});
Below is the updated code for the CourseRVAdapter.java file after adding the above code snippet.
Java
import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> {     // variable for our array list and context    private List<DataModal> dataModalArrayList;    private Context context;     public CourseRVAdapter(List<DataModal> dataModalArrayList, Context context) {        this.dataModalArrayList = dataModalArrayList;        this.context = context;    }     @NonNull    @Override    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {        // on below line we are inflating our layout        // file for our recycler view items.        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);        return new ViewHolder(view);    }     @Override    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {        DataModal modal = dataModalArrayList.get(position);        holder.courseNameTV.setText(modal.getCourseName());        holder.courseDescTV.setText(modal.getCourseDescription());        holder.courseDurationTV.setText(modal.getCourseDuration());        holder.courseTracksTV.setText(modal.getCourseTracks());         // adding on click listener for item of recycler view.        holder.itemView.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // on below line we are creating a new intent.                Intent i = new Intent(context, UpdateCourseActivity.class);                // on below line we are passing all the data to new activity.                i.putExtra("courseName", modal.getCourseName());                i.putExtra("courseDescription", modal.getCourseDescription());                i.putExtra("courseDuration", modal.getCourseDuration());                i.putExtra("courseTracks", modal.getCourseTracks());                i.putExtra("id", modal.getId());                // on below line we are starting a new activity.                context.startActivity(i);            }        });    }     @Override    public int getItemCount() {        return dataModalArrayList.size();    }     public class ViewHolder extends RecyclerView.ViewHolder {        // creating variables for our text views.        private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV;         public ViewHolder(@NonNull View itemView) {            super(itemView);            // initializing our text views            courseNameTV = itemView.findViewById(R.id.idTVCourseName);            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);            courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);            courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks);        }    }}
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. 
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".UpdateCourseActivity">     <!--Edit text to enter course name-->    <EditText        android:id="@+id/idEdtCourseName"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:hint="Enter Course Name" />     <!--edit text to enter course duration-->    <EditText        android:id="@+id/idEdtCourseDuration"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:hint="Enter Course Duration" />     <!--edit text to display course tracks-->    <EditText        android:id="@+id/idEdtCourseTracks"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:hint="Enter Course Tracks" />     <!--edit text for course description-->    <EditText        android:id="@+id/idEdtCourseDescription"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:hint="Enter Course Description" />     <!--button for updating course-->    <Button        android:id="@+id/idBtnUpdateCourse"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:text="Update Course"        android:textAllCaps="false" /> </LinearLayout>
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.
Java
import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import io.realm.Realm; public class UpdateCourseActivity extends AppCompatActivity {         // creating variables for our edit text    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt;         // creating a strings for storing    // our values from edittext fields.    private String courseName, courseDuration, courseDescription, courseTracks;    private long id;    private Button updateCourseBtn;    private Realm realm;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_update_course);                 // initializing our edittext and buttons        realm = Realm.getDefaultInstance();        courseNameEdt = findViewById(R.id.idEdtCourseName);        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);        updateCourseBtn = findViewById(R.id.idBtnUpdateCourse);                 // on below line we are getting data which is passed from intent.        courseName = getIntent().getStringExtra("courseName");        courseDuration = getIntent().getStringExtra("courseDuration");        courseDescription = getIntent().getStringExtra("courseDescription");        courseTracks = getIntent().getStringExtra("courseTracks");        id = getIntent().getLongExtra("id", 0);                 // on below line we are setting data in our edit test fields.        courseNameEdt.setText(courseName);        courseDurationEdt.setText(courseDuration);        courseDescriptionEdt.setText(courseDescription);        courseTracksEdt.setText(courseTracks);                 // adding on click listener for update button.        updateCourseBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                                 // getting data from edittext fields.                String courseName = courseNameEdt.getText().toString();                String courseDescription = courseDescriptionEdt.getText().toString();                String courseDuration = courseDurationEdt.getText().toString();                String courseTracks = courseTracksEdt.getText().toString();                                 // validating the text fields if empty or not.                if (TextUtils.isEmpty(courseName)) {                    courseNameEdt.setError("Please enter Course Name");                } else if (TextUtils.isEmpty(courseDescription)) {                    courseDescriptionEdt.setError("Please enter Course Description");                } else if (TextUtils.isEmpty(courseDuration)) {                    courseDurationEdt.setError("Please enter Course Duration");                } else if (TextUtils.isEmpty(courseTracks)) {                    courseTracksEdt.setError("Please enter Course Tracks");                } else {                    // on below line we are getting data from our modal where                    // the id of the course equals to which we passed previously.                    final DataModal modal = realm.where(DataModal.class).equalTo("id", id).findFirst();                    updateCourse(modal, courseName, courseDescription, courseDuration, courseTracks);                }                                 // on below line we are displaying a toast message when course is updated.                Toast.makeText(UpdateCourseActivity.this, "Course Updated.", Toast.LENGTH_SHORT).show();                                 // on below line we are opening our activity for read course activity to view updated course.                Intent i = new Intent(UpdateCourseActivity.this, ReadCoursesActivity.class);                startActivity(i);                finish();            }        });    }     private void updateCourse(DataModal modal, String courseName, String courseDescription, String courseDuration, String courseTracks) {         // on below line we are calling        // a method to execute a transaction.        realm.executeTransaction(new Realm.Transaction() {            @Override            public void execute(Realm realm) {                                 // on below line we are setting data to our modal class                // which we get from our edit text fields.                modal.setCourseDescription(courseDescription);                modal.setCourseName(courseName);                modal.setCourseDuration(courseDuration);                modal.setCourseTracks(courseTracks);                                 // inside on execute method we are calling a method to copy                // and update to real m database from our modal class.                realm.copyToRealmOrUpdate(modal);            }        });    }}
Now run your app and see the output of the app: 
Output:
Below is the complete project file structure after performing the update operation:
AmiyaRanjanRout
hemantjain99
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples