【问题标题】:How to update a particular row in realm table android如何更新领域表android中的特定行
【发布时间】:2017-09-19 09:58:00
【问题描述】:

我有下表,其中包含PrimaryKey。我在表中插入了一些值。现在我需要更新特定行中的特定值。我有一排gameTypePuzzle,我需要更新该行中的currentLevel。但我无法做到这一点。

GamesDetails表:

public class GamesDetail extends RealmObject {
    @PrimaryKey
    private String gameType;
    private int currentLevel;
    private int totalLevel;
    private int totalCoins;
    private int currentBadge;

    public String getGameType() {
        return gameType;
    }

    public void setGameType(String gameType) {
        this.gameType = gameType;
    }

    public int getCurrentLevel() {
        return currentLevel;
    }

    public void setCurrentLevel(int currentLevel) {
        this.currentLevel = currentLevel;
    }

    public int getTotalLevel() {
        return totalLevel;
    }

    public void setTotalLevel(int totalLevel) {
        this.totalLevel = totalLevel;
    }

    public int getTotalCoins() {
        return totalCoins;
    }

    public void setTotalCoins(int totalCoins) {
        this.totalCoins = totalCoins;
    }

    public int getCurrentBadge() {
        return currentBadge;
    }

    public void setCurrentBadge(int currentBadge) {
        this.currentBadge = currentBadge;
    }
}

这是我尝试更新表中特定行的内容:

final GamesDetail puzzleGameDetail = realm.where(GamesDetail.class).equalTo("gameType","Puzzle").findFirst();
                    final int[] nextLevel = {puzzleGameDetail.getCurrentLevel()};

                    realm.executeTransactionAsync(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            puzzleGameDetail.setCurrentLevel(++nextLevel[0]);
                            realm.copyToRealmOrUpdate(puzzleGameDetail);
                        }
                    }, new Realm.Transaction.OnSuccess() {
                        @Override
                        public void onSuccess() {
                            Log.e(TAG, "Done");
                        }
                    }, new Realm.Transaction.OnError() {
                        @Override
                        public void onError(Throwable error) {
                            Log.e(TAG,error.getMessage());
                        }
                    });

但是值没有得到更新,我收到以下错误:

Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.

如何更新表中特定行中的特定值?

【问题讨论】:

    标签: android realm


    【解决方案1】:

    当调用executeTransactionAsync 时,execute 块将在后台线程中运行,从该线程访问的任何 Realm 对象都需要在该线程上从 Realm 实例创建/查询,这是execute 的参数。

    将您的发现 GamesDetail 查询移到 execute 块中,其余的将正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 2013-02-20
      • 2012-04-05
      • 2014-08-25
      相关资源
      最近更新 更多