领域android删除所有数据

时间:2017-04-27 08:24:52

标签: android realm-mobile-platform

mRealm.beginTransaction();
mRealm.clear(AboutItemRealm.class);
mRealm.clear(AgendaItemRealm.class);
mRealm.clear(AttendeesItemRealm.class);
mRealm.clear(DocumentsItemRealm.class);
mRealm.clear(FAQsItemRealm.class);
mRealm.clear(GalleryItemRealm.class);
mRealm.clear(GoodToKnowItemRealm.class);
mRealm.clear(MultiEventItemRealm.class);
mRealm.clear(ReservationItemRealm.class);
mRealm.clear(SingleEventItemRealm.class);
mRealm.clear(SpeakerItemRealm.class);
mRealm.commitTransaction();
mRealm.close();

当我从应用程序注销时我需要清除领域的数据,因为我必须清除这样的每个类,所以有没有办法删除领域的所有数据而不必写所有这些mRealm.clear(ClassName.class)对于每个结构?

5 个答案:

答案 0 :(得分:10)

删除整个Realm(架构)的正确方法是使用:

Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();

// delete all realm objects
realm.deleteAll();

//commit realm changes
realm.commitTransaction();

请注意,这将删除所有扩展RealmObject类的领域对象。

Original answer here

有关更新的领域交易格式

realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            realm.deleteAll();
        }
    });

答案 1 :(得分:1)

realm.deleteAll()将尽一切力量,但

  

除非您要使用beginTransaction(),否则请不要使用   出于某种原因手动commitTransaction()进行交易

最好的方法是使用executeTransaction(),因为即使在事务中引发任何异常,它也会commitTransaction

        try {
            realm.executeTransaction { realm ->
                realm.deleteAll()
            }
        } finally {
            realm?.close()
        }

如果您真的想以高效便捷的方式使用Realm,请阅读This Article。我个人认为它比官方文档有用很多

答案 2 :(得分:0)

试试这个解决方案。这将删除您的Realm数据库。

public static boolean deleteRealm(RealmConfiguration configuration)

这是Realm中的一个函数,来自docs

答案 3 :(得分:0)

首先关闭所有领域实例,然后调用deleteRealm

public static void removeAllData(Realm realm)
{
    try {
        realm.close();
        Realm.deleteRealm(realm.getConfiguration());
    } catch (Exception e) {
        Log.e(TAG, "removeAllData:" + e.getMessage());
    }
}

Realm.Java

/**
     * Deletes the Realm file specified by the given {@link RealmConfiguration} from the filesystem.
     * All Realm instances must be closed before calling this method.
     *
     * @param configuration a {@link RealmConfiguration}.
     * @return {@code false} if a file could not be deleted. The failing file will be logged.
     * @throws IllegalStateException if not all realm instances are closed.
     */
    public static boolean deleteRealm(RealmConfiguration configuration) {
        return BaseRealm.deleteRealm(configuration);
    }

答案 4 :(得分:-1)

您在评论中提到的例外情况:

try (Realm realm = Realm.getInstance(realmConfig)) {
    realm.beginTransaction();
    //your operations here
    realm.commitTransaction();
} catch (Exception e) {
    realm.cancelTransaction();
}