notifyDataSetChanged()没有刷新适配器

时间:2016-08-09 06:40:10

标签: android android-recyclerview recycler-adapter notifydatasetchanged

我的适配器列表在广播接收器上刷新。

  

如果适配器列表大小大于1,一切正常   意味着如果我的recyclerview已经有一行shwoing然后列出刷新就好了。   但是如果列表大小从0变为1,那么我的适配器会通知数据集   改变停止工作。在recyclerview上没有数据显示。我不知道为什么它不起作用。

Recyclerview类:

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.job_recyclerview, container, false);
getActivity());
        initialise(v);
        init();
        showNoTaskMessage();
        new loadListTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        mMyBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // Here you can refresh your listview or other UI


                SlidingTab.slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
                SlidingTab.slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");;
                SlidingTab.slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");

            }

        };

        try {

            IntentFilter filter = new IntentFilter("newJob");
            LocalBroadcastManager.getInstance(context).registerReceiver(mMyBroadcastReceiver,
                    filter);

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return v;
    }

适配器类:

 public JobAdapter(ArrayList<Info> myDataset, Context context) {
        this.mDataset = myDataset;
        this.mAct = context;
    }

    public void addApplications(ArrayList<Info> candidates) {
        if (this.filterList == null) {
            filterList = new ArrayList<>();
        }
        this.mDataset.clear();
        this.mDataset.addAll(candidates);
        this.filterList.addAll(mDataset);
        this.notifyItemRangeInserted(0, candidates.size() - 1);

    }

    public void clearApplications() {
        int size = this.mDataset.size();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                mDataset.remove(0);
                filterList.remove(0);
            }

            this.notifyItemRangeRemoved(0, size);
        }
    }

    @Override
    public int getItemViewType(int position) {
        return VIEW_NORMAL;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_job_card, parent, false);
        ViewHolder fh = new ViewHolder(v);
        return fh;
    }

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

//        holder.jobPhone.setText(mDataset.get(position).mobileNo);
        holder.jobNumber.setText(mDataset.get(position).jobNumber);
        holder.jobTime.setText(mDataset.get(position).time);
        holder.jobAddress.setText(mDataset.get(position).address);
//        holder.jobInstructionText.setText(mDataset.get(position).spclInstruction);

        if (mDataset.get(position).jobStatus != null && mDataset.get(position).jobStatus.equalsIgnoreCase("Completed")) {
            holder.endsat.setText("Submitted at");
            holder.jobTime.setText(mDataset.get(position).completedOnString);
            holder.jobTimeLeft.setVisibility(View.INVISIBLE);
            holder.timerImage.setVisibility(View.INVISIBLE);

        } else {
            if (mDataset.get(position).status.equalsIgnoreCase("Active")) {
                holder.jobTimeLeft.setText(mDataset.get(position).appointmentTime);
            } else {
                holder.jobTimeLeft.setText("-" + mDataset.get(position).appointmentTime);
            }
        }

        holder.jobLayout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SingleTon.getInstance().setWorkDescHolder(mDataset.get(position).descHolder);
                FragmentManager fragmentManager = ((FragmentActivity) mAct).getSupportFragmentManager();
                FragmentTransaction ft = ((FragmentActivity) mAct).getSupportFragmentManager().beginTransaction();
                ft.setCustomAnimations(R.anim.glide_fragment_horizontal_in, R.anim.glide_fragment_horizontal_out);
                ft.replace(R.id.content_frame1, new DetailsFragment(), "persondetails");
                ft.addToBackStack("persondetails");

                // Start the animated transition.
                ft.commit();

            }
        });


    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView jobNumber, jobTimeLeft, jobStatus, jobAddress, jobEmail, jobPhone, timeTimer, jobInstructionText, jobTime, endsat;
        private ImageView timerImage;
        private FrameLayout frameLayout;
        private CardView cardView;
        private LayoutRipple jobLayout1;

        public ViewHolder(View v) {
            super(v);
            this.jobNumber = (TextView) v.findViewById(R.id.job_number);
            this.jobTime = (TextView) v.findViewById(R.id.job_time);
            this.jobTimeLeft = (TextView) v.findViewById(R.id.job_timertext);
            this.timerImage = (ImageView) v.findViewById(R.id.timerimage);
            this.cardView = (CardView) v.findViewById(R.id.card_view);
//            this.jobStatus = (TextView) v.findViewById(R.id.job_status);
            this.jobAddress = (TextView) v.findViewById(R.id.job_addresstext);
//            this.jobInstructionText = (TextView) v.findViewById(R.id.instruction_text);
//            this.jobLayout = (LayoutRipple)v.findViewById(R.id.job_cardLayout);
            this.jobLayout1 = (LayoutRipple) v.findViewById(R.id.cardLayout1);
            this.endsat = (AppCompatTextView) v.findViewById(R.id.endsat);
            this.jobNumber.setTypeface(Utils.RegularTypeface(mAct));
            this.jobAddress.setTypeface(Utils.RegularTypeface(mAct));
            this.jobTimeLeft.setTypeface(Utils.RegularTypeface(mAct));
            this.jobTime.setTypeface(Utils.RegularTypeface(mAct));
        }
    }
}

请帮我查找错误或其他方法。谢谢

6 个答案:

答案 0 :(得分:1)

onReceive()

BroadcastReceiver内调用数据加载任务
    mMyBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Here you can refresh your listview or other UI
           new loadListTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

            SlidingTab.slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
            SlidingTab.slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");;
            SlidingTab.slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");

        }

    };

并在适配器类中进行以下更改。

   public void addApplications(ArrayList<Info> candidates) {
        if (this.filterList == null) {
            filterList = new ArrayList<>();
        }
        this.mDataset.clear();
        this.mDataset.addAll(candidates);
        this.filterList.addAll(mDataset);
        this.notifyItemRangeInserted(0, candidates.size());

    }

    public void clearApplications() {
        int size = this.mDataset.size();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                mDataset.remove(i);
                filterList.remove(i);
            }

            this.notifyItemRangeRemoved(0, size);
        }
    }

希望有效!

答案 1 :(得分:0)

更改此内容:

public void addItems(List<Info> itemsList) {
    // This check could be avoided if you declared your mDataset final
    if(mDataset == null) {
        mDataset = new ArrayList<>();
    }

    int prevSize = mDataset.size();
    mDataset.addAll(itemsList);
    notifyItemRangeInserted(prevSize, itemsList.size());
}

适配器

ul li {
    height: 180px;
    width: 180px;
    background: #f6304c;
    display: block;
    color: #ffffff;
    text-align: center;
    margin: 2% 0 0 30%;
    padding: 50px 0;
}

答案 2 :(得分:0)

this.notifyItemRangeInserted(0, candidates.size() - 1);尝试这样的事情后,你不应该调用notifyDataSetChanged():

将此方法放入适配器类

public void setData(ArrayList<Info> infos) {
   this.mDataset = infos;
   notifyDataSetChanged();
}

并将其称为:

ArrayList<Info> list = SingleTon.getInstance().getInfoArrayList().isEmpty();
if (list != null && !list.isEmpty()) {
    recycleAdapter.setData(list);
}

在适配器中更正此方法

@Override
public int getItemCount() {
    return mDataset != null && !mDataset.isEmpty() ? mDataset.size() : 0;
}

答案 3 :(得分:0)

我不确定您在JobAdapter.class中使用clearApplications()的位置。 但是,这似乎是错误的。在for循环中,您试图每次删除索引0处的值而不是索引&#39; i&#39;。希望这会有所帮助。

答案 4 :(得分:-1)

当你使用自定义适配器时,然后没有从那个适配器外部调用notifyDatasetChange(),所以在适配器中创建addItem函数并在适配器列表中添加新的List并调用notifyDataSetChanged

public void addItem(List<Model> list) {
    if (lit != null) {
        clear();
        adapterList.addAll(list);

    }

    notifyDataSetChanged();
}

答案 5 :(得分:-1)

在您的recyclerview类中进行更改。

//Change condition ">1" to "!=null"

if (SingleTon.getInstance().getInfoArrayList().size() != null) {
recycleAdapter.addApplications(SingleTon.getInstance().getInfoArrayList());
recycleAdapter.notifyDataSetChanged();

然后在适配器中进行更改。

public void addApplications(ArrayList<Info> candidates) {
    if (this.filterList == null) {
        filterList = new ArrayList<>();
    }
    this.mDataset.clear();
    this.mDataset.addAll(candidates);
    this.filterList.addAll(mDataset);
    this.notifyItemRangeInserted(0, mDataset.size()); //notify to mDataset
}

希望这会奏效!