我使用下面的代码块将一个Customer对象添加到Realm,成功添加了对象。但是,当项目插入完成或失败时,我试图通过Toast消息提供反馈。
@Override
public void addCustomer(final Customer customer) {
Realm insertRealm = Realm.getDefaultInstance();
insertRealm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm backgroundRealm) {
long id = customerPrimaryKey.incrementAndGet();
customer.setId(id);
backgroundRealm.copyToRealm(customer);
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.d(TAG, "Customer Added");
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
Log.d(TAG, error.getMessage());
}
});
insertRealm.close();
}
上面的代码块成功插入了对象,但是没有达到成功和错误回调,因为我关闭了用于启动它的Realm。如果我不关闭Realm,则会达到onError和onSuccess回调,但是,应用程序将崩溃,因为Realm已泄露。
我试图更新代码以关闭回调中的Realm,但它仍然崩溃。
public void addCustomer(final Customer customer) {
Realm insertRealm = Realm.getDefaultInstance();
insertRealm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm backgroundRealm) {
long id = customerPrimaryKey.incrementAndGet();
customer.setId(id);
backgroundRealm.copyToRealm(customer);
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.d(TAG, "Customer Added");
insertRealm.close();
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
Log.d(TAG, error.getMessage());
insertRealm.close();
}
});
}
我的问题是,是否有办法在Activity / Fragment LifeCycle之外关闭Realm?我可以保留Realm的全局单例并注入使用它的类吗?
更新 - 添加了StackTrack
11-13 06:59:07.545 2249-2257/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/metrics.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
11-13 06:59:07.549 2249-2257/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/help_responses.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
11-13 06:59:07.557 2249-2257/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
答案 0 :(得分:0)
在onSuccess和onError回调中关闭Realm工作,我正在努力解决的问题是泄漏的现有SQLiteOpenHelper类。从任何对SQLite的引用中清除项目,一切正常。这个代码块再次起作用。
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.d(TAG, "Customer Added");
insertRealm.close();
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
Log.d(TAG, error.getMessage());
insertRealm.close();
}
});