在我的应用中,当您点击按钮时,我正在从网址下载图片。它正确显示图像一段时间但有时显示为空。 *问题有时候位图对象(即代码中的“结果”)返回null。 *请任何人帮助我。
以下是我的代码
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();
}
答案 0 :(得分:0)
尝试将getDrawableFromUrl设为:
public static Drawable getDrawableFromUrl(String url) {
Drawable image = null;
try {
InputStream in = (java.io.InputStream) new java.net.URL(url).getContent();
if (in != null) {
image = Drawable.createFromStream(in, "image");
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return image;
}
也不要在同一功能内压缩图像。尝试成功接收图像后执行此操作。将getDrawableFromUrl函数写入线程但在同一个类中更多一件事。希望这对你有用。