2017-05-30 2 views
2

J'ai un problème en essayant de télécharger le fichier PDF et enregistrez-le dans le stockage interne ou les préférences partagées et le lire. Est-il possible de le télécharger en mémoire interne? J'ai suivi plusieurs tutoriels d'internet mais ça ne marche pas. quelqu'un pourrait-il me guider comment le faire? Merci beaucoup.android studio télécharger le fichier pdf et enregistrez-le dans 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

S'il vous plaît être plus précis, par exemple nous dire ce que vous avez essayé jusqu'à présent (lier votre recherche ici) et quel est le problème que vous êtes confronté lorsque vous essayez de télécharger pdf fichier ? –

+0

Stockez-le dans PreFF partagé? –

+0

je veux télécharger un fichier pdf à partir de l'URL et l'enregistrer dans le stockage interne. je peux l'enregistrer dans la carte SD ou externe mais dans mon projet, le fichier pdf est privé de sorte qu'il doit être conservé dans le stockage interne – rizal

Répondre

0

Gradle

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

Ecrire:

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(); 
} 

Pour lire:

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

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

ne peut pas télécharger le pdf en utilisant cette méthode – rizal

0

S'il vous plaît ajouter des fichiers suivant/méthode pour votre projet

  1. PdfDownloader.java
  2. PDFDownloaderAsyncTask.java

, puis en utilisant la méthode suivante handleViewPdf pour afficher pdf:

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; 
    } 

}