-1

In my mainactivity I have the following snip

MainActivity.class

private Button btnx10;

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


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

I'm trying to access the button that is created in the onCreate() method from the method drawLines()
i.e. in the same class MainActivity.class but outside of this method.

When I am trying to access the button in the drawlines()method it's value is null.

How can I access the button?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
TeleJim
  • 317
  • 3
  • 20

4 Answers4

1

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;
}
Abhinav Suman
  • 940
  • 1
  • 9
  • 29
0

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

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

sanjeev
  • 1,664
  • 19
  • 35
0

Remove local declaration of Button again.

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

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
0

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;
}