I tried to upload a pdf file with Retrofit
, and several times it failed because I couldn't read the file path properly. So when checked with file.exist()
the result is false.
the result is:
2021-03-01 19:08:27.145 9017-9017/com.dennyprastiawan.ebaak E/TAG: onActivityResult: false /storage/emulated/0/storage_root/Download/kurikulumbaru9.pdf
when I replace the path with a specific path like: (URLFILE.replace("/storage_root",""))
Then I display with this path below , The result is a successful file upload to the server. However, this becomes a problem when changing devices where the paths are not the same :
String URLFILE = data.getData (). GetPath ();
filename.setText (URLFILE);
my code to get file pdf:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode==9 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
openFile();
} else {
displayExceptionMessage("Anda tidak memiliki permission untuk mengakses storage");
}
}
public void openFile(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Pilih file"),PICKFILE_RESULT_CODE);
}
Activity result is:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==PICKFILE_RESULT_CODE && resultCode==RESULT_OK && data != null){
SString URLFILE = data.getData().getPath();
fileuri = data.getData();
File file = new File(getRealPathFromURI(fileuri));
if(fileuri!=null){
// files = new File(Environment.getExternalStorageDirectory(), URLFILE.replace("/storage_root",""));
namaFile.setText(URLFILE);
Log.e("TAG", "onActivityResult: "+file.exists()+" "+file.toString() );
//String wholeID = DocumentsContract.getDocumentId(fileuri);
} else {
displayExceptionMessage("select file");
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}