简体   繁体   English

从内部匿名类访问和修改变量

[英]Access and modify a variable from inner anonymous class

I have the following code: 我有以下代码:

boolean gameSuccess = false;
@Override
    public boolean saveMission(final Mission mission) {
        realm = Realm.getInstance(realmConfiguration);

        realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealm(mission);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "onSuccess: mission saved");
                realm.close();
                missionSuccess = true;
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                Log.d(TAG, "onError: mission failed");
                realm.close();
                missionSuccess = false;
            }
        });
        return gameSuccess;
    }

gameSuccess is always false even if onSuccess was called. 即使调用了onSuccess,gameSuccess始终为false。 What is the way to get this done? 完成这项工作的方法是什么?

Async isn't blocking, so your code is wrong. 异步不会阻止,所以您的代码是错误的。 The transaction doesn't happen before the return, but any unspecified time later, which is why it is always false. 交易不会在返回之前发生,而是在任何未指定的时间之后发生,这就是为什么它总是错误的。

You either need to provide a callback to your method or convert the transaction to blocking 您需要提供方法的回调或将事务转换为阻塞

public void saveMission(final Mission mission, Callback callback) {
     realm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealm(mission);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "onSuccess: mission saved");
                realm.close(); 
                callback.onSuccess();
            }
        }, new Realm.Transaction.OnError() {
            @Override
            public void onError(Throwable error) {
                Log.d(TAG, "onError: mission failed");
                realm.close();
                callback.onError();
            }
        });
}

or 要么

realm.executeTransaction(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM