Android Studio:Bitmap到ImageView错误

fut*_*imm 3 android bitmap nullpointerexception drawable imageview

将Bitmap附加到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
Run Code Online (Sandbox Code Playgroud)

我知道它是一个空指针异常,但我不知道为什么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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 5

在OnCreate()方法中初始化iBall

iBall = (ImageView)findViewById(R.id.image);
Run Code Online (Sandbox Code Playgroud)