我的代码中出现NullPointerException错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
我有一个位图,它是从Web服务接收的字节中解码得到的。我不明白这个错误。您能帮我纠正代码吗?
我是Android编程的新手,我渴望学习!
这是我的代码:
public class CatListAdapter extends ArrayAdapter {
ArrayList<String> alNames;
ArrayList<String> alImages;
ArrayList<String> alId;
private Activity context;
float cornerRadius = 50.0f;
ImageView imageFlag;
public CatListAdapter(Activity context, ArrayList<String> alNames, ArrayList<String> alImages,
ArrayList<String> alId) {
super(context, R.layout.category_list, alNames);
this.context = context;
this.alNames = alNames;
this.alImages = alImages;
this.alId = alId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
row = inflater.inflate(R.layout.category_list, null, true);
TextView textViewCountry = (TextView) row.findViewById(R.id.txtcatname);
imageFlag = (ImageView) row.findViewById(R.id.catimage);
textViewCountry.setText(alNames.get(position));
if (String.valueOf(alImages.get(position)) != "") {
byte[] decode = Base64.decode(alImages.get(position), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
bitmapResize(bitmap);
}
return row;
}
public void bitmapResize(Bitmap imageBitmap) {
float widthbmp = imageBitmap.getWidth();
float lengthbmp = imageBitmap.getHeight();
// Get Screen width
DisplayMetrics displaymetrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = displaymetrics.heightPixels / 3;
float width = displaymetrics.widthPixels / 3;
int convertHighet = (int) hight, convertWidth = (int) width;
// high length
if (lengthbmp > hight) {
convertHighet = (int) hight - 20;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, convertWidth, convertHighet, true);
}
// high width
if (widthbmp > width) {
convertWidth = (int) width - 20;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, convertWidth, convertHighet, true);
imageFlag.setImageBitmap(imageBitmap);
}
}
}
答案 0 :(得分:0)
首先,请检查byte[] decode
是否返回非空值。
然后,您在下面添加以下代码行:
Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
您可以像这样使用bmOptions:
Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length,bmOptions);
要了解实现,您可以参考以下链接:https://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inJustDecodeBounds
编码愉快!