If RecyclerView scrolls, then item id changes. How to resolve this?

瘦欲@ 提交于 2019-12-12 07:01:35

问题


This is my PDFListAdapter class method. I have downloaded file locally and save on Sqlite database. But if I scroll my RecyclerView, then I am having different item id. If not scroll RecyclerView then item id is perfect.

The problem is when I scroll down the RecyclerView the item id changes. That is, I can fit one item on the screen at once. When I scroll to the second item, it saves different file and opens different.

public class PDFListAdapter extends RecyclerView.Adapter<PDFListAdapter.MyViewHolder> {

    private ArrayList<NotesResponseInfo> pdfModelClasses;
    Context context;
    static NotesResponseInfo pdfList;
    String final_nav_opt_name;
    ProgressDialog progressDialog;
    String TAG = "PDFListAdapter";
    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder mBuilder;
    int id = 1;
    DatabaseNotes databaseNotes;
    MyViewHolder holder;
    Downloader downloader;
    int deepak =0 ;

    public PDFListAdapter(Context context, ArrayList<NotesResponseInfo> pdfModelClasses, String final_nav_opt_name) {
        this.context = context;
        this.pdfModelClasses = pdfModelClasses;
        this.final_nav_opt_name = final_nav_opt_name;
        databaseNotes = new DatabaseNotes(context);
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView txtBookName, txtBookTitle, txtBookBookDateOFIssue, txtBookCategory, txtDownload;
        LinearLayout layout_open_pdf, layout_download_note_option;
        ImageView imgDownloadNote, imgCancelDownloadNote;
        ProgressBar progress_download_note;
        public MyViewHolder(View view) {
            super(view);
            txtBookName = (TextView) view.findViewById(R.id.txtBookName);
            txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
            txtBookBookDateOFIssue = (TextView) view.findViewById(R.id.txtBookBookDateOFIssue);
            txtBookCategory = (TextView) view.findViewById(R.id.txtBookCategory);
            txtDownload = view.findViewById(R.id.txtDownload);
            layout_open_pdf = (LinearLayout) view.findViewById(R.id.layout_open_pdf);
            layout_download_note_option = (LinearLayout) view.findViewById(R.id.layout_download_note_option);
            imgDownloadNote = (ImageView) view.findViewById(R.id.imgDownloadNote);
            progress_download_note = (ProgressBar) view.findViewById(R.id.progress_download_note);
            imgCancelDownloadNote = (ImageView) view.findViewById(R.id.imgCancelDownloadNote);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_pdf_adapter, parent, false);

        return new MyViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(final MyViewHolder holder1, final int index) {
        final int position = index;
        pdfList = pdfModelClasses.get(position);
        final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
        holder1.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
        holder1.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
        holder1.txtBookBookDateOFIssue.setText(pdfList.getType());
        holder1.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
        if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
            holder1.txtDownload.setVisibility(View.VISIBLE);
            holder1.layout_download_note_option.setVisibility(View.GONE);
        } else {
            holder1.txtDownload.setVisibility(View.GONE);
            holder1.layout_download_note_option.setVisibility(View.VISIBLE);
        }
        holder1.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pdfList = pdfModelClasses.get(position);
                 holder = holder1;
                Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
                Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
                if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
                    DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
                    Intent intent = new Intent(context, PDFResults.class);
                    intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
                    intent.putExtra("from", "database");
                    intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
                    context.startActivity(intent);
                } else {
                    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
                    alertDialog.setTitle("Alert");
                    alertDialog.setCancelable(true);
                    alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
                    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                        public void onClick(DialogInterface dialog, int which) {
                            downloader = new Downloader();
                            new CheckSpace().execute(pdfList.getFileName());
                        }
                    });

                    alertDialog.show();
                }
            }
        });

        holder1.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public void onClick(View v) {
                Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
                Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
                pdfList = pdfModelClasses.get(position);
                deepak =index ;
                holder = holder1;
                if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
                    if (UtilsMethods.isNetworkAvailable(context)) {
                        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
                        if (result == PackageManager.PERMISSION_GRANTED) {
                            downloader = new Downloader();
                            new CheckSpace().execute(pdfList.getFileName());
                        } else {
                            Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
                            PermissionCheck.checkWritePermission(context);
                        }
                    } else {
                        holder.imgDownloadNote.setVisibility(View.GONE);
                        holder.imgCancelDownloadNote.setVisibility(View.GONE);
                        holder.progress_download_note.setVisibility(View.GONE);
                        context.startActivity(new Intent(context, NoInternetActivity.class));
                    }
                }
                else Log.e("","Not in db");
            }
        });

        holder1.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
                Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
                final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
                alertDialog.setTitle("Alert");
                alertDialog.setMessage("Are you sure want to cancel download?");
                alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.hide();
                        downloader.cancel(true);
                    }
                });
                alertDialog.show();
            }
        });
    }

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

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

    private void startSave(final Context context, NotesResponseInfo url) {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        final base_url b = new base_url();
        Retrofit.Builder builder = new Retrofit.Builder().baseUrl(b.BASE_URL);
        Retrofit retrofit = builder.client(httpClient.build()).build();
        AllApis downloadService = retrofit.create(AllApis.class);
        Call<ResponseBody> call = downloadService.downloadFileByUrl(StringUtils.getCroppedUrl(url.getFileName()));
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    mBuilder = new NotificationCompat.Builder(context);
                    downloader.execute(response.body());
                } else {

                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private class Downloader extends AsyncTask<ResponseBody, Integer, Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mBuilder.setContentTitle("Download")
                    .setContentText("Download in progress")
                    .setSmallIcon(R.mipmap.lun);
            mBuilder.setProgress(100, 0, false);
            mNotifyManager.notify(id, mBuilder.build());
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            mBuilder.setContentTitle("Download")
                    .setContentText("Download in progress")
                    .setSmallIcon(R.mipmap.ic_logo);
            mBuilder.setProgress(100, values[0], false);
            mNotifyManager.notify(id, mBuilder.build());
            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            holder.imgDownloadNote.setVisibility(View.VISIBLE);
            holder.imgCancelDownloadNote.setVisibility(View.GONE);
            holder.progress_download_note.setVisibility(View.GONE);
            mNotifyManager.cancelAll();
        }

        @Override
        protected Integer doInBackground(ResponseBody... params) {

            NotesResponseInfo item = new NotesResponseInfo();

            item = pdfModelClasses.get(deepak);

            ResponseBody body = params[0];
            try {
                URL url = new URL(pdfList.getFileName());
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestProperty("Accept-Encoding", "identity");
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
                ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
                int lenghtOfFile = c.getContentLength();
                Log.w("getContentLength",""+lenghtOfFile);
                File file = wrapper.getDir("PDF", MODE_PRIVATE);
                file = new File(file, pdfList.getSubjectName() + "_" + TimeUtils.getCurrentTimeStamp() + ".pdf");
                FileOutputStream f = new FileOutputStream(file);
                InputStream in = c.getInputStream();
                float finalValue = 0;
                byte[] buffer = new byte[100 * 1024];
                int len1 = 0;
                int progress = 0;
                long total = 0;
                if (!(isCancelled())) {
                    while ((len1 = in.read(buffer)) >0) {
                        if (UtilsMethods.isNetworkAvailable(context)) {
                            f.write(buffer, 0, len1);
                            total += len1;
                            setProgress(Integer.parseInt(("" + (int) ((total * 100) / lenghtOfFile))));

                     /*   progress += len1;finalValue = (float) progress/body.contentLength() *100;
                        setProgress((int) finalValue);
                        mBuilder.setProgress((int) finalValue,0,false);*/

                        } else {
                            File file1 = new File(file.getPath());
                            file1.delete();
                            cancel(true);

                        }
                    }
                    new DownloadedNotesDataBase(context).addDonloadedNotesToDatabase(file.getPath(), pdfList);
                } else {
                    File file1 = new File(file.getPath());
                    file1.delete();
                    holder.imgDownloadNote.setVisibility(View.VISIBLE);
                    holder.imgCancelDownloadNote.setVisibility(View.GONE);
                    holder.progress_download_note.setVisibility(View.GONE);
                    Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
                }

            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (ProtocolException e1) {
                e1.printStackTrace();
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            mBuilder.setContentText("Download complete");
            mBuilder.setSmallIcon(R.mipmap.ic_logo);
            mBuilder.setProgress(100, 100, false);
            mNotifyManager.notify(id, mBuilder.build());
            holder.txtDownload.setVisibility(View.VISIBLE);

            holder.imgDownloadNote.setVisibility(View.GONE);
            holder.imgCancelDownloadNote.setVisibility(View.GONE);
            holder.progress_download_note.setVisibility(View.GONE);
        }

        private void setProgress(int progress) {
            mBuilder.setContentText("Downloading...")
                    .setContentTitle(progress + "%")
                    .setSmallIcon(R.mipmap.ic_logo)
                    .setOngoing(true)
                    .setContentInfo(progress + "%")
                    .setProgress(100, progress, false);
            mNotifyManager.notify(id, mBuilder.build());
            holder.progress_download_note.setProgress(progress);
        }
    }

    public class CheckSpace extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String file_size = "";
            URL url = null;
            try {
                url = new URL(params[0]);
                URLConnection urlConnection = url.openConnection();
                urlConnection.connect();
                int fileSize = urlConnection.getContentLength();
                file_size = UtilsMethods.generateFileSize(fileSize);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return file_size;
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        protected void onPostExecute(String result) {
            if (UtilsMethods.compareSpace(result)) {
                final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
                alertDialog.setTitle("Alert");
                alertDialog.setMessage("Download this PDF of size " + result + " ?");
                alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.hide();
                        holder.imgDownloadNote.setVisibility(View.GONE);
                        holder.imgCancelDownloadNote.setVisibility(View.VISIBLE);
                        holder.progress_download_note.setVisibility(View.VISIBLE);
                        startSave(context, pdfList);
                    }
                });
                alertDialog.show();
            } else {
                final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
                alertDialog.setTitle("Alert");
                alertDialog.setMessage("Unable to download file. Storage space is not available");
                alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.hide();
                    }
                });
                alertDialog.show();
            }
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}

回答1:


I have modified your onBindViewHolder function. The changes are following.

  1. Declared the pdfList variable as final and used it everywhere. It is not necessary to get the pdfList from the pdfModelClasses, each time you use it.
  2. The holder variable is removed, as it is not actually necessary. The holder1 is used everywhere.
  3. There are some changes with the visibility of the buttons. Check holder1.imgDownloadNote.setOnClickListener.

I have found no other problem in your onBindViewHolder. Please let me know if the modified code works.

@Override
public void onBindViewHolder(final MyViewHolder holder1, final int index) {
    final int position = index;

    // Declare the variable here and make it final. 
    final PDFList pdfList = pdfModelClasses.get(position);

    final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);

    holder1.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
    holder1.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
    holder1.txtBookBookDateOFIssue.setText(pdfList.getType());
    holder1.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));

    if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
        holder1.txtDownload.setVisibility(View.VISIBLE);
        holder1.layout_download_note_option.setVisibility(View.GONE);
    } else {
        holder1.txtDownload.setVisibility(View.GONE);
        holder1.layout_download_note_option.setVisibility(View.VISIBLE);
    }

    holder1.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // I have the desired pdfList already, no need to get that again.
            // pdfList = pdfModelClasses.get(position);

            // Assigning to holder is not necessary.
            // holder = holder1;

            Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
            Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
            if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
                DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
                Intent intent = new Intent(context, PDFResults.class);
                intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
                intent.putExtra("from", "database");
                intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
                context.startActivity(intent);
            } else {
                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
                alertDialog.setTitle("Alert");
                alertDialog.setCancelable(true);
                alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
                alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                    public void onClick(DialogInterface dialog, int which) {
                        downloader = new Downloader();
                        new CheckSpace().execute(pdfList.getFileName());
                    }
                });

                alertDialog.show();
            }
        }
    });

    holder1.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onClick(View v) {
            Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
            Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
            pdfList = pdfModelClasses.get(position);
            deepak =index ;

            // We don't need the reassignment.
            // holder = holder1;

            if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
                if (UtilsMethods.isNetworkAvailable(context)) {
                    int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (result == PackageManager.PERMISSION_GRANTED) {
                        downloader = new Downloader();
                        new CheckSpace().execute(pdfList.getFileName());

                        // Make them visible when the internet connection is there. 
                        holder1.imgDownloadNote.setVisibility(View.VISIBLE);
                        holder1.imgCancelDownloadNote.setVisibility(View.VISIBLE);
                        holder1.progress_download_note.setVisibility(View.VISIBLE);
                    } else {
                        Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
                        PermissionCheck.checkWritePermission(context);
                        holder1.imgDownloadNote.setVisibility(View.GONE);
                        holder1.imgCancelDownloadNote.setVisibility(View.GONE);
                        holder1.progress_download_note.setVisibility(View.GONE);
                    }
                } else {
                    holder1.imgDownloadNote.setVisibility(View.GONE);
                    holder1.imgCancelDownloadNote.setVisibility(View.GONE);
                    holder1.progress_download_note.setVisibility(View.GONE);
                    context.startActivity(new Intent(context, NoInternetActivity.class));
                }
            } else { 
                // Put proper visibility everywhere. 
                holder1.imgDownloadNote.setVisibility(View.GONE);
                holder1.imgCancelDownloadNote.setVisibility(View.GONE);
                holder1.progress_download_note.setVisibility(View.GONE);
                Log.e("","Not in db");
            }
        }
    });

    holder1.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
            Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
            final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
            alertDialog.setTitle("Alert");
            alertDialog.setMessage("Are you sure want to cancel download?");
            alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    alertDialog.hide();
                    downloader.cancel(true);
                }
            });
            alertDialog.show();
        }
    });
}

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

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


来源:https://stackoverflow.com/questions/49584607/if-recyclerview-scrolls-then-item-id-changes-how-to-resolve-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!