2016-01-29 3 views
0

В моем приложении у меня есть расширенный список, и я хочу открыть PDF-файл, загруженный из Интернета, когда я нажимаю на конкретный ребенок. Проблема в том, что файл pdf (Read.pdf) всегда пуст, что означает, что загрузка не работает.Загрузить PDF не работает

Downloader Класс:

public class Downloader { 

public static void DownloadFile(String fileURL, File directory) { 
    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; 
     while ((len1 = in.read(buffer)) > 0) { 
      f.write(buffer, 0, len1); 
     } 
     f.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

Часть деятельности:

private void registerClick() { 
    expListView.setOnChildClickListener(new OnChildClickListener() { 

     @Override 
     public boolean onChildClick(ExpandableListView parent, View v, 
            int groupPosition, int childPosition, long id) { 
      if ((groupPosition == 0) && (childPosition == 0)){ 
       File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE", "Read.pdf"); 
       try { 
        file.createNewFile(); 
       } catch (IOException e1) { 
        e1.printStackTrace(); 
       } 
       Downloader.DownloadFile("https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf", file); 


       AbrirPDF.showPdf(); 
      } else { 

      } 

      return false; 
     } 
    }); 

} 

Я думаю OpenPDF (AbrirPDF) не имеет каких-либо проблем, но я отправлю его ...

public class AbrirPDF { 



public static void showPdf() 
{ 



    File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE/Read.pdf"); 
    PackageManager packageManager = ContextGetter.getAppContext().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 = Uri.fromFile(file); 
    intent.setDataAndType(uri, "application/pdf"); 
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    ContextGetter.getAppContext().startActivity(intent); 
} 
} 

спасибо.

+0

Можете ли вы добавить описание/журнал о том, что происходит при попытке скачивания? –

+0

Вы пробовали переходить через программу с помощью отладчика? –

ответ

1

В идеале ваша загрузка должна происходить в отдельном потоке, чтобы избежать блокировки вашего приложения.

Вот пример, который также включает индикатор выполнения.

public class MainActivity extends Activity { 

    private ProgressDialog pDialog; 
    public static final int progress_bar_type = 0; 

    private static String file_url = "https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 

     new DownloadFileFromURL().execute(file_url); 

    } 


    @Override 
    protected Dialog onCreateDialog(int id) { 
     switch (id) { 
     case progress_bar_type: // we set this to 0 
      pDialog = new ProgressDialog(this); 
      pDialog.setMessage("Downloading file. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setMax(100); 
      pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
      return pDialog; 
     default: 
      return null; 
     } 
    } 

    class DownloadFileFromURL extends AsyncTask<String, String, String> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      showDialog(progress_bar_type); 
     } 

     @Override 
     protected String doInBackground(String... f_url) { 
      int count; 
      try { 
       URL url = new URL(f_url[0]); 
       URLConnection conection = url.openConnection(); 
       conection.connect(); 

       // this will be useful so that you can show a tipical 0-100% 
       // progress bar 
       int lenghtOfFile = conection.getContentLength(); 

       // download the file 
       InputStream input = new BufferedInputStream(url.openStream(), 
         8192); 

       // Output stream 
       OutputStream output = new FileOutputStream(Environment 
         .getExternalStorageDirectory().toString() 
         + "/2011.kml"); 

       byte data[] = new byte[1024]; 

       long total = 0; 

       while ((count = input.read(data)) != -1) { 
        total += count; 
        // publishing the progress.... 
        // After this onProgressUpdate will be called 
        publishProgress("" + (int) ((total * 100)/lenghtOfFile)); 

        // writing data to file 
        output.write(data, 0, count); 
       } 

       // flushing output 
       output.flush(); 

       // closing streams 
       output.close(); 
       input.close(); 

      } catch (Exception e) { 
       Log.e("Error: ", e.getMessage()); 
      } 

      return null; 
     } 

     protected void onProgressUpdate(String... progress) { 
      // setting progress percentage 
      pDialog.setProgress(Integer.parseInt(progress[0])); 
     } 

     @Override 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog after the file was downloaded 
      dismissDialog(progress_bar_type); 

     } 

    } 
} 
Смежные вопросы