I'm using Async task for downloading a pdf file from web API but somehow it is giving exception in doInbackground() method for read(buffer).
first time read() reads 1735 bytes but on second call it gives exception doesn't understand why???
Here is the codeenter code here
public ImportPdfAsyncTask(Context c)
{
mContext = c;
}
@Override
protected Void doInBackground(Void... voids) {
Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Log.d("my", "Server contacted and has file");
boolean writtenToDisk = writeResponseBodyToDisk(response.body());;
Log.d("my", "File written to disk?" + writtenToDisk);
} else {
Log.d("my", "Server contact failed");
}
}
And here is the method
private boolean writeResponseBodyToDisk(ResponseBody body)
{
try{
File file = new File(mContext.getExternalCacheDir()+File.separator+"myPDF");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[6000];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(file);
while (true)
{
Log.d("my","# of times");
int read = inputStream.read(fileReader);
//Here getting Ex when called second time
Log.d("my","bytes read"+read);
if(read == -1)
{
break;
}
outputStream.write(fileReader,0,read);
fileSizeDownloaded += read;
Log.d("my","File downloaded "+fileSizeDownloaded+" of"+
fileSize);
}
outputStream.flush();
return true;
}
catch (Exception e)
{
Log.d("my","in ex");
Log.d("my",e.getMessage()+123);
Log.d("my",e.toString());
return false;
}
finally {
if(inputStream != null)
inputStream.close();
if(outputStream != null)
outputStream.close();
}
}catch (Exception e)
{
return false;
}
}
Calling Async task as:
ImportPdfAsyncTask task = new ImportPdfAsyncTask(getApplicationContext());
task.execute();