我要做的是:我希望我的应用程序从 Internet 下载图像并将其保存到手机的内部存储器中的应用程序专用位置。如果列表项没有可用的图像(即在 Internet 上找不到),我希望显示默认占位符图像。这是我在 list_item_row.xml 文件中定义的默认图像。
在我的 ListActivity 文件中,我正在调用我编写的 CustomCursorAdapter 类的实例。它在 CustomCursorAdapter 中,我正在遍历所有列表项并定义需要映射到视图的内容,包括通过尝试从内部存储器读取图像文件。
我已经看到了关于这个主题的几个问题,但是这些示例要么特定于外部手机内存(例如 SDCard),要么涉及保存字符串而不是图像,要么涉及使用 Bitmap.CompressFormat 来降低文件的分辨率(这在我的情况,因为这些图像将是已经很小分辨率的小缩略图)。尝试将每个示例中的代码拼凑起来很困难,因此我询问了我的具体示例。
目前,我相信我已经编写了有效的代码,但没有为我的列表项显示任何图像,包括默认的占位符图像。我不知道问题是由无效的下载/保存代码还是无效的读取代码引起的 - 我不知道如何检查内部存储器以查看图像是否存在,这无济于事。
无论如何,这是我的代码。任何帮助将不胜感激。
ProductUtils.java
public static String productLookup(String productID, Context c) throws IOException {
URL url = new URL("http://www.samplewebsite.com/" + productID + ".jpg");
URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();
FileOutputStream output =
c.openFileOutput(productID + "-thumbnail.jpg", Context.MODE_PRIVATE);
byte[] data = new byte[1024];
output.write(data);
output.flush();
output.close();
input.close();
}
CustomCursorAdapter.java
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
String fileName =
cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_IMAGE_FILE_PATH));
Bitmap bMap = BitmapFactory.decodeFile(fileName);
thumbnail.setImageBitmap(bMap);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list_item_row, parent, false);
bindView(v, context, cursor);
return v;
}
}