MainActivity.java @override onPostExecute方法
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(moviesArray.get(0).getTitle());
ImageView iv = (ImageView) findViewById(R.id.imgView);
String imageUrl= "http://www.learn2crack.com/wp-content/uploads/2014/04/node-cover-720x340.png";
Bitmap bitmap = GetImageFromURL.getBitmap(imageUrl);
iv.setImageBitmap(bitmap);
GetImageFromURL.java
public class GetImageFromURL {
public static Bitmap getBitmap(String imgUrl){
Bitmap b = null;
try {
URL url = new URL(imgUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is = connection.getInputStream();
b = BitmapFactory.decodeStream(is);
}catch (Exception e){
}
return b;
}
}
activity_main.xml中
<TextView
android:id="@+id/textView"
android:background="#00ff00"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/imgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/im"/>
我想显示网址中的图片。但我不知道为什么图像不显示而且没有错误发生。请帮助!
答案 0 :(得分:0)
试试这个:
public class Mainpage extends ActionBarActivity implements OnClickListener {
ImageView iv1
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
iv1 = (ImageView) findViewById(R.id.imageView1);
LoadImageFromURL task = new LoadImageFromURL();
task.execute();
}
public class LoadImageFromURL extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
try {
URL url = new URL("http://www.learn2crack.com/wp-content/uploads/2014/04/node-cover-720x340.png");
InputStream is = url.openConnection().getInputStream();
Bitmap bitMap = BitmapFactory.decodeStream(is);
iv1.setImageBitmap(bitMap);
return bitMap;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}