Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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",""+lengh

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
128 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...