realm数据库报错:Changing Realm data can only be done from inside a transaction.

在编写realm数据库相关时:

代码:

List<Student> delByStudent(String priNum){
        RealmResults<Student> studentsList = myStudentRealm.where(Student.class).equalTo("num",priNum).findAll();
        for (int i = 0;i<studentsList.size();i++)
            studentsList.deleteFirstFromRealm();
        return studentsList;

在for的循环语句

studentsList.deleteFirstFromRealm();

报错:????

java.lang.IllegalStateException: Changing Realm data can only be done from inside a transaction.
原因:要成功更改数据库realm的数据需要在事务里。

解决方法:

myStudentRealm.beginTransaction();
//  change data to realm
myStudentRealm.commitTransaction();
故,修改后的代码如下:??????
//  delete student by primary key(StuNum)
    List<Student> delByStudent(String priNum){
        RealmResults<Student> studentsList = myStudentRealm.where(Student.class).equalTo("num",priNum).findAll();
        myStudentRealm.beginTransaction();
        for (int i = 0;i<studentsList.size();i++) {
            studentsList.deleteLastFromRealm();
            Log.e("stu","-------delet_by-------"+studentsList);
        }
        myStudentRealm.commitTransaction();
        return studentsList;