Sunday, 6 May 2018

How to Download pdf from web in Android

- on Click of download button to add following code

   String pdf_url = array_list.get(position).getpdf();
   if (pdf_url != null && !pdf_url.isEmpty()) {
         new FileDownloading().execute();
   } else {
        Toast.makeText(context, "PDF url is not found",Toast.LENGTH_LONG).show();
   }

//To Add Following Code outside of onCreate() Method.

 class FileDownloading extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            mProgressDialog = new ProgressDialog(TestActivity.this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
          String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "Test/Testwork");
            folder.mkdirs();
            File file = new File(folder, pdf_url);
            try {
                file.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            Downloader.DownloadFile("http://test.domainname.com/test/assets/testpdf/" + pdf_url, file);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
           if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
           }

           Toast.makeText(TestActivity.this, "Download Completed Successfully", Toast.LENGTH_LONG).show();
            showPdf();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
    }

//To Show Downloaded PDF

 public void showPdf() {
        File file = new File(Environment.getExternalStorageDirectory() + "/Test/Testwork/" + pdf_url);
        PackageManager packageManager = getPackageManager();
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, "application/pdf");
        startActivity(intent);
    }

No comments:

Post a Comment