title: trying a code to download PDF files from but PDF doc is not viewed
body: <p>I'm trying a code to download PDF files from dropbox and after downloading all file in my SD card when clicked on item then PDF book should be loaded in PDF viewer system app.
  But actually by using this code all PDF files are downloading but when PDF app is loaded it shows the error "the document could not be opened" and PDF book is not viewed. Can anyone please help me to sort this problem
  Thanking you in advance
  And i'm not good to post question in efficient manners so i'm really sorry in advance.</p>
  
  <pre><code>  {
  
    MainActivity
    package com.example.mahvishponum.pdfviewer;
  
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Environment;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.Toast;
  
    import java.io.File;
    import java.util.ArrayList;
  
    public class MainActivity extends Activity implements AsyncResponse {
  
    ProgressDialog mProgressDialog;
    ListView list;
    int counter = 0;
  
    ArrayList&lt;DataModel&gt; _data = new ArrayList&lt;&gt;();
    String[] web = {
          "A Textbook of Paediatric Orthopaedics" +
                  "By Nigel S. Broughton",
          "Basic Pediatric Protocols 2013" +
                  "By Ministry of Health Kenya",
          "Basic Pediatric Protocols 2016" +
                  "By Ministry of Health Kenya",
  
          "Current Diagnosis &amp; Treatment" +
                  "PEDIATRICS 19th Edition" +
                  "By McGrawHill LANGE",
          "Hospital Care For Children" +
                  "Pocket Book 2013 Edition" +
                  "By WHO",
          "Textbook of Pediatrics" +
                  "20th Edition" +
                  "By Nelson",
          "The Care and Feeding of Children" +
                  "By L. Emmett Holt. M. D.",
          "Updates on the Management of Severe Acute Malnutrition in Infants 
            and Children" +
                  "Guidelines by WHO"
  };
  String[] titles = {
          "helptextbookpedortho.pdf",
          "BasicPaediatricProcotolsNovember2013.pdf",
          "basicpaediatricprotocols2016.pdf",
          "currentdiagnosisandtreatmentpediatrics.pdf",
          "HospitalCareForChildrenPocketBooks.pdf",
          "NelsonTextbookofPediatrics.pdf",
          "TheCareAndFeedingOfChildren.pdf"
  };
  String[] urls = {
          "https://www.dropbox.com/s/ruds35lyz672jjk/helptextbookpedortho.pdf?dl=1",
          "https://www.dropbox.com/s/n2snurxnvijbqya/BasicPaediatricProcotolsNovember2013.pdf?dl=1",
          "https://www.dropbox.com/s/a1tyrfqd5jhdu7k/basicpaediatricprotocols2016.pdf?dl=1",
          "https://www.dropbox.com/s/hgs7pp97ut3mti3/currentdiagnosisandtreatmentpediatrics.pdf?dl=1",
          "https://www.dropbox.com/s/gvz2805gj39hbc4/HospitalCareForChildrenPocketBooks.pdf?dl=1",
          "https://www.dropbox.com/s/avlj81qctl83otk/NelsonTextbookofPediatrics.pdf?dl=1",
          "https://www.dropbox.com/s/j0e5p9hx6jwf2kg/TheCareAndFeedingOfChildren.pdf?dl=1",
          "https://www.dropbox.com/s/xtfurbb0umbns03/WHOMalnutritionGuidelines.pdf?dl=1"
  };
  Integer[] imageId = {
          R.drawable.book,
          R.drawable.book,
          R.drawable.book,
          R.drawable.book,
          R.drawable.book,
          R.drawable.book,
          R.drawable.book,
          R.drawable.book
  
  };
  
  void filSdCard() {
      mProgressDialog = new ProgressDialog(MainActivity.this);
      mProgressDialog.setIndeterminate(true);
      mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
      mProgressDialog.setCancelable(true);
  
      if (counter &lt; urls.length) {
  
          final Downloader downloadTask = new Downloader(MainActivity.this, mProgressDialog, titles[counter], urls[counter],counter);
          downloadTask.delegate = MainActivity.this;
          downloadTask.execute();
          mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
              @Override
              public void onCancel(DialogInterface dialog) {
                  downloadTask.cancel(true);
              }
          });
  
      }
  
  
  }
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.pdfviewer);
  
      CustomList adapter = new
              CustomList(MainActivity.this, web, imageId);
      list = (ListView) findViewById(R.id.listvid);
      list.setAdapter(adapter);
      list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  
          @Override
          public void onItemClick(AdapterView&lt;?&gt; parent, View view,
                                  int position, long id) {
  
          //give the title according to the title of your disease. every file 
          should have different title.
              if (ifFileExists(titles[position])) {
                  String filePath = Environment.getExternalStorageDirectory() + "/Pediatric/" + "helptextbookpedortho.pdf";
  
                  Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filePath));
                  intent.setDataAndType(Uri.parse(filePath), "application/pdf");
                  startActivity(intent);
              } else {
                  //constructor contains url as well as title with which the file will be saved. make sure you give the same title here and above.
                  //Also look at the url im using. you can see these files on your dropbox and see we have a different url. upload file to dropbox and make it public to get url, then compare it with any
                  //of these urls, you will know what to replace.
                  filSdCard();
  
              }
          }
      });
  }
  
  boolean ifFileExists(String title) {
      String root = Environment.getExternalStorageDirectory().toString();
      File myDir = new File(root + "/Pediatric");
      myDir.mkdirs();
      File file = new File(myDir, title);
      if (file.exists()) {
          return true;
      } else
          return false;
  }
  
  @Override
  public void processFinish(String output) {
      if (output.equals("Success")) {
          if (counter &lt; urls.length) {
              counter = counter + 1;
              filSdCard();
          }
  
      } else {
          if(mProgressDialog.isShowing())
              mProgressDialog.dismiss();
          Toast.makeText(getApplicationContext(), "Some error occured!", Toast.LENGTH_LONG).show();
      }
  
  }
  
  private class DataModel {
      String Title = "";
      String Url = "";
  
      public String getTitle() {
          return Title;
      }
  
      public void setTitle(String title) {
          Title = title;
      }
  
      public String getUrl() {
          return Url;
      }
  
      public void setUrl(String url) {
          Url = url;
      }
  }
  }
  }
  
  
  
  
  
  
  
  
  
  
  
   Downloader.java
   package com.example.mahvishponum.pdfviewer;
  
   import android.app.ProgressDialog;
   import android.content.Context;
   import android.os.AsyncTask;
   import android.os.Environment;
   import android.os.PowerManager;
   import android.widget.Toast;
  
   import java.io.File;
   import java.io.FileOutputStream;
   import java.io.IOException;
   import java.io.InputStream;
   import java.io.OutputStream;
   import java.net.HttpURLConnection;
   import java.net.URL;
  
   /**
   * Created by Mahvish on 6/6/2017.
   */
  
  public class Downloader extends AsyncTask&lt;String, Integer, String&gt; {
  ProgressDialog mProgressDialog;
  private Context context;
  String title="";
  public AsyncResponse delegate = null;
  int counter=0;
  private PowerManager.WakeLock mWakeLock;
  String urlString ="";
  public Downloader(Context context, ProgressDialog mProgressDialog, String 
  title, String urlString, int counter) {
      this.context = context;
      this.mProgressDialog = mProgressDialog;
      this.title = title;
      this.urlString = urlString;
      this.counter = counter;
  
  }
  
  @Override
  protected String doInBackground(String... sUrl) {
      InputStream input = null;
      OutputStream output = null;
      HttpURLConnection connection = null;
      try {
          URL url = new URL(urlString);
          connection = (HttpURLConnection) url.openConnection();
          connection.connect();
  
          // expect HTTP 200 OK, so we don't mistakenly save error report
          // instead of the file
          if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
              return "Server returned HTTP " + connection.getResponseCode()
                      + " " + connection.getResponseMessage();
          }
  
          // this will be useful to display download percentage
          // might be -1: server did not report the length
          int fileLength = connection.getContentLength();
  
          // download the file
          input = connection.getInputStream();
          String root = Environment.getExternalStorageDirectory().toString();
          File myDir = new File(root + "/Pediatric");
          myDir.mkdirs();
          File file = new File(myDir, title);
  
          output = new FileOutputStream(file);
  
          byte data[] = new byte[4096];
          long total = 0;
          int count;
          while ((count = input.read(data)) != -1) {
              // allow canceling with back button
              if (isCancelled()) {
                  input.close();
                  return null;
              }
              total += count;
              // publishing the progress....
              if (fileLength &gt; 0) // only if total length is known
                  publishProgress((int) (total * 100 / fileLength));
              output.write(data, 0, count);
          }
      } catch (Exception e) {
          return e.toString();
      } finally {
          try {
              if (output != null)
                  output.close();
              if (input != null)
                  input.close();
          } catch (IOException ignored) {
          }
  
          if (connection != null)
              connection.disconnect();
      }
      return null;
    }
  
    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      // take CPU lock to prevent CPU from going off if the user
      // presses the power button during download
      PowerManager pm = (PowerManager) 
      context.getSystemService(Context.POWER_SERVICE);
      mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
              getClass().getName());
      mWakeLock.acquire();
      mProgressDialog.setMessage("Downloading "+(counter+1)+"/"+8 );
      mProgressDialog.show();
   }
  
     @Override
     protected void onProgressUpdate(Integer... progress) {
      super.onProgressUpdate(progress);
      // if we get here, length is known, now set indeterminate to false
      mProgressDialog.setIndeterminate(false);
      mProgressDialog.setMax(100);
      mProgressDialog.setSecondaryProgress(30);
  
      mProgressDialog.setProgress(progress[0]);
     }
  
     @Override
     protected void onPostExecute(String result) {
      mWakeLock.release();
      mProgressDialog.dismiss();
       if (result != null) {
          Toast.makeText(context, "Download error: " + result, 
     Toast.LENGTH_LONG).show();
  
          delegate.processFinish("Error");
  
      } else {
           delegate.processFinish("Success");
  
         /* String mediaPath = Environment.getExternalStorageDirectory() + 
    "/Pediatric/" + title;
  
          Intent intent = new Intent(Intent.ACTION_VIEW, 
    Uri.parse(mediaPath));
          intent.setDataAndType(Uri.parse(mediaPath), "video/mp4");
          context. startActivity(intent);*/
      }
    }
  }
  
  
  
  
  
  
  
   AsyncResponse Inteerface
   package com.example.mahvishponum.pdfviewer;
  
   /**
   * Created by Mahvish on 12/22/2016.
    */
  
   public interface AsyncResponse {
   void processFinish(String output);
  
   }
  
  
  
  
  
  
  
   pdfviewer.xml
  
   &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" &gt;
  
   &lt;ListView
     android:id="@+id/listvid"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" &gt;
  
   &lt;/ListView&gt;
  
   &lt;/RelativeLayout&gt;
  
  
  
  
  
  
  
  Menifest.xml
  
  &lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.mahvishponum.pdfviewer"&gt;
  
  &lt;uses-permission android:name="android.permission.WAKE_LOCK"/&gt;
  &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
  &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
  &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt;
  &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;
  &lt;uses-permission android:name="android.permission.READ_PHONE_STATE" /&gt;
  &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt;
  
  
  &lt;application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme"&gt;
      &lt;activity android:name=".MainActivity"&gt;
          &lt;intent-filter&gt;
              &lt;action android:name="android.intent.action.MAIN" /&gt;
  
              &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
          &lt;/intent-filter&gt;
      &lt;/activity&gt;
  
  
    &lt;/application&gt;
  
    &lt;/manifest&gt;
  
  CustomList.java
   package com.example.mahvishponum.pdfviewer;
  
   import android.app.Activity;
   import android.view.LayoutInflater;
   import android.view.View;
   import android.view.ViewGroup;
   import android.widget.ArrayAdapter;
   import android.widget.ImageView;
   import android.widget.TextView;
  
   public class CustomList extends ArrayAdapter&lt;String&gt;{
  
   private final Activity context;
   private final String[] web;
   private final Integer[] imageId;
   public CustomList(Activity context,
                String[] web, Integer[] imageId) {
    super(context, R.layout.list_single, web);
    this.context = context;
   this.web = web;
  this.imageId = imageId;
  
   }
   @Override
    public View getView(int position, View view, ViewGroup parent) {
  LayoutInflater inflater = context.getLayoutInflater();
     View rowView= inflater.inflate(R.layout.list_single, null, true);
  TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
  
   ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
  txtTitle.setText(web[position]);
  
    imageView.setImageResource(imageId[position]);
    return rowView;
   }
   }
  
  
  list_single.xml
  
   &lt;?xml version="1.0" encoding="utf-8"?&gt;
   &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" &gt;
    &lt;TableRow&gt;
      &lt;ImageView
          android:id="@+id/img"
          android:layout_width="50dp"
          android:layout_height="50dp"/&gt;
  
      &lt;TextView
          android:id="@+id/txt"
          android:layout_width="wrap_content"
          android:layout_height="50dp" /&gt;
  
   &lt;/TableRow&gt;
   &lt;/TableLayout&gt;
  </code></pre>