如何从Recycler View适配器类打开任何类型的文件?

时间:2018-12-19 05:04:52

标签: java android android-intent android-recyclerview recycler-adapter

我要尝试的是成功下载文件后应从文件路径自动打开它,但是现在这里的问题是,当我尝试执行此操作时,我需要从回收者视图适配器类中触发该路径它产生一个异常 看一下我的适配器类: 在这里,我使用的是带有适配器的类,该适配器将基本上从url下载文件,但是当我尝试激发从下载类打开文件的意图时,它只会出错,这是错误的。

public class Filelistadapter extends RecyclerView.Adapter<Filelistadapter.ProjectViewHolder>{
    private String url;

    private ArrayList<Taskmsg> dataList;


    Context mContext;


    public Filelistadapter(ArrayList<Taskmsg> dataList, Context mContext) {
        this.dataList = dataList;
        this.mContext=mContext;

    }

    @Override
    public ProjectViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.file_item, parent, false);
        return new ProjectViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ProjectViewHolder holder, int position) {
        String fname=dataList.get(position).getFilename();
        holder.txtfilename.setText(fname);
        holder.download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                url="http://pms.cloudester.com/task_doc/"+fname;
                new DownloadFile().execute(url);

            }
        });


    }



    @Override
    public int getItemCount() {

        return dataList.size();

    }

    class ProjectViewHolder extends RecyclerView.ViewHolder {

        TextView txtfilename;
        Button download;
        ProjectViewHolder(View itemView) {
            super(itemView);
            txtfilename = (TextView) itemView.findViewById(R.id.tvfilename);
            download=itemView.findViewById(R.id.actionButton);

        }
    }

    private class DownloadFile extends AsyncTask<String, String, String> {

        private ProgressDialog progressDialog;
        private String fileName;
        private String folder;
        private boolean isDownloaded;

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            this.progressDialog = new ProgressDialog(mContext);
            this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            this.progressDialog.setCancelable(false);
            this.progressDialog.show();
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();
                // getting file length
                int lengthOfFile = connection.getContentLength();


                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

                //Extract file name from URL
                fileName = f_url[0].substring(f_url[0].lastIndexOf('/') + 1, f_url[0].length());

                //Append timestamp to file name
                fileName = timestamp + "_" + fileName;

                //External directory path to save file
                folder = Environment.getExternalStorageDirectory() + File.separator + "pms/";

                //Create androiddeft folder if it does not exist
                File directory = new File(folder);

                if (!directory.exists()) {
                    directory.mkdirs();
                }

                // Output stream to write file
                OutputStream output = new FileOutputStream(folder + fileName);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lengthOfFile));


                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();
                return "Downloaded at: " + folder + fileName;
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return "Something went wrong";
        }

        /**
         * Updating progress bar
         */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            progressDialog.setProgress(Integer.parseInt(progress[0]));
        }


        @Override
        protected void onPostExecute(String message) {
            // dismiss the dialog after the file was downloaded
            this.progressDialog.dismiss();

            // Display File path after downloading
            Toast.makeText(mContext,
                    message, Toast.LENGTH_LONG).show();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您有两个错误

在按钮内部单击此按钮,否则将始终获得上一个位置的名称

字符串fname = dataList.get(position).getFilename();

然后在需要时执行所需的方法更改类型

Intent testIntent = new Intent();
    testIntent.setType("application/pdf");
    testIntent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(folder+filename);
    testIntent.setDataAndType(uri, "application/pdf");
    startActivity(testIntent);