📌  相关文章
📜  如何在Android的Realm数据库中删除数据?

📅  最后修改于: 2021-05-13 17:05:03             🧑  作者: Mango

在领域数据库的先前系列文章中,我们已经看到了使用android中的领域数据库添加,读取和更新数据。在这些文章中,我们添加了课程详细信息,对其进行了阅读和更新。在本文中,我们将研究如何从Android应用程序的领域数据库中删除这些课程详细信息

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在该应用程序中,我们将在现有应用程序上进行工作,在其中,我们将仅添加一个新按钮以从领域数据库中删除课程。下面是视频,我们将在其中观看我们将要构建的内容。

分步实施

步骤1:使用activity_update_course.xml文件

导航至应用程序> res>布局> activity_update_course.xml文件,然后在此布局内添加一个按钮以删除课程。以下是该文件的代码。

XML


XML


 
    
    
 
    
    
 
    
    
 
    
    
 
    
    


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();
            }
     });
}


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();
            }
        });
    }
}


以下是activity_update_course.xml文件的更新代码 添加以上代码段后。

XML格式



 
    
    
 
    
    
 
    
    
 
    
    
 
    
    

步骤2:使用UpdateCourseActivity。 Java文件

初始化我们的按钮以删除我们的课程。导航到应用程序> Java >您的应用程序包名称> UpdateCourseActivity。 Java文件,并向其中添加以下代码。

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();
            }
     });
}

下面是UpdateCourseActivity的更新代码。 Java文件 添加以上代码段后。

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();
            }
        });
    }
}

现在运行您的应用程序,然后查看代码输出:

输出:

下面是执行CRUD操作后的完整项目文件结构:

在以下链接中查看项目: https : //github.com/ChaitanyaMunje/Realm-Db