我从我的 PHP 和 MySQL 数据库中获取图像 URL。这里的一切都很好,因为它Log.d
显示了带有有效图像 URL 的结果。
if (success == 1) {
JSONArray comments = json.getJSONArray("photos");
for (int i = 0; i < comments.length(); i++) {
JSONObject m = comments.getJSONObject(i);
final String filename = m.getString("filename");
final String extension = m.getString("extension");
String upload_at = m.getString("upload_at");
String uid = m.getString("uid");
runOnUiThread(new Runnable() {
@Override
public void run() {
Bitmap mThumbIds = fetchImage(filepath_min
+ filename + "." + extension);
Log.d("Photo URL", filepath_min + filename + "." + extension);
List<Bitmap> l = Arrays.asList(mThumbIds);
photoList = new ArrayList<Bitmap>(l);
}
});
}
}
// Instance of ImageAdapter Class
mHandler.postDelayed((new Runnable() {
public void run() {
imgGrid.setAdapter(new ImageAdapter(
PhotoViewerActivity.this, photoList));
}
}), 1000);
在此下方用于从给定的 URL 获取图像并作为位图返回。这里没什么问题,仅供参考想表明返回的是Bitmap。
public Bitmap fetchImage(String urlstr) {
try {
URL url;
url = new URL(urlstr);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setDoInput(true);
c.connect();
InputStream is = c.getInputStream();
Bitmap img;
img = BitmapFactory.decodeStream(is);
return img;
} catch (MalformedURLException e) {
Log.d("RemoteImageHandler", "fetchImage passed invalid URL: "
+ urlstr);
} catch (IOException e) {
Log.d("RemoteImageHandler", "fetchImage IO exception: " + e);
}
return null;
}
这是我在 GridView 中查看图像的 ImageAdapter。
public class ImageAdapter extends BaseAdapter {
private Context mContext;
List<Bitmap> list = new ArrayList<Bitmap> l;
public ImageAdapter(Context c, ArrayList<Bitmap> l) {
mContext = c;
list = l;
}
public Bitmap[] mThumbIds = list.toArray(new Bitmap[list.size()]);
@Override
public int getCount() {
return mThumbIds.length;
}
@Override
public Object getItem(int position) {
return mThumbIds[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(130, 130));
return imageView;
}
}
这是我的问题。活动中未显示任何图像。当我尝试在 Bitmap[] mThumbIds 中使用 fetch 数组硬编码 URL 时,它是成功的。
Bitmap[] mThumbIds = { fetchImage("http://...jpg"),
fetchImage("http://...jpg") }
我不知道怎么了。我试图Bitmap[] mThumbIds = list.toArray(new Bitmap[list.size()]);
将 ArrayList 转换为 Array。