2017-05-30 4 views
2

PDFファイルをダウンロードして内部ストレージまたは共有プリファレンスに保存しようとすると問題が発生します。内部ストレージにダウンロードすることは可能ですか?私はインターネットからいくつかのチュートリアルに従ってきましたが、うまくいきません。誰かが私にそれをする方法を導くことができますか? ありがとうございました。アンドロイドスタジオPDFファイルをダウンロードしてsharedpreferencesに保存

package com.icul.downloadinternal; 

import android.content.SharedPreferences; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.preference.PreferenceManager; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Base64; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.Toast; 

import java.io.IOException; 

import okhttp3.OkHttpClient; 
import okhttp3.Request; 
import okhttp3.Response; 

public class MainActivity extends AppCompatActivity { 

    Button download, read; 
    ImageView pdf; 
    String url = "https://www.cdc.gov/eval/guide/cdcevalmanual.pdf"; 

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

     download = (Button) findViewById(R.id.button); 
     read = (Button) findViewById(R.id.button2); 
     pdf = (ImageView) findViewById(R.id.image); 

     download.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       try { 
        downloadFileSync(url); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 

     read.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
       String previouslyEncodedImage = shre.getString("pdf_data", ""); 

       if(!previouslyEncodedImage.equalsIgnoreCase("")){ 
        byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT); 
        Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0 , b.length); 
        pdf.setImageBitmap(bitmap); 
       } 
       else { 
        Toast.makeText(getApplicationContext(),"No File", Toast.LENGTH_LONG).show(); 
       } 
      } 
     }); 

    } 
    public void downloadFileSync(String downloadUrl) throws Exception { 

     OkHttpClient client = new OkHttpClient(); 
     Request request = new Request.Builder().url(downloadUrl).build(); 
     Response response = client.newCall(request).execute(); 
     if (!response.isSuccessful()) { 
      throw new IOException("Failed to download file: " + response); 
     } 

     String encodedImage = Base64.encodeToString(response.body().bytes(), Base64.DEFAULT); 
     SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this); 
     SharedPreferences.Editor edit = shre.edit(); 
     edit.putString("pdf_data", encodedImage); 
     edit.commit(); 
    } 
} 
+0

あなたは(ここではあなたの研究をリンク)これまでに試したとPDFファイルをダウンロードしようとしたとき、あなたが直面している問題は何が何であるかを教え、すなわち、より具体的にしてくださいファイル? –

+0

それを共有preffに格納?? –

+0

URLからPDFファイルをダウンロードして内部のストレージに保存したいのですが。私はSDカードまたは外部に保存することができますが、私のプロジェクトでは、PDFファイルはプライベートなので、内部ストレージに保存する必要があります – rizal

答えて

0

のGradle

compile 'com.squareup.okhttp3:okhttp:3.8.0' 

書き込み:読み取りのために

public void downloadFileSync(String downloadUrl) throws Exception { 

    OkHttpClient client = new OkHttpClient(); 
    Request request = new Request.Builder().url(downloadUrl).build(); 
    Response response = client.newCall(request).execute(); 
    if (!response.isSuccessful()) { 
     throw new IOException("Failed to download file: " + response); 
    } 
    String encodedImage = Base64.encodeToString(response.body().bytes(), Base64.DEFAULT); 

    SharedPreferences shre = 
    PreferenceManager.getDefaultSharedPreferences(this); 
    Editor edit=shre.edit(); 
    edit.putString("pdf_data",encodedImage); 
    edit.commit(); 
} 

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this); 
String previouslyEncodedImage = shre.getString("pdf_data", ""); 

if(!previouslyEncodedImage.equalsIgnoreCase("")){ 
    byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT); 
    // ..... 
} 
+0

その方法を使用してpdfをダウンロードできません – rizal

0

プロジェクトに以下のファイル/メソッドを追加してください

  1. PdfDownloader.java
  2. PDFDownloaderAsyncTask.java

した後PDFを表示するには、以下の方法handleViewPdf使用:

private void handleViewPdf() { 

    File folder = getAppDirectory(context); 
    String fileName = "test.pdf";// getPdfFileName(pdfUrl); 
    File pdfFile = new File(folder, fileName); 

    if(pdfFile.exists() && pdfFile.length() > 0) { 
     openPDFFile(context, Uri.fromFile(pdfFile)); 
    } 
    else { 
     if(pdfFile.length() == 0) { 
      pdfFile.delete(); 
     } 
     try { 
      pdfFile.createNewFile(); 
     } 
     catch(IOException e) { 
      e.printStackTrace(); 
     } 
     ArrayList<String> fileNameAndURL = new ArrayList<>(); 
     fileNameAndURL.add(pdfFile.toString()); 
     fileNameAndURL.add(pdfUrl); 
     fileNameAndURL.add(fileName); 
     if(pdfDownloaderAsyncTask == null) { 
      pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask(context, pdfFile); 
     } 
     if(hasInternetConnection(context)) { 
      if(!pdfDownloaderAsyncTask.isDownloadingPdf()) { 
       pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask(context, pdfFile); 
       pdfDownloaderAsyncTask.execute(fileNameAndURL); 
      } 
     } 
     else { 
      //show error 
     } 
    } 
} 

PDFDownloaderAsyncTask.java

import java.io.File; 
    import java.util.ArrayList; 

    import android.content.Context; 
    import android.net.Uri; 
    import android.os.AsyncTask; 
    import android.os.Handler; 
    import android.text.TextUtils; 
    import android.widget.Toast; 


    public class PDFDownloaderAsyncTask extends AsyncTask<ArrayList<String>, Void, String> { 

     private boolean isDownloadingPdf = false; 

     private File file; 
     private Context context; 

     public PDFDownloaderAsyncTask(Context context, File file) { 

      this.file = file; 
      this.context = context; 
      this.isDownloadingPdf = false; 
     } 

     public boolean isDownloadingPdf() { 

      return this.isDownloadingPdf; 
     } 

     @Override 
     protected void onPreExecute() { 

      super.onPreExecute(); 
      //show loader etc 
     } 

     @Override 
     protected String doInBackground(ArrayList<String>... params) { 

      isDownloadingPdf = true; 
      File file = new File(params[0].get(0)); 
      String fileStatus = PdfDownloader.downloadFile(params[0].get(1), file); 
      return fileStatus; 
     } 

     @Override 
     protected void onPostExecute(String result) { 

      super.onPostExecute(result); 
      Loader.hideLoader(); 
      if(!TextUtils.isEmpty(result) && result.equalsIgnoreCase(context.getString(R.string.txt_success))) { 
       showPdf(); 
      } 
      else { 
       isDownloadingPdf = false; 
       Toast.makeText(context, context.getString(R.string.error_could_not_download_pdf), Toast.LENGTH_LONG).show(); 
       file.delete(); 
      } 
     } 

     @Override 
     protected void onCancelled() { 

      isDownloadingPdf = false; 
      super.onCancelled(); 
      //Loader.hideLoader(); 
     } 

     @Override 
     protected void onCancelled(String s) { 

      isDownloadingPdf = false; 
      super.onCancelled(s); 
      //Loader.hideLoader(); 
     } 

     private void showPdf() { 

      new Handler().postDelayed(new Runnable() { 
       @Override 
       public void run() { 

        isDownloadingPdf = false; 
        openPDFFile(context, Uri.fromFile(file)); 
       } 
      }, 1000); 
     } 
    } 

PdfDownloader.java

package com.pdf; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

public class PdfDownloader { 
    private static final int MEGABYTE = 1024 * 1024; 

    public static String downloadFile(String fileUrl, File directory) { 

     String downloadStatus; 
     try { 

      URL url = new URL(fileUrl); 
      HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection(); 
      urlConnection.connect(); 

      InputStream inputStream = urlConnection.getInputStream(); 
      FileOutputStream fileOutputStream = new FileOutputStream(directory); 
      int totalSize = urlConnection.getContentLength(); 

      Log.d("PDF", "Total size: " + totalSize); 
      byte[] buffer = new byte[MEGABYTE]; 
      int bufferLength = 0; 
      while((bufferLength = inputStream.read(buffer)) > 0) { 
       fileOutputStream.write(buffer, 0, bufferLength); 
      } 
      downloadStatus = "success"; 
      fileOutputStream.close(); 
     } 
     catch(FileNotFoundException e) { 
      downloadStatus = "FileNotFoundException"; 
      e.printStackTrace(); 
     } 
     catch(MalformedURLException e) { 
      downloadStatus = "MalformedURLException"; 
      e.printStackTrace(); 
     } 
     catch(IOException e) { 
      downloadStatus = "IOException"; 
      e.printStackTrace(); 
     } 
     Log.d("PDF", "Download Status: " + downloadStatus); 
     return downloadStatus; 
    } 


    public static void openPDFFile(Context context, Uri path) { 

     Intent intent = new Intent(Intent.ACTION_VIEW); 
     intent.setDataAndType(path, "application/pdf"); 
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     try { 
      context.startActivity(intent); 
     } 
     catch(ActivityNotFoundException e) { 
      Toast.makeText(context, context.getString(R.string.txt_no_pdf_available), Toast.LENGTH_SHORT).show(); 
     } 
     Loader.hideLoader(); 
    } 

    public static File getAppDirectory(Context context) { 

     String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
     File folder = new File(extStorageDirectory, context.getString(R.string.app_folder_name).trim()); 
     if(!folder.exists()) { 
      boolean success = folder.mkdirs(); 
      Log.d("Directory", "mkdirs():" + success); 
     } 
     return folder; 
    } 

} 
関連する問題