I need to get an image from the web and display it on the main activity of my app. I am trying to put it inside a separate thread, with the following code (it goes inside the onCreate method):
Thread trd = new Thread(new Runnable(){
@Override
public void run(){
ImageView iv1 = (ImageView) findViewById(R.id.promo);
try{
URL url = new URL("http://www.domain.com/image.jpg");
InputStream content = (InputStream)url.getContent();
Drawable d = Drawable.createFromStream(content, "src");
iv1.setImageDrawable(d);
}
catch(Exception e){
e.printStackTrace();
}
}
});
trd.run();
This code is working properly and updating the UI with the image I am getting from the web.
Questions:
-
I heard that Android only allows you to modify the UI from the main UI thread, but it looks like with my code I am doing it from inside a separate thread. How come? Should I be worried my code might break for some reason?
-
Is the above code efficient to make sure my app UI will not freeze while waiting for the web image to be retrieved?
Yes you are modifying from a separate thread.
to set drawable inside a thread use, and make
das final.Is the above code efficient to make sure my app UI will not freeze while waiting for the web image to be retrieved?No as It will not run at all. and will through the
Exception.