Question

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.

Was it helpful?

Solution

Becaues you need to call

setContentView(R.layout.layoutXML); 

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.getHolder

Suggested 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top