2016-08-05 220 views
0

我的項目後,無法更新UI涉及以下內容:安卓:修改數據庫

1)EditText視圖(inputText),其中假設用戶鍵入一個名稱

2)Button那按下後,將創建一個名稱爲inputText的Person對象,並將該對象保存到領域數據庫。然後它刷新textLog以包含新人的姓名。

3)A「的TextView」(textLog),顯示的境界數據庫中的Person對象的所有名稱的列表。

我的問題是,點擊該按鈕刷新文本日誌節省人物對象到數據庫之前。這意味着只有再次單擊按鈕才能創建新的Person對象,新人員的姓名纔會顯示出來。我想讓用戶界面在之後刷新,將對象保存到數據庫,因此它始終處於最新狀態。以下代碼來自我的MainActivity類。此前我做過Handler handler = new Handler(Looper.getMainLooper());

// called when button is clicked 
private void submit(View view) 
{ 
    final String input = inputText.getText() 
            .toString() 
            .trim(); 
    // asynchronous transaction 
    realm.executeTransactionAsync(realm -> { 
     realm.copyToRealm(new Person(input)); 
     handler.post(this::refresh); 
    }); 
} 

private void refresh() 
{ 
    textLog.setText(realm.where(Person.class) 
         .findAll() 
         .stream() 
         .map(Person::getName) 
         .collect(Collectors.joining("\n"))); 
} 

回答

3

添加Realm.Transaction.OnSuccess()Realm.Transaction.OnError()回調到您的異步交易。當這些方法被調用時,您知道交易已完成,您可以刷新您的UI。

+0

是的,那會解決他的比賽狀態,這比我的回答更具體。 – EJoshuaS

+0

謝謝!這工作! – novice

1

看起來好像你有一個race condition。你做realm.executeTransactionAsync,然後立即做handler.post(this :: refresh); - 不保證他們會按照您希望的順序執行。