In my activity, I has some views and a surfaceView.
Here is my first code in onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upBtn = (Button) findViewById(R.id.upBtn);
// and more widget here
surface = (SurfaceView) findViewById(R.id.surfaceView);
this.holder = surface.getHolder(); // NullPointerException
setContentView(R.layout.view);
If I change the above code by taking surfaceView and getHolder() in onResume() (I have tried many times to have this result), no error:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upBtn = (Button) findViewById(R.id.upBtn);
// and more widget here
// surface = (SurfaceView) findViewById(R.id.surfaceView); //cancel
// this.holder = surface.getHolder(); // cancel
setContentView(R.layout.view);
public void onResume() {
surface = (SurfaceView) findViewById(R.id.surfaceView);
this.holder = surface.getHolder(); // No Error now
Please explain for me.
Becaues you need to call
before you call
findViewById(R.id.viewID). that is why your findview by id returning nul, and you probably getting nullPointerException when you are calling surfaceView.getHolderSuggested solution is, Create a layout.xml file which should have surfaceView inside any layout.
in your Activity’s oncreate call
setContentView(R.layout.layoutXML);and after this you can retrieve surface view by findViewByID and do whatever you want with it.