I am trying to download a pdf from the internet, store the file in internal storage and then launch the pdf in an intent. I keep getting "The document is empty (size 0KB)" when it launches the intent.
class Pdf extends AsyncTask<Void, Void, String>{
private Context ctx;
public Pdf(Context ctx){
this.ctx = ctx;
}
@Override
protected String doInBackground(Void... params) {
try {
FileOutputStream f = ctx.openFileOutput("city.pdf", ctx.MODE_WORLD_READABLE);
URL u = new URL("http://www.example.com/city.pdf");
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();
}
File file = new File(ctx.getFilesDir(), "city.pdf");
PackageManager packageManager = ctx.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");
ctx.startActivity(intent);
return null;
}
}
This has been driving me crazy, any ideas?