【问题标题】:Android Studio: Bitmap to ImageView ErrorAndroid Studio:位图到 ImageView 错误
【发布时间】:2018-04-03 13:10:06
【问题描述】:

将位图附加到 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 文件,我也把它缩小了很多。

【问题讨论】:

  • 请尝试使用 context.getResources() 而不是 getResources()..
  • 您好,不幸的是,这不起作用...在我的主要活动(仅扩展 AppCompatActivity)中,我通过以下代码调用我的 SimulationView: SimulationView view = view = new SimulationView(this).. . 这是我应该通过的吗?
  • iBall 为空,关于错误消息。试着找出原因,这就是答案。

标签: android bitmap nullpointerexception imageview drawable


【解决方案1】:

在 OnCreate() 方法中初始化 iBall

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 2017-09-12
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多