시나리오는 다음과 같습니다.
Dao :
@Dao
interface TipDAO {
@Query("SELECT * FROM tip_table")
fun getAll(): LiveData<List<Tip>>
@Query("SELECT * FROM tip_table WHERE title LIKE :title")
fun findByName(title: String): Tip
@Query("SELECT * from tip_table ORDER BY title DESC")
fun getAlphabetizedTips(): LiveData<List<Tip>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(vararg tip: Tip)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(vararg tips: Tip)
@Delete
suspend fun delete(tip: Tip)
@Query("DELETE FROM tip_table")
suspend fun deleteAll()
저장소:
class TipRepository (private val tipDAO: TipDAO){
// Room executes all queries on a separate thread.
// Observed LiveData will notify the observer when the data has changed.
val allTips: LiveData<List<Tip>> = tipDAO.getAll()
// The suspend modifier tells the compiler that this must be called from a
// coroutine or another suspend function.
suspend fun insert (tip: Tip){
tipDAO.insert(tip)
}
fun getAlphabetizedTips (): LiveData<List<Tip>> {
return tipDAO.getAlphabetizedTips()
}
suspend fun delete (tip: Tip) {
tipDAO.delete(tip)
}
모델보기
class TipViewModel (application: Application): AndroidViewModel (application) {
private val repository : TipRepository
val allTips: LiveData<List<Tip>>
init {
val tipDAO = TipRoomDatabase.getDatabase(application).tipDao()
repository = TipRepository(tipDAO)
allTips = repository.allTips
}
fun insert (tip: Tip) = viewModelScope.launch {
repository.insert(tip)
}
fun delete (tip: Tip) = viewModelScope.launch {
repository.delete(tip)
}
fun getAlphabetizedTips () {
//How I can query so I can see the change ????¿¿¿¿
}
}
활동
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_how_to)
val recyclerView: RecyclerView = findViewById (R.id.content)
val adapter = TipListAdapter(this)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.isNestedScrollingEnabled = false
tipViewModel = ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory(this.application))
.get(TipViewModel::class.java)
tipViewModel.allTips.observe(this,
Observer<List<Tip>> { tips ->
// Update the cached copy of the tips in the adapter.
tips?.let { adapter.setTips(tips)} //setTips notify the listener
})
val addButton: Button = findViewById(R.id.how_to_add_bt)
val delButton: Button = findViewById(R.id.how_to_delete_bt)
val sortButton: ImageButton = findViewById(R.id.how_to_sort_bt)
val searchBar: TextView = findViewById(R.id.how_to_search_bar)
addButton.setOnClickListener {
Toast.makeText(this,"ADD", Toast.LENGTH_SHORT).show()
intent = Intent(this, AddActivity::class.java)
startActivityForResult(intent, NEW_TIP_ACTIVITY_REQUEST_CODE)
}
delButton.setOnClickListener {
TipListAdapter.delete = !TipListAdapter.delete //changes a flag
}
sortButton.setOnClickListener {
tipViewModel.getAlphabetizedTips()
}
///more irrelevant code
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (NEW_TIP_ACTIVITY_REQUEST_CODE == requestCode && resultCode == RESULT_OK && data!= null) {
data.let{
val description: String = it.getStringExtra(AddActivity.DESCRIPTION)!!
val title: String = it.getStringExtra(AddActivity.TITLE)!!
val image: String = it.getStringExtra(AddActivity.IMAGE)!!
Toast.makeText(this, "You have created a tip succesfully",Toast.LENGTH_SHORT).show()
val tip = Tip (null,title, image, description)
tipViewModel.insert(tip)
}
} else {
Toast.makeText(this,"The tip was not uploaded correctly",Toast.LENGTH_SHORT).show()
}
}
내가 사용할 때 상황은 LiveData
대한 allTips 에서 모델 는 RecycleView에 올바르게 표시됩니다. 하지만 사용 MutableLiveData
하면 아무것도 표시되지 않습니다. 내 목표는 MutableLiveData
쿼리를 실행하는 데 사용 하는 것이며 관찰자는 recycleview 데이터를 변경하라는 알림을받습니다. 내 질문은 다음과 같습니다.
[편집하다]
모델보기 MutableLiveData
class TipViewModel (application: Application): AndroidViewModel (application) {
private val repository : TipRepository
val allTips: MutableLiveData<List<Tip>>
init {
val tipDAO = TipRoomDatabase.getDatabase(application).tipDao()
repository = TipRepository(tipDAO)
allTips.value = repository.allTips.value
}
fun insert (tip: Tip) = viewModelScope.launch {
repository.insert(tip)
}
fun delete (tip: Tip) = viewModelScope.launch {
repository.delete(tip)
}
fun getAlphabetizedTips () {
//How I can query so I can see the change ????¿¿¿¿
allTips.post(respository.getAlphabetizedTips.value)
}
}
MediatorLiveData
변경 가능 대신 시도
저장소:
class TipRepository (private val tipDAO: TipDAO){
// Room executes all queries on a separate thread.
// Observed LiveData will notify the observer when the data has changed.
val allTips: LiveData<List<Tip>> = tipDAO.getAll()
// The suspend modifier tells the compiler that this must be called from a
// coroutine or another suspend function.
suspend fun insert (tip: Tip){
tipDAO.insert(tip)
}
fun getAlphabetizedTips (): LiveData<List<Tip>> {
return tipDAO.getAlphabetizedTips()
}
suspend fun delete (tip: Tip) {
tipDAO.delete(tip)
}
모델보기
class TipViewModel (application: Application): AndroidViewModel (application) {
private val repository : TipRepository
val allTips = MediatorLiveData<List<Tip>()
init {
val tipDAO = TipRoomDatabase.getDatabase(application).tipDao()
repository = TipRepository(tipDAO)
allTips.addSource(repository.allTips){
this.allTips.value = it
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다