[Firebase] [Android] 실시간으로 Firestore 업데이트 내용 읽어오기

최승원·2021년 4월 24일
0
post-thumbnail

앞선 포스팅에서 설명했듯이 이번에 구현하고자 하는 기능은
- PC에서 python 코드로 Firstore에 접근해서 Firestore 필드의 내용을 수정해준다.
- 모바일에서는 Firestore의 필드 내용이 수정될 때마다 실시간으로 반영한다.

이번에는 이중에서 아래의 기능을 구현해보고자 한다.


final DocumentReference docRef = db.collection("[컬렉션 이름]").document("[문서 이름]");
        docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot snapshot,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Log.w(TAG, "Listen failed.", e);
                    return;
                }

                if (snapshot != null && snapshot.exists()) {
                    Log.d(TAG, "Current data: " + snapshot.getData());
                    TextView tv = (TextView) findViewById(R.id.isMaskDefective);
                    tv.setText(snapshot.getData().get("[필드 이름]").toString());

                } else {
                    Log.d(TAG, "Current data: null");
                }
            }
        });

생각보다 구현이 쉬운 편이었는데 공식문서가 매우 잘되어있었음..
Cloud Firestore 실시간 업데이트 수신 대기 공식 문서

profile
문의 사항은 메일로 부탁드립니다🙇‍♀️

0개의 댓글