Button variable turns to null after calling method

情到浓时终转凉″ 提交于 2019-11-29 18:49:21

Since you have declared the Button in Scope of Method onCreate()

Button btnx10=(Button)findViewById(R.id.MainCOPbtn);

and you are trying to access it outside of the method onCreate(), that makes it inaccessible outside of this method.

Just make the reference on class level (Globally) and use the same Reference in onCreate() method.

you can do this:-

private Button btnx10;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    btnx10 = (Button)findViewById(R.id.MainCOPbtn);
    DrawLines();
}


private void drawLines(){
   float centerYOnImage1 = btnx10.getHeight()/2;
}

Change the code to btnx10= findViewById(R.id.MainCOPbtn);

You are casting Button in the declaration which makes global variable inaccessible.

Remove local declaration of Button again.

Just use btnx10=(Button)findViewById(R.id.MainCOPbtn); in onCreate()

You are declaring Button btnx10 twice. Remove the local declaration. You should declare outside the method, and define inside the method.

Class MainActivity...
private Button btnx10;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    btnx10=(Button)findViewById(R.id.MainCOPbtn); //MINOR CORRECTION IN THIS LINE
    DrawLines()    
}

private void drawLines() {
     float centerYOnImage1=btnx10.getHeight()/2;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!