Cannot load drawable in image view Android Studio

75
October 14, 2021, at 6:20 PM

I am trying to capture a url from a EditText, download the image with that url and set it to an ImageView. I don't know why but it doesn't show any image when I run the program. If this helps it returns a exception: android.os.NetworkOnMainThreadException

This is my main code:

enter image description here

Answer 1

You should run your Network code off your UI Thread or the Main Thread. Network Operations are intensive and take some time to complete and end up blocking the Main Thread thus the exception NetworkOnMainThreadException.

To get around this you can start a new background thread to run your Network code:

public class MainActivity extends AppCompatActivity {
    //declare drawable as a class variable
    Drawable drawable;
......
onCreate(...) {.... }
buttonPressed(View view) { ...}
public Drawable loadImageFromNet(String url) {
      //lambda for Java 8
        new Thread(() -> {
            // do network operation here
            try {
                InputStream is = (InputStream) new URL(url).getContent();
                drawable = Drawable.createFromStream(is, "src name");
            } catch (Exception e) {
                System.out.println("Exc" + e);
                drawable = null;
            }
        }).start();
        return drawable;
    }
}

The other code remains the same and code should work with this test URL:

https://sample-videos.com/img/Sample-jpg-image-50kb.jpg

Cheers ...

READ ALSO
React Framer-motion: Trying to add animation based on navigating back or forward

React Framer-motion: Trying to add animation based on navigating back or forward

I have made a replica of my component in the code sandbox link below:

61
window.print() not working on android devices

window.print() not working on android devices

I have prepared a method that prints the element , but it only works properly on the Windows platform and does not work on the Android platformAfter searching, I realized that Google Cloud Print can be used, but I realized that it is no longer supported

46
How to separate and rotate numbers in integer?

How to separate and rotate numbers in integer?

I have a small problem, i think, it´s simple, but i don´t know, how to manage it of properly

53