Как обновить RecyclerView, используя пример LiveData: SeenCounter, CommentCounter, LikeCounter - PullRequest
0 голосов
/ 04 ноября 2019

поэтому я создаю приложение для социальных сетей, используя RecyclerView, оно имеет кнопку «Мне нравится» и счетчик «Мне нравится». Когда MainActivity загружает OnCreate, он нажимает «http // test / getLikeCounter», чтобы отобразить как счетчик в моем RecyclerView, но когда я нажимаю кнопку «Нравится», оно будетнажмите мой собственный API "http // test / setLikeCounter" и добавьте счетчик в мою базу данных, но поскольку он не загружает метод OnCreate снова, он не добавляет свой счетчик лайков в My RecyclerView, как я должен сделать, чтобы обновить мойRecyclerView динамически, когда я нажимаю кнопку «Мне нравится»? Кто-то предлагает использовать LiveData, но как и где его реализовать?

Это когда я нажимаю свой API в OnCreate, он попадает в "http // test / getLikeCounter" в WebAPI.java

webAPI_.rncryptorALLDEWA("Trending");

Я получил данные от попадания в API, преобразовал файл JSON и отправил его обратно в MainActivity с помощью EventBus

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredTrending event) {
    getTrendingMainActivity(event.SendDummyUrutan, event.SendTotalThread, event.SendDummyIDContent, event.SendDummyTitle, event.SendDummyPublishTime, event.SendDummyImageOri, event.SendDummyShortDescription, event.SendDummySeen, event.SendDummyComment, event.SendDummyLike);
}

После этого я вручную установил значение для моего RecyclerView

public void createDummyData1UPDATE(int ReceivedDummyUrutan, int ReceivedTotalThread, String ReceivedDummyIDContent, String ReceivedDummyTitle, String ReceivedDummyPublishTime, String ReceivedDummyImageOri, String ReceivedDummyShortDescription, int ReceivedDummySeen, int ReceivedDummyComment, int ReceivedDummyLike, int ReceivedDummyisComment, int ReceivedDummyisLike, int ReceivedDummyisBookmark) {
    modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(ReceivedDummyIDContent, ReceivedDummyTitle, ReceivedDummyPublishTime, ReceivedDummyImageOri, ReceivedDummyShortDescription, ReceivedDummySeen, ReceivedDummyComment, ReceivedDummyLike, ReceivedDummyisComment, ReceivedDummyisLike, ReceivedDummyisBookmark,"x53535", "No Error"));

    if(ReceivedDummyUrutan ==  ReceivedTotalThread-1){
        ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = new ModelSectionHotTrendingNews();
        modelSectionHotTrendingNewsX.setHeaderTitle("TRENDING NEWS");
        modelSectionHotTrendingNewsX.setAllItemsInSection(modelSingleHotTrendingNews);
        modelSectionHotTrendingNews.add(modelSectionHotTrendingNewsX);

        RecyclerViewSingleHotTrendingNews = v.findViewById(R.id.RecyclerView_Single_HotTrendingNews);
        RecyclerViewSingleHotTrendingNews.setHasFixedSize(true);
        adapterSectionHotTrendingNews = new AdapterSectionHotTrendingNews(getActivity(), modelSectionHotTrendingNews, listenerHotTrendingNews);
        RecyclerViewSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        RecyclerViewSingleHotTrendingNews.setAdapter(adapterSectionHotTrendingNews);
        //Optimized
        RecyclerViewSingleHotLatestNews.setHasFixedSize(true);
        RecyclerViewSingleHotLatestNews.setItemViewCacheSize(20);
    }

}

Когда я нажимаю кнопку «Мне нравится», я хочу обновить свой RecyclerView, чтобы при увеличении «LikeCounter» в базе данных RecyclerView обновлялся динамически

webAPI_.rncryptorCommentLikeBookmark("isLike", modelSingleHotTrendingNews.get(position).getIdcontent(), modelSingleHotTrendingNews.get(position).getIslike());

Это HotSectionAdapter.java

public class AdapterSectionHotTrendingNews extends RecyclerView.Adapter{

private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
private AdapterSingleHotTrendingNews.RecyclerViewClickListener mListener;

public AdapterSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews, AdapterSingleHotTrendingNews.RecyclerViewClickListener mListener) {
    this.mContext = mContext;
    this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
    this.mListener = mListener;
}



@Override
        public SectionHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_section_hottrendingnews, null);
    return new SectionHotTrendingNewsViewHolder(v);
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

    final SectionHotTrendingNewsViewHolder sectionHotTrendingNewsViewHolder = (SectionHotTrendingNewsViewHolder) holder;
    ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);

    //Set
    sectionHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());

    ArrayList singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();

    //WOW
    AdapterSingleHotTrendingNews itemListDataAdapter = new AdapterSingleHotTrendingNews(mContext, singleSectionItems, mListener);
    //WOW

    final String sectionTitle = modelSectionHotTrendingNewsX.getHeaderTitle();
    sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
            new View.OnClickListener() { @Override public void onClick(View v) {
                Toast.makeText(v.getContext(), "click event on more, "+sectionTitle, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mContext, TabMoreHotActivity.class);
                // here you create put extra in new intent not the intent that you created

                intent.putExtra("MoreTrendingNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
                mContext.startActivity(intent);

            } });




    /*Glide.with(mContext)
            .load(feedItem.getImageURL())
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .centerCrop()
            .error(R.drawable.bg)
            .into(feedListRowHolder.thumbView);*/

    //SetRecyclerView
    sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setHasFixedSize(true);
    sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
    sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setAdapter(itemListDataAdapter);
    sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setNestedScrollingEnabled(false);
}

@Override
public int getItemCount() {
    int itemCount = modelSectionHotTrendingNews.size();
    return itemCount;
}

public class SectionHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {

    protected TextView TVSectionTitle;
    protected ImageView BTNHotTrendingNewsMore;
    protected RecyclerView RecyclerViewSectionHotTrendingNews;
    protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;

    public SectionHotTrendingNewsViewHolder(View itemView) {
        super(itemView);

        TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
        BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
        RecyclerViewSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerView_Section_HotTrendingNews);
        RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
    }

}

}

Это HotSingleAdapter.java

public class AdapterSingleHotTrendingNews extends RecyclerView.Adapter{

private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;

private RecyclerViewClickListener mListener;


public AdapterSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews, RecyclerViewClickListener mListener) {
    this.mContext = mContext;
    this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
    this.mListener = mListener;
}

/*public void swap(ArrayList<ModelSingleHotTrendingNews> datas)
{
    modelSingleHotTrendingNews.clear();
    modelSingleHotTrendingNews.addAll(datas);
    notifyDataSetChanged();
}*/

public void swap(ArrayList list){
    if (modelSingleHotTrendingNews != null) {
        modelSingleHotTrendingNews.clear();
        modelSingleHotTrendingNews.addAll(list);
    }
    else {
        modelSingleHotTrendingNews = list;
    }
    notifyDataSetChanged();
}

//Container
@Override
public SingleHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_single_hottrendingnews, null);
    return new SingleHotTrendingNewsViewHolder(v, mListener);
}

//Fill Container with Model Setter Getter
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

    final SingleHotTrendingNewsViewHolder singleHotTrendingNewsViewHolder = (SingleHotTrendingNewsViewHolder) holder;
    final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);

    //Set
    singleHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
    singleHotTrendingNewsViewHolder.TVGameTitle.setText(modelSingleHotTrendingNewsX.getGametitle());
    Glide.with(mContext).load(modelSingleHotTrendingNewsX.getGameimage()).into(singleHotTrendingNewsViewHolder.IMGGameImage);
    /*singleHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());*/

    singleHotTrendingNewsViewHolder.TVSeenCounter.setText(String.valueOf(modelSingleHotTrendingNewsX.getSeencounter()));
    singleHotTrendingNewsViewHolder.TVCommentCounter.setText(String.valueOf(modelSingleHotTrendingNewsX.getCommentcounter()));
    singleHotTrendingNewsViewHolder.TVLikeCounter.setText(String.valueOf(modelSingleHotTrendingNewsX.getLikecounter()));

    if(modelSingleHotTrendingNewsX.getIscomment() == 0){
        singleHotTrendingNewsViewHolder.IMGCommentView.setImageResource(R.drawable.comment_off);
    }else if(modelSingleHotTrendingNewsX.getIscomment() == 1){
        singleHotTrendingNewsViewHolder.IMGCommentView.setImageResource(R.drawable.comment_on);
    }

    if(modelSingleHotTrendingNewsX.getIslike() == 0){
        singleHotTrendingNewsViewHolder.IMGLikeView.setImageResource(R.drawable.heart_off);
    }else if(modelSingleHotTrendingNewsX.getIslike() == 1){
        singleHotTrendingNewsViewHolder.IMGLikeView.setImageResource(R.drawable.heart_on);
    }

    if(modelSingleHotTrendingNewsX.getTrendingnewssaving() == 0) {
        singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
        singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setVisibility(View.GONE);
    }else if(modelSingleHotTrendingNewsX.getTrendingnewssaving() == 1) {
        singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
    }

    singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final int booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();

            final String idcontent = modelSingleHotTrendingNewsX.getIdcontent();

            if (booltrendingnewssaving == 1){
                Toast.makeText(v.getContext(), "Turn Off Saved News " + idcontent, Toast.LENGTH_SHORT).show();
                singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
                modelSingleHotTrendingNewsX.setTrendingnewssaving(0);
                /*updateSavedNewsSaving("update_newssaving", id, false);*/
            } else if(booltrendingnewssaving == 0) {
                Toast.makeText(v.getContext(), "Turn On Saved News " + idcontent, Toast.LENGTH_SHORT).show();
                singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
                modelSingleHotTrendingNewsX.setTrendingnewssaving(1);
                /*updateSavedNewsSaving("update_newssaving", id, true);*/
            }
        }
    });



   /* Glide.with(mContext)
            .load(feedItem.getImageURL())
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .centerCrop()
            .error(R.drawable.bg)
            .into(feedListRowHolder.thumbView);*/

    /*singleHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();

            //Passing Data to GameDescriptionActivity
            Intent intent = new Intent(mContext, GameDetailActivity.class);
            intent.putExtra("ImagePKG",  modelSingleHotTrendingNews.get(position).getGameimage());
            intent.putExtra("NamePKG",  modelSingleHotTrendingNews.get(position).getGamedate());
            intent.putExtra("UrlPKG",  modelSingleHotTrendingNews.get(position).getIdcontent());
            intent.putExtra("DescriptionPKG",  modelSingleHotTrendingNews.get(position).getGametitle());
            mContext.startActivity(intent);
        }
    });*/
}

@Override
public int getItemCount() {
    int itemCount = modelSingleHotTrendingNews.size();
    return itemCount;
}

public class SingleHotTrendingNewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    TextView TVGameDate;
    TextView TVGameTitle;
    ImageView IMGGameImage;

    TextView TVSeenCounter;
    TextView TVCommentCounter;
    TextView TVLikeCounter;

    ImageView IMGSeenView;
    ImageView IMGCommentView;
    ImageView IMGLikeView;

    ImageView ICONHotTrendingNewsSaving;
    private RelativeLayout ROWHotTrendingNewsContainer;

    private RecyclerViewClickListener mListener;


    public SingleHotTrendingNewsViewHolder(View itemView, RecyclerViewClickListener listener) {
        super(itemView);

        TVGameDate = itemView.findViewById(R.id.TV_GameDate);
        TVGameTitle = itemView.findViewById(R.id.TV_GameTitle);
        IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);

        TVSeenCounter = itemView.findViewById(R.id.TV_SeenCounter);
        TVCommentCounter = itemView.findViewById(R.id.TV_CommentCounter);
        TVLikeCounter = itemView.findViewById(R.id.TV_LikeCounter);

        IMGSeenView = itemView.findViewById(R.id.IMG_SeenView);
        IMGCommentView = itemView.findViewById(R.id.IMG_CommentView);
        IMGLikeView = itemView.findViewById(R.id.IMG_LikeView);

        ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
        ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);

        mListener = listener;
        ROWHotTrendingNewsContainer.setOnClickListener(this);
        IMGCommentView.setOnClickListener(this);
        IMGLikeView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ROW_HotTrendingNewsContainer:
                mListener.onRowHotTrendingNewsContainerClick(ROWHotTrendingNewsContainer, getAdapterPosition());
                break;
            case R.id.IMG_CommentView:
                mListener.onRowCommentViewClick(IMGCommentView, getAdapterPosition());
                break;
            case R.id.IMG_LikeView:
                mListener.onRowLikeViewClick(IMGLikeView, getAdapterPosition());
                break;
            default:
                break;
        }
    }
}

public interface RecyclerViewClickListener {
    void onRowHotTrendingNewsContainerClick(View view, int position);
    void onRowCommentViewClick(View view, int position);
    void onRowLikeViewClick(View view, int position);
}

}

Это HotSectionModel.java

public class ModelSectionHotTrendingNews implements Serializable {

private String headerTitle;
private ArrayList<ModelSingleHotTrendingNews> allItemsInSection;

public ModelSectionHotTrendingNews() {
}

public String getHeaderTitle() {
    return headerTitle;
}

public void setHeaderTitle(String headerTitle) {
    this.headerTitle = headerTitle;
}

public ArrayList<ModelSingleHotTrendingNews> getAllItemsInSection() {
    return allItemsInSection;
}

public void setAllItemsInSection(ArrayList<ModelSingleHotTrendingNews> allItemsInSection) {
    this.allItemsInSection = allItemsInSection;
}

}

Это HotSingleModel.java

public class ModelSingleHotTrendingNews implements Serializable {

private String idcontent;
private String gametitle;

private String gamedate;
private String gameimage;
private String gamedescription;

private int seencounter;
private int commentcounter;
private int likecounter;

private int iscomment;
private int islike;
private int trendingnewssaving;

private String value;
private String message;

public ModelSingleHotTrendingNews(String idcontent, String gametitle, String gamedate, String gameimage, String gamedescription, int seencounter, int commentcounter, int likecounter, int iscomment, int islike, int trendingnewssaving, String value, String message) {
    this.idcontent = idcontent;
    this.gametitle = gametitle;
    this.gamedate = gamedate;
    this.gameimage = gameimage;
    this.gamedescription = gamedescription;
    this.seencounter = seencounter;
    this.commentcounter = commentcounter;
    this.likecounter = likecounter;
    this.iscomment = iscomment;
    this.islike = islike;
    this.trendingnewssaving = trendingnewssaving;
    this.value = value;
    this.message = message;
}

public String getIdcontent() {
    return idcontent;
}

public void setIdcontent(String idcontent) {
    this.idcontent = idcontent;
}

public String getGametitle() {
    return gametitle;
}

public void setGametitle(String gametitle) {
    this.gametitle = gametitle;
}

public String getGamedate() {
    return gamedate;
}

public void setGamedate(String gamedate) {
    this.gamedate = gamedate;
}

public String getGameimage() {
    return gameimage;
}

public void setGameimage(String gameimage) {
    this.gameimage = gameimage;
}

public String getGamedescription() {
    return gamedescription;
}

public void setGamedescription(String gamedescription) {
    this.gamedescription = gamedescription;
}

public int getSeencounter() {
    return seencounter;
}

public void setSeencounter(int seencounter) {
    this.seencounter = seencounter;
}

public int getCommentcounter() {
    return commentcounter;
}

public void setCommentcounter(int commentcounter) {
    this.commentcounter = commentcounter;
}

public int getLikecounter() {
    return likecounter;
}

public void setLikecounter(int likecounter) {
    this.likecounter = likecounter;
}

public int getIscomment() {
    return iscomment;
}

public void setIscomment(int iscomment) {
    this.iscomment = iscomment;
}

public int getIslike() {
    return islike;
}

public void setIslike(int islike) {
    this.islike = islike;
}

public int getTrendingnewssaving() {
    return trendingnewssaving;
}

public void setTrendingnewssaving(int trendingnewssaving) {
    this.trendingnewssaving = trendingnewssaving;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

}

1 Ответ

0 голосов
/ 04 ноября 2019

Таким образом, у вас есть событие ответа в MainActivity (с EventBus), которое является правильным местом для добавления вашего элемента (который вы получили от api) в свой список и затем обновите адаптер с помощью notifyDataSetChanged.

у вас есть два адаптера, поэтому в mainActivity вам нужен экземпляр этого адаптера, который вы хотите обновить данными.

adapter.setItems(list); 
adapter.notifyDataSetChanged();

вы также можете добавить новый элемент в свой список, когда вы щелкнете по значку,но если у вас есть какая-то ошибка в БД, ваш список обновится, но вы не синхронизированы с БД, так что лучше сделать это с ответом Evenbus.

...