如何更新realm表android中的特定行

时间:2017-09-19 09:58:00

标签: android realm

我的下表中包含PrimaryKey。我在表格中插入了一些值。现在我需要更新特定行中的特定值。我的gameType行为Puzzle,我需要更新行中的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.

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

1 个答案:

答案 0 :(得分:3)

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

GamesDetail块内移动您的查找execute查询,其余功能正常。