2016-12-28 2 views
1

アプリ内でのPDFドキュメントの表示例をウェブで検索しました。また、私はインターネットからpdfをロードしたいので、Downloaderクラスを検索しました。実行後、空のPDFページが表示されます。アプリ内のpdfをダウンロードして表示するだけのアプリで空白のコンテンツが返される

MainActivity.javaはちょうどDisplayPDF.java活動へのpdfのリンクを送信します。

package com.example.pdfviewevaluation; 

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 

public class MainActivity extends AppCompatActivity { 
    public final static String EXTRA_MESSAGE = "com.example.pdfviewevaluation.MESSAGE"; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Intent intent = new Intent(this, DisplayPDF.class); 
     String url = "pdf link"; 
     intent.putExtra(EXTRA_MESSAGE, url); 
     startActivity(intent); 
    } 
} 

DisplayPDF.javaは、キャッシュディレクトリ内のフォルダやPDFを作成します。次に、pdfリンクとディレクトリを持つDownloaderを起動します。最後に、それだけでPDFファイルを表示する必要があります:

package com.example.pdfviewevaluation; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.net.Uri; 
import android.support.v4.content.FileProvider; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 

import java.io.File; 
import java.io.IOException; 
import java.util.List; 
import java.util.concurrent.ExecutionException; 

    public class DisplayPDF extends AppCompatActivity { 

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

     String pdfURL = getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE); 
     File folder = new File(this.getCacheDir(), "pdf"); 
     folder.mkdir(); 
     File file = new File(folder, "Read.pdf"); 
     try { 
      file.createNewFile(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 
     Downloader dl = new Downloader(pdfURL, file); 
     try { 
      dl.execute().get(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      e.printStackTrace(); 
     } 
     showPdf(); 
    } 

    public void showPdf() { 
     File file = new File(this.getCacheDir()+"/pdf/Read.pdf"); 
     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 = FileProvider.getUriForFile(this.getApplicationContext(), this.getApplicationContext().getPackageName() + ".provider", file); 
     intent.setDataAndType(uri, "application/pdf"); 
     startActivity(intent); 
    } 
} 

Downloader.javaは、PDFページに接続して、目的のディレクトリに与えられたリンクからPDFをダウンロード:私の問題への支出の多くの時間後

package com.example.pdfviewevaluation; 

import android.os.AsyncTask; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.concurrent.locks.Lock; 
import java.util.concurrent.locks.ReentrantLock; 

public class Downloader extends AsyncTask<Void,Void,Void> { 
    private String fileURL; 
    private File directory; 

    public Downloader(String fileURL, File directory) 
    { 
     this.fileURL = fileURL; 
     this.directory = directory; 
    } 

    protected Void doInBackground(Void... params) { 
     try { 
      FileOutputStream f = new FileOutputStream(directory); 
      URL u = new URL(fileURL); 
      HttpURLConnection c = (HttpURLConnection) u.openConnection(); 
      c.setRequestMethod("GET"); 
      c.setDoOutput(true); 
      c.connect(); 

      InputStream in = c.getInputStream(); 

      byte[] buffer = new byte[1024]; 
      int len1 = 0; 
      int i = 0; 
      while ((len1 = in.read(buffer)) > 0) { 
       f.write(buffer, 0, len1); 
      } 
      f.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 
+0

はほとんどの場合、あなたはこれらの一つが解決策を示していますクラッシュ'NetworkOnMainThreadException'を指定してください。 LogCatを調べて、ログに記録している例外を調べます。 – CommonsWare

+1

解決策を2つの部分に分けて、問題が実際にどこにあるかを理解してください。1)ダウンロードしたファイルをパブリックディレクトリに保存し、標準のpdfリーダーで開き、ファイルが破損していないかどうかを確認します。有効であることがわかっているpdfファイルを表示できるようにするファイルシステム – SimoV8

答えて

0

私はYouTubeで別の解決策を探しました。

  1. https://www.youtube.com/watch?v=pGlqHeB5hdk
  2. https://www.youtube.com/watch?v=8YPJCOxiklQ

のAndroidManifest.xml:

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

    <uses-sdk android:minSdkVersion="21" 
    android:targetSdkVersion="22" /> 
     <uses-permission android:name="android.permission.INTERNET"/> 
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
     <application 
      android:allowBackup="true" 
      android:icon="@mipmap/ic_launcher" 
      android:label="@string/app_name" 
      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> 

MainActivity.java

import android.app.DownloadManager; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.graphics.Bitmap; 
import android.graphics.Matrix; 
import android.graphics.Rect; 
import android.graphics.pdf.PdfRenderer; 
import android.net.Uri; 
import android.os.Environment; 
import android.os.ParcelFileDescriptor; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.webkit.MimeTypeMap; 
import android.webkit.URLUtil; 
import android.widget.ImageView; 
import android.widget.Toast; 
import java.io.File; 

public class MainActivity extends AppCompatActivity { 
    String myUrl = "http://www.orimi.com/pdf-test.pdf"; 
    private ImageView imageView; 
    private int currentPage = 0; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 

     DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myUrl)); 
     request.setTitle("File download."); 
     request.setDescription("File is being downloaded..."); 
     request.allowScanningByMediaScanner(); 
     request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
     String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl)); 
     request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile); 
     DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE); 
     manager.enqueue(request); 
    } 


    BroadcastReceiver onComplete=new BroadcastReceiver() { 
     public void onReceive(Context context, Intent intent) { 
      render(); 
    } 
}; 

    /**Called when the user clicks the "Next" button defined in activity_main.xml */ 
    public void nextPage(View view) { 
     currentPage++; 
     render(); 
    } 

    /**Called when the user clicks the "Previous" button defined in activity_main.xml */ 
    public void previousPage(View view) { 
     currentPage--; 
     render(); 
    } 

    private void render(){ 
     try{ 
      imageView = (ImageView) findViewById(R.id.image); 
      int REQ_WIDTH = imageView.getWidth(); 
      int REQ_HEIGHT = imageView.getHeight(); 

      Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444); 
      String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl)); 
      File file = new File("/sdcard/Download/"+nameOfFile); 
      PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)); 
      if(currentPage < 0){ 
       currentPage = 0; 
      }else if(currentPage >= renderer.getPageCount()){ 
       currentPage = renderer.getPageCount() - 1; 
      } 

      Matrix m = imageView.getImageMatrix(); 
      Rect rect = new Rect(0, 0, REQ_WIDTH, REQ_HEIGHT); 
      renderer.openPage(currentPage).render(bitmap, rect, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY); 
      imageView.setImageMatrix(m); 
      imageView.setImageBitmap(bitmap); 
      imageView.invalidate(); 
     } catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 
関連する問題