문제

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

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top