无法清除数据或将数据添加到列表-UnsupportedOperationException

时间:2018-10-22 15:17:59

标签: java android

我一直在使用搜索功能,它将使我能够在RecyclerView中搜索数据。单击搜索图标时,我的应用程序崩溃。经过调试后,我发现了问题,似乎无法清除或将信息添加到新列表中。

AdapterClass.java

public class JobAdapter extends RecyclerView.Adapter<JobAdapter.ViewHolder> implements Filterable {

    private OnJobClickListener mListener;
    private List<Job> jobs;
    private List<Job> jobsListFiltered;

    private static final String LOG_TAG = JobAdapter.class.getName();


    public interface OnJobClickListener {
        void onJobClick(Job job);
    }

    public void setOnItemClickListener(OnJobClickListener listener) {
        mListener = listener;
    }

    // Provide a reference to the views for each data item
    // Provide access to all the views for a data item in a view holder
    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView jobTitle;
        public TextView companyName;
        public TextView datePosted;
        public ImageView companyLogo;
        public View layout;


        public ViewHolder(View itemView) {
            super(itemView);
            layout = itemView;
            jobTitle = layout.findViewById(R.id.textView_job_title);
            companyName = layout.findViewById(R.id.textView_company_name);
            datePosted = layout.findViewById(R.id.textView_date);
            companyLogo = layout.findViewById(R.id.imageViewLogo);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mListener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            Job currentJob = jobs.get(position);
                            mListener.onJobClick(currentJob);
                        }
                    }
                }
            });
        }
    }


    // Job constructor
    public JobAdapter(List<Job> job, OnJobClickListener listener) {
        jobs = job.subList(1, job.size());
        this.mListener = listener;
        jobsListFiltered = new ArrayList<>(job);
    }

    // Create new views (invoked by the layout manager)
    @Override
    public JobAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.job_item_row, parent, false);

        // set the view's size, margins, paddings and layout parameters
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Get element from the dataset at this position
        // Replace the contents of the view with that element
        Job currentJob = jobs.get(position);

        String mJobTitle = currentJob.getJobTitle();
        holder.jobTitle.setText(mJobTitle);

        String mCompanyName = currentJob.getCompanyName();
        holder.companyName.setText(mCompanyName);

        Context context = holder.datePosted.getContext();

        Date mDatePosted = currentJob.getDatePosted();
        String dateFormat = formatDayMonth(context, mDatePosted);
        holder.datePosted.getContext();
        holder.datePosted.setText(dateFormat);

        String mCompanyLogo = currentJob.getCompanyLogo();
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.drawable.ic_launcher_foreground)
                .circleCrop();
        Glide.with(context)
                .load(mCompanyLogo)
                .apply(requestOptions)
                .into(holder.companyLogo);
    }

        @Nullable
        public static String formatDayMonth (@NonNull Context context, @Nullable Date date){
            if (date == null) {
                return null;
            }

            SimpleDateFormat sdf = new SimpleDateFormat(
                    context.getString(R.string.format_date),
                    Locale.US);
            return sdf.format(date);
        }

        public int getItemCount () {
            return (jobs != null) ? jobs.size() : 0;
        }

    @Override
    public Filter getFilter() {
        return jobFilter;
    }

    private Filter jobFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<Job> filteredList = new LinkedList<>();

            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(jobsListFiltered);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();

                for (Job job : jobsListFiltered) {
                    if (job.getJobTitle().toLowerCase().contains(filterPattern)) {
                        filteredList.add(job);
                    }
                }
            }

            FilterResults results = new FilterResults();
            results.values = filteredList;

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            jobs.clear();
            jobs.addAll((LinkedList)results.values);
            notifyDataSetChanged();
        }
    };

}

错误:

E/AndroidRuntime: FATAL EXCEPTION: main Process: packagename, PID: 17390 java.lang.UnsupportedOperationException at java.util.AbstractList.remove(AbstractList.java:161) at java.util.AbstractList$Itr.remove(AbstractList.java:374) at java.util.AbstractList.removeRange(AbstractList.java:571) at java.util.SubList.removeRange(AbstractList.java:668) at java.util.AbstractList.clear(AbstractList.java:234) at packagename.JobAdapter$1.publishResults(JobAdapter.java:178) at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

到目前为止,我已经尝试了thread中的建议,但这些建议似乎不适用于我的情况。 任何帮助将不胜感激;)

1 个答案:

答案 0 :(得分:1)

请显示调用JobAdapter构造函数的代码。

在JobAdapter构造函数中,您正在使用List.subList创建一个由原始列表支持的子列表视图。这样,您的子列表将继承后备列表上的所有属性(例如不变性)。

堆栈跟踪清楚地表明您正在尝试清除一个无法清除的列表,我只能认为这是因为它是不可变的。

要解决此问题,您可以像这样从JobAdapter构造函数的子列表中创建一个新的ArrayList:

jobs = new ArrayList<>(job.subList(1, job.size()));