Android Network image displayed on ImageView
When I wrote this blog post, I participated in the development of a project, which involved a lot of network call problems. I remember when I started my android project, once encountered this problem, at that time in the online search, found a blog, now share with you, http://www.open-open.com/lib/view/open1376128628881.html
In fact, the idea of this article is problematic, because the network requires constant round-robin access, so it must be placed in the thread rather than directly in the onCreate method, I made some changes to this program and put them in the thread for update.
MainActivity. java code:
package com.test.picture;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.widget.ImageView;public class MainActivity extends Activity {private ImageView imageView;private String picturePath = "http://content.52pk.com/files/100623/2230_102437_1_lit.jpg";@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfinal Bitmap bitmap = returnBitMap(picturePath);imageView.post(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubimageView.setImageBitmap(bitmap);}});}}).start();}private Bitmap returnBitMap(String url) {URL myFileUrl = null;Bitmap bitmap = null;try {myFileUrl = new URL(url);} catch (MalformedURLException e) {e.printStackTrace();}try {HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();conn.setDoInput(true);conn.connect();InputStream is = conn.getInputStream();bitmap = BitmapFactory.decodeStream(is);is.close();} catch (IOException e) {e.printStackTrace();}return bitmap;}private void initView() {imageView = (ImageView) findViewById(R.id.picture);}}
This is the layout file code:
Of course, we also need to add the corresponding network permissions in AndroidManifest. xml.
In MainActivity. the onCreate method in java creates a new thread, but we also understand that we cannot operate the user interface in a non-UI thread, so we cannot directly operate the UI in the new thread, so we need to post the changes to the UI thread.
There is no problem with the above method. Thank you.