尝试从PDF文档下载PDF文件的代码不被查看

时间:2017-07-20 18:01:20

标签: android pdf

我正在尝试使用代码从dropbox下载PDF文件,并在点击项目后下载SD卡中的所有文件后,PDF book应该加载到PDF查看器系统应用程序中。 但实际上通过使用此代码,所有PDF文件都在下载,但是当加载PDF应用程序时,它会显示错误“文档无法打开”,并且不会查看PDF书籍。任何人都可以帮我解决这个问题 提前感谢你 而且我不善于用有效的方式发帖提问,所以我真的很抱歉。

  {

  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<DataModel> _data = new ArrayList<>();
  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 & 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 < 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<?> 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 < 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<String, Integer, String> {
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 > 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

 <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" >

 <ListView
   android:id="@+id/listvid"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

 </ListView>

 </RelativeLayout>







Menifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mahvishponum.pdfviewer">

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


<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">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


  </application>

  </manifest>

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<String>{

 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

 <?xml version="1.0" encoding="utf-8"?>
 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" >
  <TableRow>
    <ImageView
        android:id="@+id/img"
        android:layout_width="50dp"
        android:layout_height="50dp"/>

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="50dp" />

 </TableRow>
 </TableLayout>

1 个答案:

答案 0 :(得分:0)

您可以从普通数据文件管理器/自己的文件中打开它吗?如果这不起作用,则下载出错

此处将代码更改为MainActivity中的代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        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<?> 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";
                    File f = new File(filePath);
                    Log.d("Main","file exits " + f.exists());
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filePath));
                    intent.setDataAndType(Uri.fromFile(f), "application/pdf");
                    //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();

                }
            }
        });
    }

我改变了这句话:

File f = new File(filePath);
intent.setDataAndType(Uri.fromFile(f), "application/pdf");