如果RecyclerView滚动,则项目ID更改.如何解决呢? [英] If RecyclerView scrolls, then item id changes. How to resolve this?

查看:53
本文介绍了如果RecyclerView滚动,则项目ID更改.如何解决呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的PDFListAdapter class方法.我已经在本地下载文件并保存在Sqlite数据库中.但是,如果滚动我的RecyclerView,则表示我有不同的商品ID.如果没有滚动RecyclerView,则项目ID是完美的.

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.

问题是当我向下滚动RecyclerView时,项目ID会更改.也就是说,我可以一次在屏幕上放置一个项目.当我滚动到第二个项目时,它会保存不同的文件并打开不同的文件.

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

推荐答案

我已经修改了您的onBindViewHolder函数.所做的更改如下.

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

  1. 将pdfList变量声明为final,并在各处使用它.每次使用pdfModelClasses时都不必从pdfModelClasses中获取pdfList.
  2. holder变量已删除,因为实际上没有必要. holder1随处可见.
  3. 按钮的可见性进行了一些更改.检查holder1.imgDownloadNote.setOnClickListener.
  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.

我在您的onBindViewHolder中没有发现其他问题.请让我知道修改后的代码是否有效.

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

这篇关于如果RecyclerView滚动,则项目ID更改.如何解决呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆