From the logcat I understand that the Activity crashes because of NullPointerException causes by this line of code.
mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),
R.id.picture, imageWidth, imageHeight));
I have read articles about similar problem but still getting NullPointerException. I think that mistake right under my nose, but still I can't catch it.
Where should I put this line to avoid NullPointerException?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
ImageView mImageView = (ImageView) findViewById(R.id.picture);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.picture, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),
R.id.picture, imageWidth, imageHeight));
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
and here is ImageView from layout.
<ImageView
android:layout_height="240dp"
android:layout_width="199dp"
android:src="@drawable/galaxy"
android:id="@+id/picture"
android:layout_gravity="center_horizontal"
android:scaleType="fitCenter"
android:layout_weight="0.19" />