[英]Why aren't my images downloading into ImageViews?
我是原生Android开发的新手。 我的应用程序当前正在做什么:
从我们的服务器下载图像网址的JSON
为每个图像将一个ImageView
添加到ListView
我已经获取了JSON
,现在正在使用ImageAdapter
(扩展BaseAdapter
)来填充ListView
,但是我遇到了一个错误:
OpenHttpGETConnection
函数中创建InputStream
期间,我得到println needs a message
。 这是我的代码(按从高到低的顺序删除了不必要的代码):
加载JSON后,我的onPostExecute
代码将运行以启动适配器:
private class DownloadImagesTextTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... urls){ return getImages(urls[0]); } @Override protected void onPostExecute(String result){ JSONArray images = null; images = new JSONArray(result); // TURN images into array of imageviews ListView listView = (ListView) findViewById(R.id.list); @here----> listView.setAdapter(new ImageAdapter(getBaseContext(), images)); Log.d("DownloadTextTask", images.toString()); } }
这是我的ImageAdapter
代码:
public class ImageAdapter extends BaseAdapter { private Context context; private JSONArray images; public ImageAdapter(Context c, JSONArray i){ context = c; images = i; } // returns an imageview view public View getView(int position, View convertView, ViewGroup parent){ ImageView imageView = new ImageView(context); try { String url = "http://www.example.com/" + images.get(position); @here----> imageView.setImageBitmap(getImageBitmap(url)); } catch (Exception e){ Log.d("LoadImage", e.getLocalizedMessage()); } imageView.setScaleType(ImageView.ScaleType.FIT_XY); return imageView; } }
这是我的getImageBitmap
函数:
private Bitmap getImageBitmap(String url){ Bitmap bitmap = null; InputStream in = null; try { @here----> in = OpenHttpGETConnection(url); } catch (Exception e) { @i_get @this ----> Log.wtf("OpenGET", e.getMessage() + ": " + url ); @error } bitmap = BitmapFactory.decodeStream(in); in.close(); return bitmap; }
最后,这是我的OpenHttpGETConnection
函数:
public static InputStream OpenHttpGETConnection(String url){ InputStream inputStream = null; HttpClient httpClient = null; HttpResponse httpResponse = null; httpClient = new DefaultHttpClient(); httpResponse = httpClient.execute(new HttpGet(url)); inputStream = httpResponse.getEntity().getContent(); return inputStream; }
这是相关的LogCat
行:(发生3个通过JSON文件传入的图像)
A/OpenGET﹕ println needs a message: http://www.example.com/image1.jpg
奇怪的是,在加载JSON数据时,我使用了相同的OpenHttpGETConnection
,所以我很确定这将返回正确的InputStream
对象。 将其用于文本和二进制数据(jpg)时有一些注意事项吗?
提前致谢!
首先,在适配器的getView()
方法中,您不回收项目。 看一下ViewHolder模式( http://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html )。 然后, getImageBitmap()
似乎在同一线程上执行,我想知道为什么它不会崩溃。 我猜你在那里下载了实际的图像。 它应该异步完成,并且应该发送ImageView
的引用,下载完成后,应该将其加载到其中。 当然,你不必在意,如果当你把bitmap
里面ImageView
你有良好的ImageView
屏幕上(因为它可能已被回收)。 要摆脱所有这些担忧,您可以使用Picasso library
( http://square.github.io/picasso/ ),这将为您完成所有这些工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.