I have a button that when pressed launches an activity to select a PDF document
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("application/pdf");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(chooseFile, REQ_PDF);
}
});
I encode the selected document in base64 and store it in my variableencodedPDF
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_PDF && resultCode == RESULT_OK && data != null){
Uri path = data.getData();
try {
InputStream inputStream = MainActivity.this.getContentResolver().openInputStream(path);
byte[] pdfInBytes = new byte[inputStream.available()];
inputStream.read(pdfInBytes);
encodedPDF = Base64.encodeToString(pdfInBytes, Base64.DEFAULT);
textView.setText("Document Selected");
btnSelect.setText("Change Document");
Toast.makeText(this, "Document Selected", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I then have another button that reads the variable and sends it to a server
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadDocument();
}
});
private void uploadDocument() {
Call<ResponsePOJO> call = RetrofitClient.getInstance().getAPI().uploadDocument(encodedPDF);
call.enqueue(new Callback<ResponsePOJO>() {
@Override
public void onResponse(Call<ResponsePOJO> call, Response<ResponsePOJO> response) {
Toast.makeText(MainActivity.this, response.body().getRemarks(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<ResponsePOJO> call, Throwable t) {
Toast.makeText(MainActivity.this, "Network Failed", Toast.LENGTH_SHORT).show();
}
});
}
All this I copied from a tutorial and it works perfect. However the first button doesn't make sense in my app because the pdf I want to upload is always in the same path that I know beforehand
File path = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/" + Login.gIdPedido + " Examen.pdf")));
What I want is to get rid of that first part of selecting the document but I don't know how to implement it.
How can I bypass the manual selection of the PDF and get it directly from storage when I hit the submit button?
You just have to connect the pieces:
You have a method
uploadDocument
that sends the PDF that is in the variableencodedPDF
.Then inside
onActivityResult
you have a code thatUri
generates a base64 string and stores it in that variable.Finally you say you have the file path.
So all you have to do is take the code out of
onActivityResult
and put it in a method that you can call from the clickListener, replacing the result uri of the intent with the one in your file.and just call it inside the clickListener