我尝试以下方式,但我在iv.setImageBitmap(bm)获得Null Pointer Exception。 我尝试使用网格视图和布局Inflater设置带有文本的图像。我也进行了debuging过程,但我仍然无法获得解决方案。请检查以下代码。
public class CategoryAdapter extends BaseAdapter {
private Context mContext;
public static final int ACTIVITY_CREATE = 10;
int id=-1;
public CategoryAdapter(Context c) {
mContext = c;
}
public int getCount() {
return CategorylogoActivity.logoarray.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Bitmap bm=null;
ImageView iv = null ;
TextView tv=null;
View v;
if(convertView==null){
@SuppressWarnings("static-access")
LayoutInflater li = (LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.category_icon, null);
tv= (TextView)v.findViewById(R.id.icon_text);
iv = (ImageView)v.findViewById(R.id.icon_image);
}
else
{
v = convertView;
}
try {
URL aURL = new URL(CategorylogoActivity.logoarray[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// Buffered is always good for a performance plus.
BufferedInputStream bis = new BufferedInputStream(is);
// Decode url-data to a bitmap.
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
iv.setImageBitmap(bm);
tv.setText(CategorylogoActivity.namearray[0]);
return v;
答案 0 :(得分:0)
您不应该在适配器中执行URLConnection,这将尝试执行多重连接,因为每次在适配器中显示该视图时都会调用getView()。而是在一个单独的类中处理连接。
答案 1 :(得分:0)
static class viewHolder {
ImageView iv = null ;
TextView tv=null;
}
public View getView(int position, View convertView, ViewGroup parent) {
Bitmap bm=null;
viewHolder vh;
View v;
if(convertView==null){
vh = new viewHolder();
@SuppressWarnings("static-access")
LayoutInflater li = (LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.category_icon, null);
vh.tv= (TextView)v.findViewById(R.id.icon_text);
vh.iv = (ImageView)v.findViewById(R.id.icon_image);
v.setTag(vh);
}
else
{
vh = (viewHolder)convertView.getTag();
v = convertView;
}
try {
URL aURL = new URL(CategorylogoActivity.logoarray[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// Buffered is always good for a performance plus.
BufferedInputStream bis = new BufferedInputStream(is);
// Decode url-data to a bitmap.
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
vh.iv.setImageBitmap(bm);
vh.tv.setText(CategorylogoActivity.namearray[0]);
return v;
你必须使用viewHolder类型的对象,当convertView不为null时,你的iv imageView为null。所以你在null对象上使用setImageBitmap()。试试我的代码。
HTH。