LiveData는 recyle보기에서 작동하지만 MutableLiveData는 작동하지 않습니다. 왜?

아가 피토 갈라 트와 베르나 트

시나리오는 다음과 같습니다.

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 데이터를 변경하라는 알림을받습니다. 내 질문은 다음과 같습니다.

  • 뷰 모델에서 내가 만드는 각 쿼리에 대한 LiveData allTips 값을 어떻게 변경할 수 있습니까? 즉 : getAlphabetizedTips, getTip (title) 등
  • 다음과 같이 조각 코드로 MutableLiveData가 작동하지 않는 이유는 무엇입니까?

[편집하다]

모델보기 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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Validate 함수는 ValidationTextBox에서는 작동하지만 FilteringSelect에서는 작동하지 않습니다. 왜?

분류에서Dev

데스크톱에서는 잘 작동하지만 Android에서는 작동하지 않습니다. 왜?

분류에서Dev

정규식은 PHP에서 작동하지만 Erlang에서는 작동하지 않습니다. 왜?

분류에서Dev

서블릿으로 작동하지만 Java 클래스로는 작동하지 않습니다. 왜?

분류에서Dev

왜`echo`는 작동하지만`openssl`에 파이프 할 때`cat`은 작동하지 않습니다.

분류에서Dev

VS Code IntelliSense는 Unity에서 작동하지 않습니다. 왜?

분류에서Dev

PHP에서는 왜 작동하지 않습니다

분류에서Dev

왜 display : flex는 <body>에서는 작동하지만 <html> 태그에서는 작동하지 않습니까?

분류에서Dev

왜 Duration.new가 Int에서 작동하지만 Rat에서는 작동하지 않습니까?

분류에서Dev

RTSP 스트림은 파이썬에서는 작동하지 않지만 VLC에서는 작동합니다. 왜?

분류에서Dev

.asp 및 .aspx에서 정확히 동일한 콘텐츠 아톰 피드 형식 : 하나는 작동하지만 하나는 작동하지 않습니다. 왜?

분류에서Dev

EaselJS에서 스테이지에 추가. 하나는 작동하지만 하나는 작동하지 않습니다. 왜?

분류에서Dev

반동적 할당 코드는 C ++에서는 작동하지만 C에서는 작동하지 않습니다. 왜 그런가요?

분류에서Dev

왜 봄 보안 permitAll는 () OAuth2.0에 작동하지 않습니다?

분류에서Dev

Docker-compose는 작동하지만 Dockerfile을 사용하는 Docker는 작동하지 않습니다. 왜?

분류에서Dev

새 줄에서 분해는 "\ n"에서는 작동하지만 PHP_EOL에서는 작동하지 않습니다. 왜?

분류에서Dev

내 시간 테이블 js는 작동하지만 입력 상자에서 초기 값을 얻을 때 작동하지 않습니다. 왜?

분류에서Dev

UIPanGesture는 작동하지만 UITapGesture는 UIView에서 작동하지 않습니다.

분류에서Dev

PHP에서 작동하지만 PHPUnit에서는 작동하지 않습니다.

분류에서Dev

#include <iostream.h>는 turboc ++에서는 잘 작동하지만 Visual Studio에서는 잘 작동하지 않습니다. 왜?

분류에서Dev

#include <iostream.h>는 turboc ++에서는 잘 작동하지만 Visual Studio에서는 잘 작동하지 않습니다. 왜?

분류에서Dev

부트 스트랩 그리드는 bootply에서는 제대로 작동하지만 html에서는 작동하지 않습니다. 왜 그런가요?

분류에서Dev

왜 스파크 dataframe 캐시는 여기에 작동하지 않습니다

분류에서Dev

다른 시트에 인쇄하는데 왜 작동하지 않습니까?

분류에서Dev

왜 clean.doLast는 작동하지 않지만 clean.doFirst는 gradle에서 잘 작동합니까?

분류에서Dev

jQuery Animation은 작동하지만 Safari에서는 작동하지 않습니다.

분류에서Dev

var 1 개는 작동하지만 1 개는 작동하지 않습니다. 왜?

분류에서Dev

별도의 애니메이션이 작동하지만 Storyboard는 작동하지 않습니다. 왜?

분류에서Dev

CGRectContainsPoint는 다른보기에서 작동하지 않습니다.

Related 관련 기사

  1. 1

    Validate 함수는 ValidationTextBox에서는 작동하지만 FilteringSelect에서는 작동하지 않습니다. 왜?

  2. 2

    데스크톱에서는 잘 작동하지만 Android에서는 작동하지 않습니다. 왜?

  3. 3

    정규식은 PHP에서 작동하지만 Erlang에서는 작동하지 않습니다. 왜?

  4. 4

    서블릿으로 작동하지만 Java 클래스로는 작동하지 않습니다. 왜?

  5. 5

    왜`echo`는 작동하지만`openssl`에 파이프 할 때`cat`은 작동하지 않습니다.

  6. 6

    VS Code IntelliSense는 Unity에서 작동하지 않습니다. 왜?

  7. 7

    PHP에서는 왜 작동하지 않습니다

  8. 8

    왜 display : flex는 <body>에서는 작동하지만 <html> 태그에서는 작동하지 않습니까?

  9. 9

    왜 Duration.new가 Int에서 작동하지만 Rat에서는 작동하지 않습니까?

  10. 10

    RTSP 스트림은 파이썬에서는 작동하지 않지만 VLC에서는 작동합니다. 왜?

  11. 11

    .asp 및 .aspx에서 정확히 동일한 콘텐츠 아톰 피드 형식 : 하나는 작동하지만 하나는 작동하지 않습니다. 왜?

  12. 12

    EaselJS에서 스테이지에 추가. 하나는 작동하지만 하나는 작동하지 않습니다. 왜?

  13. 13

    반동적 할당 코드는 C ++에서는 작동하지만 C에서는 작동하지 않습니다. 왜 그런가요?

  14. 14

    왜 봄 보안 permitAll는 () OAuth2.0에 작동하지 않습니다?

  15. 15

    Docker-compose는 작동하지만 Dockerfile을 사용하는 Docker는 작동하지 않습니다. 왜?

  16. 16

    새 줄에서 분해는 "\ n"에서는 작동하지만 PHP_EOL에서는 작동하지 않습니다. 왜?

  17. 17

    내 시간 테이블 js는 작동하지만 입력 상자에서 초기 값을 얻을 때 작동하지 않습니다. 왜?

  18. 18

    UIPanGesture는 작동하지만 UITapGesture는 UIView에서 작동하지 않습니다.

  19. 19

    PHP에서 작동하지만 PHPUnit에서는 작동하지 않습니다.

  20. 20

    #include <iostream.h>는 turboc ++에서는 잘 작동하지만 Visual Studio에서는 잘 작동하지 않습니다. 왜?

  21. 21

    #include <iostream.h>는 turboc ++에서는 잘 작동하지만 Visual Studio에서는 잘 작동하지 않습니다. 왜?

  22. 22

    부트 스트랩 그리드는 bootply에서는 제대로 작동하지만 html에서는 작동하지 않습니다. 왜 그런가요?

  23. 23

    왜 스파크 dataframe 캐시는 여기에 작동하지 않습니다

  24. 24

    다른 시트에 인쇄하는데 왜 작동하지 않습니까?

  25. 25

    왜 clean.doLast는 작동하지 않지만 clean.doFirst는 gradle에서 잘 작동합니까?

  26. 26

    jQuery Animation은 작동하지만 Safari에서는 작동하지 않습니다.

  27. 27

    var 1 개는 작동하지만 1 개는 작동하지 않습니다. 왜?

  28. 28

    별도의 애니메이션이 작동하지만 Storyboard는 작동하지 않습니다. 왜?

  29. 29

    CGRectContainsPoint는 다른보기에서 작동하지 않습니다.

뜨겁다태그

보관