安卓工作室 : Bitmap to ImageView Error

标签 android bitmap nullpointerexception imageview drawable

我在将位图附加到 ImageView 时遇到问题。这是我得到的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: accelerometer.example.com.accgame, PID: 25897
...
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference

我知道这是一个空指针异常,但我不知道为什么 getResources() 返回 null... 这是我的构造函数类:

public SimulationView(Context context) {
    super(context);
    mXOrigin = 50;
    mYOrigin = 50;

    mHorizontalBound = 100;
    mVerticalBound = 100;

    //Sensor Manager
    sensorManager = (SensorManager)context.getSystemService(SENSOR_SERVICE);

    Bitmap ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
    iBall.setImageBitmap(ball);

    mBitmap = Bitmap.createScaledBitmap(ball, BALL_SIZE, BALL_SIZE, true);
    Bitmap basket = BitmapFactory.decodeResource(getResources(), R.drawable.basket);
    mBasket = Bitmap.createScaledBitmap(basket, BASKET_SIZE, BASKET_SIZE, true);
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inDither = true;
    opts.inPreferredConfig = Bitmap.Config.RGB_565;
    mField = BitmapFactory.decodeResource(getResources(), R.drawable.field, opts);

    WindowManager mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
    mDisplay = mWindowManager.getDefaultDisplay();
}

基本上错误突出显示行 iBall.setImageBitmap(ball);

就图像本身而言,我确保将其放在 drawables 文件夹中。这是一个 .jpg 文件,我也将它缩小了很多。

最佳答案

在 OnCreate() 方法中初始化 iBall

iBall = (ImageView)findViewById(R.id.image);

关于安卓工作室 : Bitmap to ImageView Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46881686/

相关文章:

javascript - 将数据从 Native Activity 传递到 WebView

java - 属性文件不起作用

java - 尝试将对象实例写入 ObjectOutputStream 时出现 NullPointerException

c# - 如何在 C# 中为插件创建图标属性?

java - 如何在android中从不同形状的位图中切出一个圆圈

c# - 如何将分辨率为 32767 x 32767 的 C# .NET WriteableBitmap 保存为 JPG 或 PNG

java - JLabel空指针异常

android - 在 ListView 中选择任何列表项时不调用 OnItemSelected 方法

android - 谷歌地图 LatLngbounds 不工作

Android动态加载ListView