0

I'm working on an app that needs to save user's information to a server using retrofit, the backend is built with spring boot, I want to get the real path of the user's image and serve it on the server which stores all the information in MYSQL database, the issue is when I select an image from my gallery, it's not displaying in my imageView. The same code is working fine if I use a real device but the issue is that my mobile device cannot connect to my localhost so that's why I prefer to use an emulator for it. I don't know why the image is not displaying. Here is my code.

private static final int PICK_IMAGE_REQUEST = 1;

imagePicker.setOnClickListener(view -> { if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED){ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent,PICK_IMAGE_REQUEST); }else { ActivityCompat.requestPermissions(PatientRegistrationActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1); } });

@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode== PICK_IMAGE_REQUEST && resultCode== RESULT_OK && data !=null){ profileImageUri = data.getData(); profileImagePath = RealPathUtil.getRealPath(PatientRegistrationActivity.this,profileImageUri); Bitmap bitmap = BitmapFactory.decodeFile(profileImagePath); profilePicture.setImageBitmap(bitmap); } }

public class RealPathUtil {

public static String getRealPath(Context context, Uri fileUri) {
    String realPath;
    // SDK < API11
    if (Build.VERSION.SDK_INT < 11) {
        realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(context, fileUri);
    }
    // SDK >= 11 && SDK < 19
    else if (Build.VERSION.SDK_INT < 19) {
        realPath = RealPathUtil.getRealPathFromURI_API11to18(context, fileUri);
    }
    // SDK > 19 (Android 4.4) and up
    else {
        realPath = RealPathUtil.getRealPathFromURI_API19(context, fileUri);
    }
    return realPath;
}

}

Ukeme Elijah
  • 157
  • 3
  • 13
  • "The same code is working fine if I use a real device" -- you tested on one phone out of *billions*. Your code will not work reliably on many, many devices, as a `Uri` is not a file. "that needs to save user's information to a server using retrofit" -- [you do not need a "real path" to do this](https://stackoverflow.com/questions/56308559/create-a-file-from-a-photo-uri-on-android), which is good, because there is no "real path" – CommonsWare Dec 02 '22 at 14:59

0 Answers0