Mike Thomson Mike Thomson -5 years ago 108
Java Question

A button which allows an image to be shown in Android Studio

I am building my application using Android Studio, this app can upload an image from raspberry to my emulator. It works fine. What I want to do now is uploading this image and showing it directly to the user without searching it in the gallery. I thought about creating another class and setting this image as a background image in my xml file, but this is too much like I have to create another class every time I want to upload an image from my raspberry.
Can someone help me please. Thank you

Answer Source

If I'm understanding your question correctly, you'd like to load an image from the Android filesystem into your app and display it to the user.

Drawable, Android's generalized image class, allows you to load from file via Drawable#createFromPath.

This SO question suggests Drawable#createFromPath doesn't work on paths beginning with file://, so depending on your use case you may want to precede that with Uri#parse/Uri#getPath.

Once you have a Drawable, you can display it in one of two ways: put an ImageView in your app and call its setImageDrawable method, or set the Drawable as your background image via View#setBackground (note that setBackground was only added in API 16 - in prior versions, you should call View#setBackgroundDrawable).

Putting all of this together, we end up with the following (untested):

private void loadImage(String imagePath) {
    Uri imageUri;
    String fullImagePath;
    Drawable image;
    ImageView imageDisplay;

    imageUri = Uri.parse(imagePath);
    fullImagePath = imageUri.getPath();
    image = Drawable.createFromPath(fullImagePath);

    imageDisplay = (ImageView) findViewById(R.id.imageDisplay);
    /*if image is null after Drawable.createFromPath, this will simply
      clear the ImageView's background */

    /*if you want the image in the background instead of the foreground,
      comment the line above and uncomment this bit instead */

You should be able to modify this to work with any View just by replacing imageDisplay's declared type with the appropriate View type and changing the cast on findViewById. Just make sure you're calling setBackground, not setImageDrawable, for a non-ImageView View.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download