본문 바로가기

Android/note

firebase realtime database 데이터 삭제해도 adapter에 남아있을 때

제목을 어떻게 적어야할지 모르겠다,,

문제를 발견했을 때 내가 검색했던 검색어들은

 

android fireabase realtime database 데이터 삭제

android mvvm repository fireabase data remove

그러면서도 viewmodel과 repository를 잘못 설정한것인가 싶어서

viewmodel, repository도 검색했다

 

아무튼 며칠동안 혼자 해결해보겠다고 앓고있다가

why is not remove data of apdater when remove realtime database of firebase

되도않는 영어로 작성해서 검색했더니

 

나에게 해결방법을 준 stackoverflow

역시 모든 해결책은 여기에 있나보다

 

When I delete a data in firebase, it is deleted from the database, but it is not deleted from the list without going to another

I'm listing Firebase user's favorite words. When the user presses the favButton, it will remove the favorite word. The favorite word is deleted in the database. But the favorite list is not updated

stackoverflow.com


해결 전 / 후

 

해결 방법

 

 

위의 stackoverflow에서 댓글에서 해결법을 얻었다

① onDataChange 안에 breakpoint를 찍어서 원하는 값이 나오는지 확인

② 위에서 확인한 값들이 adapter에 제대로 전달되는지 확인

 

그래서 목록을 조회하는 getFriendList() 안에 있는 onDataChange() 메소드에 breakpoint를 찍었다.

 

 

breakpoint를 찍은 채로 디버깅을 해보면

데이터가 존재할 때에는 아래와 같이 value에 저장된 데이터가 들어있다.

 

 

하지만 데이터를 삭제했을 땐?

 

 

value = null로 null값이 들어오는 것을 확인할 수 있다.

 

근데 사실 이 부분은 fireabase realtime database에서도 확인 할 수 있는 내용인데

이 부분을 놓쳐서 며칠을 삽질했던 것이다.

 

 

내 코드에는

 

override fun onDataChange(snapshot: DataSnapshot) {
    if (snapshot.exists()) {
        val friendList = snapshot.children.map { friendSnapshot ->
            friendSnapshot.getValue(Friend::class.java)!!
        }
        friendListLiveData.postValue(friendList)
    }
}

 

snapshot.exists가 true일 때만 처리를 했고 false일때는 처리를 하지 않았기 때문에 발생한 문제였다는 것을 이제는 보인다.

 

override fun onDataChange(snapshot: DataSnapshot) {
    if (snapshot.exists()) {
        val friendList = snapshot.children.map { friendSnapshot ->
            friendSnapshot.getValue(Friend::class.java)!!
        }
        friendListLiveData.postValue(friendList)
    } else {
        val friendList = emptyList<Friend>()
        friendListLiveData.postValue(friendList)
    }
}

 

false일 때에는 emptyList를 생성하여 반환하였다.

 

며칠을 삽질하고 있었는데 드디어 해결되었다.

thanks.... frank..

'Android > note' 카테고리의 다른 글

Uni-Directional Architecture  (0) 2022.02.24
[Android] Design Pattern - MVC, MVP, MVVM  (0) 2022.02.10
[kotlin] Kakao Map API 연결  (0) 2022.01.09
[android] 카카오 지도 API가 화면에 보이지 않음  (0) 2021.11.28
[android] Event Bus  (0) 2021.08.21