我想在结果为空时显示默认图片,这是我的尝试:
getBitmapFromURL
和一个使用它的类:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
connection.disconnect();
return myBitmap;
} catch (IOException e) {
// tasvirdimg.setImageResource(R.drawable.p3_books);
e.printStackTrace();
return null;
}
}
}
class RetrievePic extends AsyncTask<String, String, Bitmap>{
@Override
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
return JSONCommands.getBitmapFromURL(url);
}
}
在ListAdapter
执行课程:
// tasvirlimg.setImageResource(R.drawable.p3_books);
RetrievePic retPic = new RetrievePic();
retPic.execute(JSONCommands.firstURL + MainActivity.books_array.get(position).tasvir);
Bitmap img = null;
try {
img = retPic.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
tasvirlimg.setImageResource(R.drawable.p3_books);
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
tasvirlimg.setImageResource(R.drawable.p3_books);
e.printStackTrace();
}
tasvirlimg.setImageBitmap(img);
当图书图片为空时,它不会显示任何内容,但我希望它显示默认的图片来源为R.drawable.p3_books
。请帮忙。谢谢。
答案 0 :(得分:0)
你可以试试这个:
if(img == null)
{
tasvirlimg.setImageDrawable(R.drawable.p3_books);
}
else
{
tasvirlimg.setImageBitmap(img);
}
答案 1 :(得分:0)
为什么不在xml中设置项目的默认pic,然后在result不为null时替换默认pic
<ImageView
...
android:src="@drawable/p3_books"
/>
编辑:
class RetrievePic extends AsyncTask<String, String, Bitmap>{
final image = (ImageView) findViewById(R.id.limg_tasvir);
@Override
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
return JSONCommands.getBitmapFromURL(url);
}
@Override
protected void onPreExecute() {
runOnUiThread(new Runnable() {
@Override
public void run() {
image.setBackgroundResource(R.drawable.p3_books);
}
});
}
}
答案 2 :(得分:0)
你想要做的是你的适配器的getView()
方法的实现,像这样,
...
final imageView = ...;
imageView.setImageBitmap(defaultBitmap);
new AsyncTask<Void,Void,Bitmap>() {
public Bitmap doInBackground(Void... params) {
// get bitmap from `net, or return null if failure
}
public void onPostExecute(Bitmap result) {
if (result != null) {
imageView.setBitmap(result);
}
}
}.execute();
这样,默认设置。如果您碰巧获得了网络结果,请更改默认值。