我有一个url传递给一个活动,我试图从url全屏显示图像,但它抛出一个主网络线程异常。
据我所知,我相信我必须把这个方法放在异步任务中,但我似乎根本无法理解它。那么我如何将这个方法放在异步任务中呢?
FullScreenImageView.java
public class FullscreenImageView extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = getIntent().getStringExtra("SelectedImageURL");
try {
ImageView i = (ImageView)findViewById(R.id.imgView);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
它应该是这样的。
在doInBackground
中,您可以获得图片,并在onPostExecute
中设置图片
private class DownloadFilesTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(urls[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
ImageView i = (ImageView)findViewById(R.id.imgView);
i.setImageBitmap(bitmap);
}
}
然后,您在onCreate
方法
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = getIntent().getStringExtra("SelectedImageURL");
new DownloadFilesTask ().execute(url);
}
答案 1 :(得分:0)
将您的网络任务放在AsyncTask的doInBackground()
方法中,如下所示:
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
//ImageView i = (ImageView)findViewById(R.id.imgView);Put this line in onPreExecute() method
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
// i.setImageBitmap(bitmap);//and this one on postExecute() method
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
答案 2 :(得分:0)
使用findViewById()初始化yourImageView
后使用Picasso;
Picasso.with(context).load(url).into(yourImageView)