Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Delete Data from Firebase Realtime Database in Android?
Next article icon

How to Delete Data in Realm Database in Android?

Last Updated : 19 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In the previous series of articles on the realm database, we have seen adding, reading, and updating data using the realm database in android. In that articles, we were adding course details, reading them, and updating them. In this article, we will take a look at deleting these course details from our realm database in the Android app. 

What we are going to build in this article? 

We will be building a simple application in which we will be working on the existing applications in which we will be simply adding a new button to delete our course from the realm database. 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: 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 2: Working with the activity_update_course.xml file

Navigate to the app > res > layout > activity_update_course.xml file and add a Button inside this layout for deleting a course. Below is the code for that file. 

XML
<!--Button for deleting your course to database--> <Button   android:id="@+id/idBtnDeleteCourse"   android:layout_width="match_parent"   android:layout_height="wrap_content"   android:layout_margin="10dp"   android:text="Delete Course"   android:textAllCaps="false"   android:visibility="visible" /> 

Below is the updated code for the activity_update_course.xml file after adding the above code snippet.

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" />      <!--Button for deleting your course to database-->     <Button         android:id="@+id/idBtnDeleteCourse"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="10dp"         android:text="Delete Course"         android:textAllCaps="false"         android:visibility="visible" />  </LinearLayout> 

Step 3: Working with the UpdateCourseActivity.java file

Initializing our button to delete our course. Navigate to the app > java > your app’s package name > UpdateCourseActivity.java file and add the below code to it. 

Java
// adding on click listener for delete course button. deleteCourseBtn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 // on below line we are calling a method to delete course.                 deleteCourse(id);                 // after deleting we are displaying a toast message as course deleted.                 Toast.makeText(UpdateCourseActivity.this, "Course Deleted.", Toast.LENGTH_SHORT).show();                 // after that we are opening a new activity via an intent.                 Intent i = new Intent(UpdateCourseActivity.this, ReadCoursesActivity.class);                 startActivity(i);                 finish();             }         });     }  // deleteCourse() function private void deleteCourse(long id) {         // on below line we are finding data from our modal class by comparing it with the course id.         DataModal modal = realm.where(DataModal.class).equalTo("id", id).findFirst();         // on below line we are executing a realm transaction.         realm.executeTransaction(new Realm.Transaction() {             @Override             public void execute(Realm realm) {                 // on below line we are calling a method for deleting this course                 modal.deleteFromRealm();             }      }); } 

Below is the updated code for the UpdateCourseActivity.java file after adding the above code snippet.

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, deleteCourseBtn;     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);         deleteCourseBtn = findViewById(R.id.idBtnDeleteCourse);          // 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();             }         });          // adding on click listener for delete course button.         deleteCourseBtn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 // on below line we are calling a method to delete course.                 deleteCourse(id);                 // after deleting we are displaying a toast message as course deleted.                 Toast.makeText(UpdateCourseActivity.this, "Course Deleted.", Toast.LENGTH_SHORT).show();                 // after that we are opening a new activity via an intent.                 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);             }         });     }      // deleteCourse() function     private void deleteCourse(long id) {         // on below line we are finding data from our modal class by comparing it with the course id.         DataModal modal = realm.where(DataModal.class).equalTo("id", id).findFirst();         // on below line we are executing a realm transaction.         realm.executeTransaction(new Realm.Transaction() {             @Override             public void execute(Realm realm) {                 // on below line we are calling a method for deleting this course                 modal.deleteFromRealm();             }         });     } } 

Now run your app and see the output of the code: 

Output:

Below is the complete project file structure after performing the CRUD operation:

Check out the project at the below link: https://github.com/ChaitanyaMunje/Realm-Db


Next Article
How to Delete Data from Firebase Realtime Database in Android?

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Android
Practice Tags :
  • Java

Similar Reads

  • How to Delete Data in SQLite Database in Android?
    In the previous articles, we have seen three operations of CRUD operations such as create, read and update operations in our Android app. In this article, we will take a look at adding delete operation for deleting our items stored in the SQLite database.  What we are going to build in this article?
    8 min read
  • 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
    7 min read
  • How to Delete Data in Back4App Database in Android?
    We have seen adding data to our Back4App database along with reading and updating this data. In this article, we will take a look at Deleting this data.  What we are going to build?  We will be adding a simple button inside our update screen where we were updating our data and inside that screen, we
    7 min read
  • How to Read Data from Realm Database in Android?
    In the previous article, we have seen adding data to the realm database in Android. In this article, we will take a look at reading this data from our Realm Database in the Android app.  What we are going to build in this article?  In this article, we will be simply adding a Button to open a new act
    8 min read
  • How to Delete Data from Firebase Realtime Database in Android?
    In this article, we will see How to Delete added data inside our Firebase Realtime Database. So we will move towards the implementation of this deleting data in Android Firebase.   What we are going to build in this article?   We will be showing a simple AlertBox when the user long clicks on the ite
    4 min read
  • How to Install and Add Data to Realm Database in Android?
    Realm Database is a service which is provided by MongoDb which is used to store data in users device locally. With the help of this data can be stored easily in users' devices and can be accessed easily. We can use this database to store data in the user's device itself. This is a series of 4 articl
    8 min read
  • How to Delete Data in SQLite Database in Android using Jetpack Compose?
    In the previous articles, we have seen three operations of CRUD operations such as create, read and update operations in our Android app. In this article, we will take a look at the delete operation for deleting our items stored in the SQLite database in the android application using Jetpack Compose
    9 min read
  • How to Save Data to the Firebase Realtime Database in Android?
    Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simp
    7 min read
  • How to Read Data from Back4App Database in Android?
    We have seen adding data to the Back4App database in the Android app. In this article, we will take a look at reading this data from our database in our Android App. What we are going to build in this article?  We will be creating a new screen in the previous application and inside that, we will dis
    9 min read
  • How to Debug Database in Android?
    The Android Debug Database library is a useful tool for troubleshooting databases and shared preferences in Android apps. In this article we would be looking forward to using this library and get our hand on it, so continue reading, and indulge. First thing's first, What's Exactly an Android Debug D
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences