使用list.add(0,arrayObj)在arraylist android中添加最后一项的元素覆盖

时间:2017-07-25 05:44:34

标签: android android-recyclerview

我正在使用recyclerview显示一些服务器数据,这将显示更新的数据到顶部,并且更新列表我在每个15秒后调用一个方法,第一次我req服务器它的工作正常但在那之后当我更新列表每个服务器数据15秒,并尝试将新项目添加到顶部并显示,它不能正常工作,更具体的问题是,最后一项是pic,更新的数据是文本,它在输出中合并。

enter image description here

enter image description here

看图片。最后一项是webadeal pic,当我用数据“test”更新列表时,它在UI中合并。

这是我的代码:

片段:

oncreateview(){
     //adapter initialization
        linearLayoutManager=new LinearLayoutManager(context_newsfeed);

        recyclerView.setLayoutManager(linearLayoutManager);

            newsFeedAdapter = new NewsFeedAdapter(newsFeedClassArrayList, context_newsfeed);

            recyclerView.setAdapter(newsFeedAdapter);
            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(context_newsfeed, linearLayoutManager.getOrientation());
            recyclerView.addItemDecoration(dividerItemDecoration);
            if (WebViewActivity.getScrollPosition() != null) {
                recyclerView.scrollToPosition(Integer.valueOf(WebViewActivity.getScrollPosition()));
            }
            }
//below are two method. first is called for once which working well but second is for 15 sec each.

void updateNewsFeed(){

//        newsFeedClassArrayList=new ArrayList<>();

        postId_ArrayList=new ArrayList<>();

//   allArrayList=new ArrayList<>();

        try {
            newsFeedQuery= URLEncoder.encode("userId","UTF-8")+"="+URLEncoder.encode(ServiceClass.getDefaults("USERID",context_newsfeed),"UTF-8")
                    + "&" + URLEncoder.encode("updatePostId","UTF-8")+"="+ URLEncoder.encode(lastPostId,"UTF-8");

            if(asyncTaskClass==null || asyncTaskClass.getStatus()== AsyncTask.Status.FINISHED) {

                asyncTaskClass = new AsyncTaskClass(context_newsfeed, new AsyncTaskResult() {
                    @Override
                    public void AsyncTaskResult(String result) throws JSONException {

                        Log.v("ResDUpdate", result);
                        swipeRefreshLayout.setRefreshing(false);

                            JSONObject jsonObject = new JSONObject(result);
                            JSONArray jsonArray = jsonObject.getJSONArray("result");
                        if (jsonArray.length() > 0){
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject tmpjsonObject = new JSONObject(jsonArray.optString(i));
                            newsFeedClass_updated = new NewsFeedClass();

                            if (tmpjsonObject.getString("funpage").equals("1")) {

                                newsFeedClass_updated.setUserId_friends(tmpjsonObject.getString("user_id"));
                                newsFeedClass_updated.setPostId(tmpjsonObject.getString("id"));

                            /*if(postId==(null) || postId.equals("")|| Integer.valueOf(postId)<Integer.valueOf(tmpjsonObject.getString("id")))
                            {
                                ServiceClass.setDefaults("postId",tmpjsonObject.getString("id"),context_newsfeed);
                            }*/
                                // make post id arrayList
                                ContactListClass contactListClass_postId = new ContactListClass();
                                contactListClass_postId.setContactName(tmpjsonObject.getString("id"));   //post id
                                contactListClass_postId.setContactNumber(String.valueOf(i));  //index no
                                postId_ArrayList.add(contactListClass_postId);

                                //updated post id
                                if (Integer.valueOf(tmpjsonObject.getString("id")) > Integer.valueOf(lastPostId)) {
                                    lastPostId = tmpjsonObject.getString("id");
                                }

                                newsFeedClass_updated.setUserPicUrl_newsFeed(tmpjsonObject.getString("profile_pic"));
                                newsFeedClass_updated.setUserProName(tmpjsonObject.getString("author_name"));
                                newsFeedClass_updated.setStatus(tmpjsonObject.getString("post_content"));
                                newsFeedClass_updated.setLikeCount(tmpjsonObject.getString("post_likes"));
                                newsFeedClass_updated.setWowCount(tmpjsonObject.getString("post_wows"));
                                newsFeedClass_updated.setBlehCount(tmpjsonObject.getString("post_blehs"));
                                newsFeedClass_updated.setDislikeCount(tmpjsonObject.getString("post_dislikes"));
                                newsFeedClass_updated.setTimeStamp(tmpjsonObject.getString("post_time"));
                                newsFeedClass_updated.setVideo("");
                                newsFeedClass_updated.setYoutubeVideo("");
                                newsFeedClass_updated.setIsSharedValue(tmpjsonObject.getString("is_shared"));
                                newsFeedClass_updated.setIsFriend(tmpjsonObject.getString("is_by_friend"));



                                //post attachment // here image if more than one
                                imageList_FunPost = new ArrayList<>();
                                if (tmpjsonObject.getJSONArray("attachments").length() > 0) {

                                    JSONArray jsonArray_attachment = tmpjsonObject.getJSONArray("attachments");
                                    for (int i_attachment = 0; i_attachment < jsonArray_attachment.length(); i_attachment++) {
                                        JSONObject jsonObject_attachment = new JSONObject(jsonArray_attachment.optString(i_attachment));
                                        ContactListClass contactListClass = new ContactListClass();
                                        contactListClass.setContactName(InfoSetClass.getBaseUrl() + jsonObject_attachment.getString("file_path"));// post picture url save
                                        contactListClass.setContactNumber((tmpjsonObject.getString("id")));
                                        imageList_FunPost.add(contactListClass);
                                    }
                                    newsFeedClass_updated.setImageList(imageList_FunPost);
                                }
                                Log.v("ResDfsd","tes "+ newsFeedClassArrayList);
                                newsFeedClassArrayList.add(0,newsFeedClass_updated);// but as i need to show last item at top thats why i do this and prb raise.
                                Log.e("newsFeedClassArrayList","after adding new data from api response "+ newsFeedClassArrayList);

                            }
                        }
                            //that is fine, may be problem is else where
//                        allArrayList.addAll(newsFeedClassArrayList);
//                            newsFeedAdapter.swapList(newsFeedClassArrayList);
 //                       newsFeedAdapter.notifyItemInserted(0);
                         newsFeedAdapter.notifyDataSetChanged();
                        //set list to service class
                        ServiceClass.setPostId_list(postId_ArrayList);
                    }
                        Log.v("ResDfsd","tesdf "+ newsFeedClassArrayList);
                    }
                });
                asyncTaskClass.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "POST", "mobileApi/getUpdatePost", newsFeedQuery);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

适配器:

@Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {

        holder.rightArrowViewPagerId.setVisibility(View.GONE);
        holder.leftArrowViewPagerId.setVisibility(View.GONE);
        currentPageNo=holder.viewPager.getCurrentItem();
//        mediaPlayer=new MediaPlayer();
        newsFeedClass=newsFeedClassArrayList.get(position);
        Picasso.with(context).load(InfoSetClass.getBaseUrl()+newsFeedClass.getUserPicUrl_newsFeed()).centerCrop().transform(new CircleTransform()).resize(50,50).into(holder.userProPicImg);

        holder.userProNameTvId.setText(newsFeedClass.getUserProName());

        if(newsFeedClass.getLikeCount()!=null)
            totalLikeWow=Integer.valueOf(newsFeedClass.getLikeCount())+Integer.valueOf(newsFeedClass.getBlehCount()) +Integer.valueOf(newsFeedClass.getDislikeCount())+Integer.valueOf(newsFeedClass.getWowCount());
        holder.likeCountTv.setText(String.valueOf(totalLikeWow));

        if(newsFeedClass.getCommentCount()!=null)
        holder.commentCountTv.setText(String.valueOf(newsFeedClass.getCommentCount()));

        if(newsFeedClass.getShareCount()!=null){
            holder.shareCountTv.setText(String.valueOf(newsFeedClass.getShareCount()));
        }

        if(!((newsFeedClass.getStatus().toLowerCase().contains(".jpg"))||(newsFeedClass.getStatus().toLowerCase().contains(".png"))||
                (newsFeedClass.getStatus().toLowerCase().contains("https"))||(newsFeedClass.getStatus().toLowerCase().contains("http")))) {
            holder.statusTv.setText(Html.fromHtml(newsFeedClass.getStatus()));
//            holder.viewPager.setVisibility(View.GONE);
        }
        else {

            holder.newsFeedImageView.loadData(newsFeedClass.getStatus(), "text/html", null);
            holder.newsFeedImageView.getSettings().setJavaScriptEnabled(true);
            WebSettings webSettings = holder.newsFeedImageView.getSettings();
            webSettings.setGeolocationEnabled(true);
            webSettings.getJavaScriptEnabled();
            webSettings.getMediaPlaybackRequiresUserGesture();
//          holder.viewPager.setVisibility(View.GONE);

        }

        //image slider
        if(newsFeedClass.getImageList()!=null){

            holder.viewPager.setVisibility(View.VISIBLE);
            viewPagerAdapter=new ViewPagerAdapter(context,newsFeedClass.getImageList());
            holder.viewPager.setAdapter(viewPagerAdapter);

            if(viewPagerAdapter.getCount()>1){
                holder.rightArrowViewPagerId.setVisibility(View.VISIBLE);
            }
            if(holder.viewPager.getCurrentItem()>1){
                holder.leftArrowViewPagerId.setVisibility(View.VISIBLE);
            }
            if(holder.viewPager.getCurrentItem()==0){
                holder.leftArrowViewPagerId.setVisibility(View.GONE);
            }
            if(holder.viewPager.getCurrentItem()==viewPagerAdapter.getCount()){
                holder.rightArrowViewPagerId.setVisibility(View.GONE);
            }
            holder.rightArrowViewPagerId.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(holder.viewPager.getCurrentItem()<viewPagerAdapter.getCount()){
                        if(holder.viewPager.getCurrentItem()<=viewPagerAdapter.getCount()){
                            holder.viewPager.setCurrentItem(currentPageNo++,true);
                        }
                    }
                }
            });
//            holder.viewPagerArrowIndicator.bind(holder.viewPager);
//            holder.viewPagerArrowIndicator.setArrowIndicatorRes(R.drawable.arrow_left_black_24dp,R.drawable.arrow_right_black_24dp);
            viewPagerAdapter.notifyDataSetChanged();

        }else {
//            holder.viewPager.setVisibility(View.GONE);
            relativeLayout.setVisibility(View.GONE);
        }

        holder.timeStampTvId.setText(newsFeedClass.getTimeStamp());


    }

1 个答案:

答案 0 :(得分:0)

Recycle View将重用该项,因此我们应该始终在bindView中设置值,但是您没有正确设置某些值,所以这样做,

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {

        holder.rightArrowViewPagerId.setVisibility(View.GONE);
        holder.leftArrowViewPagerId.setVisibility(View.GONE);
        currentPageNo=holder.viewPager.getCurrentItem();
//        mediaPlayer=new MediaPlayer();
        newsFeedClass=newsFeedClassArrayList.get(position);
        Picasso.with(context).load(InfoSetClass.getBaseUrl()+newsFeedClass.getUserPicUrl_newsFeed()).centerCrop().transform(new CircleTransform()).resize(50,50).into(holder.userProPicImg);

        holder.userProNameTvId.setText(newsFeedClass.getUserProName());

        if(newsFeedClass.getLikeCount()!=null)
            totalLikeWow=Integer.valueOf(newsFeedClass.getLikeCount())+Integer.valueOf(newsFeedClass.getBlehCount()) +Integer.valueOf(newsFeedClass.getDislikeCount())+Integer.valueOf(newsFeedClass.getWowCount());
        holder.likeCountTv.setText(String.valueOf(totalLikeWow));

        if(newsFeedClass.getCommentCount()!=null) {
            holder.commentCountTv.setText(String.valueOf(newsFeedClass.getCommentCount()));
        } else {
            holder.commentCountTv.setText("");
        }

        if(newsFeedClass.getShareCount()!=null){
            holder.shareCountTv.setText(String.valueOf(newsFeedClass.getShareCount()));
        } else {
            holder.shareCountTv.setText("");
        }

        if(!((newsFeedClass.getStatus().toLowerCase().contains(".jpg"))||(newsFeedClass.getStatus().toLowerCase().contains(".png"))||
                (newsFeedClass.getStatus().toLowerCase().contains("https"))||(newsFeedClass.getStatus().toLowerCase().contains("http")))) {
            holder.statusTv.setText(Html.fromHtml(newsFeedClass.getStatus()));
            holder.newsFeedImageView.setVisibility(View.GONE);
//            holder.viewPager.setVisibility(View.GONE);
        }
        else {
            holder.newsFeedImageView.setVisibility(View.VISIBLE);
            holder.statusTv.setText("");

            holder.newsFeedImageView.loadData(newsFeedClass.getStatus(), "text/html", null);
            holder.newsFeedImageView.getSettings().setJavaScriptEnabled(true);
            WebSettings webSettings = holder.newsFeedImageView.getSettings();
            webSettings.setGeolocationEnabled(true);
            webSettings.getJavaScriptEnabled();
            webSettings.getMediaPlaybackRequiresUserGesture();
//          holder.viewPager.setVisibility(View.GONE);

        }

        //image slider
        if(newsFeedClass.getImageList()!=null){
            relativeLayout.setVisibility(View.VISIBLE);
            holder.viewPager.setVisibility(View.VISIBLE);

            ViewPagerAdapter viewPagerAdapter=new ViewPagerAdapter(context,newsFeedClass.getImageList());
            holder.viewPager.setAdapter(viewPagerAdapter);

            if(viewPagerAdapter.getCount()>1){
                holder.rightArrowViewPagerId.setVisibility(View.VISIBLE);
            }
            if(holder.viewPager.getCurrentItem()>1){
                holder.leftArrowViewPagerId.setVisibility(View.VISIBLE);
            }
            if(holder.viewPager.getCurrentItem()==0){
                holder.leftArrowViewPagerId.setVisibility(View.GONE);
            }
            if(holder.viewPager.getCurrentItem()==viewPagerAdapter.getCount()){
                holder.rightArrowViewPagerId.setVisibility(View.GONE);
            }
            holder.rightArrowViewPagerId.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(holder.viewPager.getCurrentItem()<viewPagerAdapter.getCount()){
                        if(holder.viewPager.getCurrentItem()<=viewPagerAdapter.getCount()){
                            holder.viewPager.setCurrentItem(currentPageNo++,true);
                        }
                    }
                }
            });
//            holder.viewPagerArrowIndicator.bind(holder.viewPager);
//            holder.viewPagerArrowIndicator.setArrowIndicatorRes(R.drawable.arrow_left_black_24dp,R.drawable.arrow_right_black_24dp);
            viewPagerAdapter.notifyDataSetChanged();

        }else {
            holder.viewPager.setVisibility(View.GONE);
            relativeLayout.setVisibility(View.GONE);
        }

        holder.timeStampTvId.setText(newsFeedClass.getTimeStamp());


    }