2017-07-20 113 views
0

我試圖從Dropbox下載PDF文件的代碼,並在單擊項目時下載了我的SD卡中的所有文件後,PDF書籍應以PDF格式加載查看器系統應用。 但實際上通過使用此代碼所有的PDF文件正在下載,但是當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> 

回答

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"); 
+0

是所有文件都看我打開文件管理器, –

+0

但我想查看它時單擊列表項 –

+0

是的,我知道,但現在我們知道它在代碼中出錯了;) –