Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android cant open pdf from cache dir

Trying to download and open a pdf file from internet using HTTPClient on android. I have 2 classes. First one is the parser class that has the next method:

public static void saveFile(String link, FileOutputStream fos) {
    DefaultHttpClient client = new DefaultHttpClient();
    try{
        client.setCookieStore(cookieStore);
        HttpGet method = new HttpGet(link);
        HttpResponse response = client.execute(method);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            entity.writeTo(fos);
            fos.close();
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        client.getConnectionManager().shutdown();
    }
}

The next class is an Activity. It makes a new Intent and opens pdf file using installed software (user decides what soft to use). This Activity saves the pdf file using the upper method from Parser.class and AsyncTask. It looks so:

   private class AsyncExecutionOfPdf extends AsyncTask<Void,Void,Void>{
    @Override
    protected Void doInBackground(Void... arg0) {
        File file;
        file = new File(getCacheDir()+"/tempFile.pdf");
        file.setWritable(true);
        file.setReadable(true);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Parser.saveFile("http://existingInternetFile.pdf", fos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(Void resu) {
        pd.dismiss();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(getCacheDir()+"/tempFile.pdf");
        Log.e("FILE EXISTS?",""+file.exists());
        intent.setDataAndType(Uri.fromFile(file), "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
            startActivity(intent);
        } 
        catch (ActivityNotFoundException e) {
            Toast.makeText(FilesActivity.this, 
                "No Application Available to View PDF", 
                Toast.LENGTH_SHORT).show();
        }
    }

}

While the Log.e("FILE EXISTS?",""+file.exists()) sais, that the file exists, it doesnot want to be opened with any of 8 pdf readers I tryed to use. Please help.Thanks in advance

like image 420
Rinomancer Avatar asked Feb 16 '23 10:02

Rinomancer


1 Answers

Those "8 pdf readers" have no access to your cache directory. Either store it on external storage (e.g., getExternalCacheDir()), or create a ContentProvider to serve the PDF out of your internal cache dir. This sample project demonstrates serving a file from internal storage.

like image 142
CommonsWare Avatar answered Feb 26 '23 18:02

CommonsWare