I'm writing a program to download a pdf file from a url to byte format and then display it on PdfViewer in android. However it takes some time to download and I would like to do this on a separate thread using asynctask. The code works well without asynctask but gives an error when I use asynctask.
loadBookPdf.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AsyncTask<String, Void, byte[]> task = new AsyncTask<String,
Void, byte[]>() {
ProgressBar bar;
@Override
protected void onPreExecute() {
bar = findViewById(R.id.progressBar);
bar.setVisibility(View.VISIBLE);
}
@Override
protected byte[] doInBackground(String... strings) {
Log.e("thread", "success?");
String urlString = strings[0];
byte[] bookByte = getFile(urlString);
Log.e("thread", "success");
return bookByte;
}
@Override
protected void onPostExecute(byte[] bytes) {
fileReader = bytes;
bar.setVisibility(View.GONE);
}
};
task.execute(BookBriefInfo.textUrl);
// fileReader = getFile(BookBriefInfo.textUrl);
Intent intent = new Intent(BookBriefInfo.this,
BookPdfReader.class);
startActivity(intent);
finish();
}
});
The file reader code:
private byte[] getFile(String pdfUrl) {
//TODO send translation URL from cloudLibraryAdaptor
URL url;
HttpURLConnection c;
byte[] bytes = null;
try {
url = new URL(pdfUrl);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream is = c.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = is.read(buf)) != -1; ) {
bos.write(buf, 0, readNum);
}
bytes = bos.toByteArray();
// fileReader = bytes;
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
The error I'm getting:
A/zygote: java_vm_ext.cc:504] JNI DETECTED ERROR IN APPLICATION: jarray
was NULL
java_vm_ext.cc:504] in call to GetByteArrayElements
java_vm_ext.cc:504] from long com.shockwave.pdfium.PdfiumCore.nativeOpenMemDocument(byte[], java.lang.String)
java_vm_ext.cc:504] "AsyncTask #2" prio=5 tid=26 Runnable
java_vm_ext.cc:504] | group="main" sCount=0 dsCount=0 flags=0 obj=0x1322fec0 self=0xa401dc00
java_vm_ext.cc:504] | sysTid=8528 nice=10 cgrp=default sched=0/0 handle=0x8e10b970
java_vm_ext.cc:504] | state=R schedstat=( 12742370 18637590 15 ) utm=1 stm=0 core=1 HZ=100
java_vm_ext.cc:504] | stack=0x8e009000-0x8e00b000 stackSize=1038KB
A/zygote: java_vm_ext.cc:504] | held mutexes= "mutator lock"(shared held)