public class GridViewAdapter extends BaseAdapter {
private List
String>> list;
private Context context;
public GridViewAdapter(Context context,
List
String>> list) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup
parent) {
MyView tag;
if (convertView == null) {
View v = LayoutInflater.from(context).inflate(
R.layout.gridview_list, null);
tag = new MyView();
tag.imageView = (ImageView)
v.findViewById(R.id.grid_image);
tag.textView = (TextView)
v.findViewById(R.id.grid_time);
v.setTag(tag);
convertView = v;
} else {
tag = (MyView) convertView.getTag();
}
String image_path = list.get(position).get("itemImage");
String text = list.get(position).get("itemText");
Bitmap bm = getBitMap(context, image_path);
if (bm == null) {
bm =
BitmapFactory.decodeResource(context.getResources(),
R.drawable.error);
Log.i("BitmapPicture", "picture is null!!");
}
Bitmap newBit = Bitmap.createScaledBitmap(bm, 400, 300,
true);
tag.imageView.setImageBitmap(newBit);
tag.textView.setText(text);
return convertView;
}
public synchronized Bitmap getBitMap(Context c, String url)
{
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
bitmap = BitmapFactory.decodeResource(c.getResources(),
R.drawable.error); // 当网络连接异常后,给个默认图片
return bitmap;
}
try {
// 打开网络连接
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream(); // 把得到的内容转换成流
int length = (int) conn.getContentLength(); // 获取文件的长度
if (length != -1) {
byte[] imgData = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, imgData, destPos, readLen);
destPos += readLen;
}
bitmap = BitmapFactory.decodeByteArray(imgData, 0,
imgData.length);
}
} catch (IOException e) {
bitmap = BitmapFactory.decodeResource(c.getResources(),
R.drawable.error);
return bitmap;
}
return bitmap;
}
}
class MyView {
ImageView imageView;
TextView textView;
}