마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

리사이클러뷰 notifyDataSetChanged 질문

0 추천

detailviewitem_favrite_imageview 를 누르면 +1 카운트를 하고 이미지가 변경되도록 하고싶습니다.

현재 변경은 되는데, 바로 변경 되는게 아니라 다른 곳을 들어갔다가 다시 원래 페이지로 돌가가면 변경됩니다.

클릭과 동시에 이미지를 변경하도록 하고싶은데 어떻게 해야하나요..?

 

public class Frag1 extends Fragment {
    private View view;
    private FirebaseFirestore firestore;

    private RecyclerView detailviewfragment_recyclerview;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    ArrayList<ContentDTO> contentDTOs = new ArrayList<>();
    ArrayList<String> contentUidList = new ArrayList<>();

    String uid ;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag1,container,false);
        firestore = FirebaseFirestore.getInstance();

        uid = FirebaseAuth.getInstance().getCurrentUser().getUid();


        detailviewfragment_recyclerview = view.findViewById(R.id.detailviewfragment_recyclerview);
        detailviewfragment_recyclerview.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false);
        detailviewfragment_recyclerview.setLayoutManager(layoutManager);

        adapter = new DetailViewRecyclerViewAdapter(contentDTOs);
        detailviewfragment_recyclerview.setAdapter(adapter);

        return view;

    }

    public class DetailViewRecyclerViewAdapter extends RecyclerView.Adapter<DetailViewRecyclerViewAdapter.ViewHolder>{




        public DetailViewRecyclerViewAdapter(ArrayList<ContentDTO> contentDTOs) {


            firestore.collection("images").orderBy("timestamp").get()
                    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                        @Override
                        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                            contentDTOs.clear();
                            contentUidList.clear();
                            try{
                                for(DocumentSnapshot snapshot : queryDocumentSnapshots.getDocuments()){
                                    ContentDTO item = snapshot.toObject(ContentDTO.class);
                                    contentDTOs.add(item);
                                    contentUidList.add(snapshot.getId());
                                }
                            }catch (Exception e){

                            }

                            notifyDataSetChanged();
                        }
                    });
        }
        @NonNull
        @Override
        public DetailViewRecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_detail,parent,false);
            ViewHolder holder= new  ViewHolder(view);



            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull DetailViewRecyclerViewAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            holder.detailviewitem_profile_textview.setText(contentDTOs.get(position).getUserId());
            Glide.with(holder.itemView)
                    .load(contentDTOs.get(position).getImageUri())
                    .into(holder.detailviewitem_profile_imageview_content);
            holder.detailviewitem_explain_textview.setText(contentDTOs.get(position).getExplain());
            holder.detailviewitem_favoritecounter_textview.setText("Likes "+contentDTOs.get(position).getFavoriteCount());
            Glide.with(holder.itemView)
                    .load(contentDTOs.get(position).getImageUri())
                    .into(holder.detailviewitem_profile_image);

//이미지 변경 부분
            if(contentDTOs.get(position).getFavorites().containsKey(uid)){
                holder.detailviewitem_favrite_imageview.setImageResource(R.drawable.ic_baseline_favorite_24);
            }else{
                holder.detailviewitem_favrite_imageview.setImageResource(R.drawable.ic_baseline_favorite_border_24);

            }holder.detailviewitem_favrite_imageview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    favoriteEvent(position);


                }
            });

        }
        @Override
        public int getItemCount() {
            return contentDTOs.size();
        }


        public class ViewHolder extends RecyclerView.ViewHolder{
            ImageView detailviewitem_profile_image;
            TextView detailviewitem_profile_textview;
            ImageView detailviewitem_profile_imageview_content;
            TextView detailviewitem_favoritecounter_textview;
            TextView detailviewitem_explain_textview;
            ImageView detailviewitem_favrite_imageview;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                this.detailviewitem_profile_image = itemView.findViewById(R.id.detailviewitem_profile_image);
                this.detailviewitem_profile_textview = itemView.findViewById(R.id.detailviewitem_profile_textview);
                this.detailviewitem_profile_imageview_content = itemView.findViewById(R.id.detailviewitem_profile_imageview_content);
                this.detailviewitem_favoritecounter_textview = itemView.findViewById(R.id.detailviewitem_favoritecounter_textview);
                this.detailviewitem_explain_textview = itemView.findViewById(R.id.detailviewitem_explain_textview);
                this.detailviewitem_favrite_imageview = itemView.findViewById(R.id.detailviewitem_favrite_imageview);
            }
        }



        private void favoriteEvent(int position){
            DocumentReference tsDoc = firestore.collection("images").document(contentUidList.get(position));

            firestore.runTransaction(new Transaction.Function<Void>() {

                @Nullable
                @Override
                public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {

                    ContentDTO contentDTO =  transaction.get(tsDoc).toObject(ContentDTO.class);

                    if(contentDTO.getFavorites().containsKey(uid)){
                        contentDTO.setFavoriteCount(contentDTO.getFavoriteCount() -1);
                        contentDTO.getFavorites().remove(uid);


                    }else{
                        contentDTO.setFavoriteCount(contentDTO.getFavoriteCount() +1);
                        contentDTO.getFavorites().put(uid,true);
                    }
                    transaction.set(tsDoc,contentDTO);




                    return null;
                }
            });
        }
    }
}

 

개미1 (620 포인트) 님이 4월 18일 질문

1개의 답변

0 추천

코드를 한군데 너무 몰아넣지 마시고 적절하게 분리하세요.  DetailViewRecyclerViewAdapter는 별도의 파일로 분리하시는게 아주 보편적인 코드입니다. 그리고 Adapter안에서 파어이베이스 처리를 하지 마시고 Frag1에 처리하시는 것도 아주 보편적인 코드입니다.

더 정리할 부분이 있긴하지만 아래와 비슷하게 분리하시면 될 것 같구요. 

public class ContentItem {
    private String docId;
    private boolean favourite;
    //contentDTOs 필드 포함, 생성자에 contentDTOs 필드 추가

    public ContentItem(String docId, boolean favourite, ...) {
        this.docId = docId;
        this.favourite = favourite;
        ...
    }

    public String getDocId() {
        return docId;
    }

    public boolean isFavourite() {
        return this.favourite;
    }

    @drawableRes
    public int getFavouriteDrwableId() {
        return isFavourite() ? R.drawable.ic_baseline_favorite_24 : R.drawable.ic_baseline_favorite_border_24;
    }
    

    public static List<ContentItem> from(QuerySnapshot querySnapshot) {
        List<ContentItem> results = new ArrayList<>();
        for(DocumentSnapshot snapshot : querySnapshot.getDocuments()){
            results.add(ContentItem.from(snapshot));
        }
        return results;
    }
    
    public static ContentItem from(DocumentSnapshot snapshot) {
        ContentDTO dto = snapshot.toObject(ContentDTO.class);
        ContentItem result = ContentItem(
            snapshot.getId(),
            item.getFavorites().containsKey(uid),
            ...
        );
        return result;
    }
}

public class DetailsFragment extends Fragment {
    private View view;
    private FirebaseFirestore firestore;

    private RecyclerView.Adapter adapter;
    private String uid ;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag1,container,false);
        return view;
    }

    @Override
    public void onViewCreated (View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        setupFirebase();
        setupViews();
        fetchDetails();
    }

    private void setupFirebase() {
        firestore = FirebaseFirestore.getInstance();
        uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    }

    private void setupViews() {
        RecyclerView recyclerView = view.findViewById(R.id.detailviewfragment_recyclerview);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(layoutManager);
 
        adapter = new DetailViewAdapter();
        adapter.setListener(new object: DetailViewAdapter() {
            @Override
            public void onFavouriteClicked(ContentItem item) {
                favouriteClicked(item);
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void fetchDetails() {
        firestore.collection("images")
            .orderBy("timestamp").get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot querySnapshot) {
                    detailsFetched(querySnapshot);
                }
            });
        }
    }

    private void detailsFetched(QuerySnapshot querySnapshot) {
        try{
            List<ContentItem> contentItems = ContentItem.from(querySnapshot);
            adapter.submitList(contentItems);
        }catch (Exception e){
           // TODO : handleRemoteError(e);
        }
    }

    private void favouriteClicked(ContentItem item){
        DocumentReference docRef = firestore.collection("images")
                .document(contentUidList.get(position));
        firestore.runTransaction(new Transaction.Function<Void>() {
            @Nullable
            @Override
            public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {
                ContentDTO contentDTO =  transaction.get(docRef).toObject(ContentDTO.class);
                if(contentDTO.getFavorites().containsKey(uid)){
                    contentDTO.setFavoriteCount(contentDTO.getFavoriteCount() -1);
                    contentDTO.getFavorites().remove(uid);
                } else {
                    contentDTO.setFavoriteCount(contentDTO.getFavoriteCount() +1);
                    contentDTO.getFavorites().put(uid, true);
                }
                transaction.set(docRef, contentDTO);
                return null;
            }
        });
    }
}           
                

public class DetailViewAdapter extends RecyclerView.Adapter<DetailViewAdapter.ViewHolder>{
    interface Listener {
        void onFavouriteClicked(ContentItem item);
    }

    private Listener listener;
    private final List<ContentItem> items = new ArrayList<>();

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    public void submitList(List<ContentItem> items) {
        this.items = items;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public DetailViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_detail,parent,false);
        ViewHolder holder = new ViewHolder(view, listener);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull DetailViewAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        holder.bind(items.get(position));
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private ImageView profile_image;
        private TextView profile_textview;
        private ImageView profile_imageview_content;
        private TextView favoritecounter_textview;
        private TextView explain_textview;
        private ImageView favrite_imageview;

        private final DetailViewAdapter.Listener listener;

        public ViewHolder(@NonNull View itemView, DetailViewAdapter.Listener listener) {
            super(itemView);
            this.profile_image = itemView.findViewById(R.id.detailviewitem_profile_image);
            this.profile_textview = itemView.findViewById(R.id.detailviewitem_profile_textview);
            this.profile_imageview_content = itemView.findViewById(R.id.detailviewitem_profile_imageview_content);
            this.favoritecounter_textview = itemView.findViewById(R.id.detailviewitem_favoritecounter_textview);
            this.explain_textview = itemView.findViewById(R.id.detailviewitem_explain_textview);
            this.favrite_imageview = itemView.findViewById(R.id.detailviewitem_favrite_imageview);
            this.listener = listener;
        }
    }

    private void bind(item: ContentItem) {
        profile_textview.setText(item.getUserId());

        String imageUrl = item.getImageUri();
        loadImage(profile_imageview_content, imageUrl); 
        loadImage(profile_image, imageUrl);               
        
        explain_textview.setText(item.getExplain());
        favoritecounter_textview.setText("Likes " + item.getFavoriteCount());

        //이미지 변경 부분
        favrite_imageview.setImageResource(item.getFavouriteDrwableId());
        favrite_imageview.setOnClickListener(v -> {
            if (listener != null) {
                listener.onFavouriteClicked(item)
            }
        });
    }
 
    private void loadImage(ImageView imageView, String url) {
        Glide.with(itemView)
                .load(url)
                .into(imageView);
    }
}

 

아이템 갱신은 즐겨찾기 숫자를 변경하신 다음, fetchDetails를 호출하거나 아니면 fetchDetails 에 addSnapshortListener를 사용하시면 되지 않을까 생각합니다.

spark (139,480 포인트) 님이 4월 18일 답변
spark님이 4월 18일 수정
...