BitmapFactory throws NullPointerException (sometimes)
<p>I'm beginning to learn programming on android, but I have come across a problem with Bitmap factory. Here is the code:</p>

<pre><code>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);
}
</code></pre>

<p>If I try to make a bitmap here, BitmapFactory throws a NullPointerException. </p>

<p>BUT, when I do it later in the onDraw() function it work:</p>

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

<p>The onDraw function is run by another thread:</p>

<pre><code>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);
            }
        }
    }
}
</code></pre>

<p>So my question is: Why does BitmapFactory work under onDraw but not in the constructor?</p>

<p>Thanks to anyone who answers my question!</p>
