计数Kotlin上的Android Room行

时间:2019-11-23 20:09:54

标签: android kotlin android-livedata

学习Kotlin,适当的应用程序结构和内容...再次... :) 所以我有以下内容:

  • 存储库
  • ViewModel

Dao代码

print("welcome to hangman")
number_left = 1
answer_input = input()
answer = []

for i in range(len(answer_input)):
    answer.append(answer_input[i])
print(answer)
guessed = []
number_of_underscores = 0
length = len(answer)
for i in range(length):
    guessed.append("_")
while True:
    for i in guessed:
        if i != "_":
            number_of_underscores = number_of_underscores + 1
            if number_of_underscores == length:
                break

    guess = input("Guess your letter")
    actual_number_left = answer.count(guess) + 1
    if guess not in answer:
        print("incorrect")
        output_answer = " ".join(guessed)
        print(output_answer)
    else:
        if answer.count(guess) > 1:
            while number_left != 0:                
                position = answer.index(guess)
                answer[position] = "_"
                number_left = actual_number_left - 1
                guessed[position] = guess
                if number_left == 0:                    
                    output_answer = " ".join(guessed)
                    print(output_answer)
                    break
        else:
            for i in answer:
                if i == guess:
                    index_number = answer.index(guess)
                    guessed[index_number] = guess
                    output_answer = " ".join(guessed)
                    print(output_answer)
                    break     

存储库

    @Dao
interface ItemDao {
    @Query("SELECT * from item_table ORDER BY Name ASC")
    fun getSortedItems(): LiveData<List<Item>>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insert(item: Item)

    @Query("DELETE FROM item_table")
    suspend fun deleteAll()

}

ViewModel

class ItemRepository (private val itemDao: ItemDao) {


    val allItems: LiveData<List<Item>> = itemDao.getSortedItems()

    suspend fun insert(item: Item) {
        itemDao.insert(item)
    }

}

我需要获取表中的当前行数,而我在想这样的事情: 添加到Dao

class ItemViewModel(application: Application) : AndroidViewModel(application) {

    private val repository: ItemRepository
    val allItems: LiveData<List<Item>>


    init {
        val itemsDao = ItemDataBase.getDatabase(application, viewModelScope).itemDao()
        repository = ItemRepository(itemsDao)
        allItems = repository.allItems
    }


    fun insert(item: Item) = viewModelScope.launch {
        repository.insert(item)
    }

}

,然后在回购中

@Query("SELECT COUNT(name) FROM item_table")
    fun getAmount(): LiveData<Int>

,并且在ViewModel中相同

fun getAmount(): LiveData<Int>{
        return itemDao.getAmount()
    }

但是,我还是应该在Activity中使用观察者来获取此值吗?或者,另一方面,当我从DB以LiveData的形式获取表时,我可以只使用Int吗?

0 个答案:

没有答案