BitmapFactory抛出NullPointerException(有时)

时间:2012-02-11 23:25:14

标签: java android

我开始学习Android上的编程,但我遇到了Bitmap工厂的问题。这是代码:

public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {

    private MainThread gameThread;
    public ResourceManager resourceManager;
    public MainGamePanel (Context context) {
        super(context);
        getHolder().addCallback(this);

        try {
            Bitmap temp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        } catch (NullPointerException e) {
            Log.d(MainGamePanel.class.getSimpleName(), "Null Pointered!");
        }

        gameThread = new MainThread(getHolder(),this);
        setFocusable(true);
}

如果我尝试在此处制作位图,BitmapFactory会抛出NullPointerException

但是,当我稍后在onDraw()函数中执行此操作时:

protected void onDraw(Canvas canvas)
{
    //Add the drawing code here
    Bitmap temp = BitmapFactory.decodeResource(getResources(), R.drawable.sprite);
    canvas.drawBitmap(temp, 10, 10, null);
}

onDraw()函数由另一个线程运行:

public class MainThread extends Thread {
    private boolean running;
    private SurfaceHolder surfaceHolder;
    private MainGamePanel gamePanel;
    public MainThread(SurfaceHolder _surfaceHolder, MainGamePanel _gamePanel)
    {
        surfaceHolder=_surfaceHolder;
        gamePanel = _gamePanel;
    }
    public void run() {
        Canvas canvas;
        running = true;
        while(running)
        {
            canvas = null;
            try{
                canvas = this.surfaceHolder.lockCanvas();
                synchronized (surfaceHolder)
                {
                    //WHY DOES THIS (The folllowing line) WORK!????
                    this.gamePanel.onDraw(canvas);
                }
            }

            finally
            {
                if(canvas!=null)
                    surfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
    }
}

所以我的问题是:BitmapFactory为什么在onDraw()下工作但在构造函数中不工作?

感谢任何回答我问题的人!

0 个答案:

没有答案