在我的應用程序中,當你點擊按鈕,然後我從網址下載圖片。它正確地顯示一些圖像,但有一段時間它顯示爲空。 *問題是某些時候位圖對象(即代碼中的「結果」)返回null。 *請任何人都可以幫助我。android - 從url下載圖片顯示不正確
以下是我的代碼
try
{
String ImageUrl = ((eachReview)RB_Constant.revht.get(title_value)).UserImageUrl;
System.out.println("Image Url:"+ImageUrl);
if(ImageUrl != null)
{
DownLoadImageInAThreadHandler(ImageUrl,holder);
}
else
{
System.out.println("Image url is null then display the default image");
holder.userImage.setImageResource(R.drawable.defaultuserimage);
}
}
catch(Exception e){
System.out.println("Error from Userimage fetching.."+e.toString());
}
private void DownLoadImageInAThreadHandler(final String imgurl,final ViewHolder holder)
{
//Thread for getting the attributes values
Thread t = new Thread()
{
public void run()
{
try
{
Bitmap drawable = getDrawableFromUrl(imgurl);
System.out.println("Drawable(after downloading):"+drawable);
if(drawable != null)
{
holder.userImage.setImageBitmap(drawable);
}
else
{
System.out.println("after downloading drawable is null then set the default image");
holder.userImage.setImageResource(R.drawable.defaultuserimage);
}
}
catch(Exception exp)
{
System.out.println("Exception in DownLoadImageInAThread : " + exp.getMessage());
}
}
private Bitmap getDrawableFromUrl(String imageUrl)
{
try
{
URL myFileUrl = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
final Bitmap result = BitmapFactory.decodeStream(is);
is.close();
new Thread() {
public void run() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if(result != null)
{
result.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
}
}
}.start();
return result;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
};
t.start();
}
您是否在瀏覽器中檢查了圖片URL?那裏有圖片嗎?您所嘗試下載的圖片可能無法在所提供的網址上顯示。 – 2011-12-29 10:36:46
是的,圖像可用。 PLZ檢查我的線程調用是否正確? – naresh 2011-12-29 11:02:09
您是否考慮切換到畢加索? [here] http://stackoverflow.com/questions/22330772/why-to-use-android-picasso-library-to-download-the-images – Sarpe 2014-03-11 16:50:31