I just wanted to Grab an image from a URL and to display it in an imageview
The code:
public class MainActivity extends Activity {
// declare internal using controls
private TextView txtUrl;
private ImageView imgView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView =(ImageView)findViewById(R.id.imageView1);
Drawable drawable=null;
drawable = grabImageFromUrl("http://blog.sptechnolab.com/wp-content/uploads/2011/02/c2.jpg");
imgView.setImageDrawable(drawable);
}
private Drawable grabImageFromUrl(String url) {
try {
return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
I am having this error:
09-04 20:34:18.712: E/AndroidRuntime(1156): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: android.os.NetworkOnMainThreadException
I would appreciate your help please be specific in your answers
Is your app configured with Internet permissions? That is, do you have the following in your app’s manifest?
FOLLOW UP: Also, the error seems to be saying you shouldn’t do network access on your app’s UI thread. It’s generally a bad practice to do any long blocking I\O on your app’s UI thread. Try using an AnycTask, or you might even have a look at some of the code in LazyList.
EXAMPLE: add this as an inner class to your activity:
Then call it like this from your onCreate: