notifyDataSetChanged()不刷新适配器

6

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

如果适配器列表的大小大于1,则一切正常运行,即如果我的recyclerview已经显示了一行,则列表刷新得很好。但是,如果列表大小从0到1,则我的适配器通知数据集更改停止工作。recyclerview上不显示任何数据。我不知道为什么它不起作用。

Recyclerview Class:

     @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));
        }
    }
}

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


请检查这行代码是否有问题:this.notifyItemRangeInserted(0, candidates.size() - 1); - random
3
方法中的第二个参数是项数,但如果您的候选项集大小为一,则减一意味着项数为零。尝试将第二个参数更改为candidates.size()。 - random
@random 还是不起作用。 - young_08
尝试在getItemCount()内部记录mDataset.size(),并查看它是否在您期望刷新RecyclerView时每次都更新。 - random
@random 但我只在RecyclerView类中接收到我的广播,然后获取它的实例,我认为这可能不是正确的方式。 - young_08
显示剩余10条评论
7个回答

1
BroadcastReceiveronReceive()中调用数据加载任务。
    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);
        }
    }

希望那能行!

0

我不确定你在JobAdapter.class中的clearApplications()方法是在哪里使用。 但是,看起来是有问题的。在for循环中,你每次都试图移除索引为0的值,而不是索引'i'。希望这能帮到你。


0

将此更改为:

mMyBroadcastReceiver = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        // Here you can refresh your listview or other UI
                        recycleAdapter.addItems(SingleTon.getInstance()
                                         .getInfoArrayList());

                        // I'm assuming your "SingleTon.getInstance().getInfoArrayList()" is the received data.
                    }

在你的适配器

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());
}

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;
}

已经根据建议做出了所有更改,但仍然无法正常工作。 - young_08
您可以更新您的问题。请将新代码放在 更新: 标题下方。 - MrOnyszko

0
根据你的代码,我们需要一个变量列表来存储你的信息数据。
//Declare the info list
private ArrayList<Info> mInfos = new ArrayList<Info>() 

在你的onCreateView()中,将mInfos设置为你的recycleAdapter
recycleAdapter =  new JobAdapter(mInfos, getActivity());
recyclerView.setAdapter(recycleAdapter);

所以,每次您想要设置新的信息列表时,只需将其分配给mInfos并确保清除先前的列表数据以避免重复数据。
mInfos.clear()
mInfos.addAll(SingleTon.getInstance().getInfoArrayList());
//refresh data
recycleAdapter.notifyDataSetChanged();

-1

当您使用自定义适配器时,notifyDatasetChange() 不会从适配器外部调用,因此请在适配器中创建 addItem 函数并将新列表添加到适配器列表中,然后调用 notifyDataSetChanged。

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

    }

    notifyDataSetChanged();
}

如果您查看我贴出的适配器代码,您会发现我正是这样做的。 - young_08

-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
}

希望这个能够运行!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接