This is strange, maybe someone can help with this. I have two classes and when I try to access variable from main class, value is always 0.0
MAIN CLASS
public class MainActivity extends Activity {
public float angleCurrent;
- do something whith angleCurrent
//System.out.println(angleCurrent); - I get right values
}
SECOND CLASS
public class SecondClass extends ImageView {
public float curAngle = new MainActivity().angleCurrent;
//System.out.println(curAngle); - I get 0.0 all the time
}
Code is just illustration.
There are a couple big issues at play here. First, why the behavior is occurring:
You are not accessing the variable from the first
MainActivityinstance inside ofSecondClass, you have created a new second instance ofMainActivity, so you are getting access to a different variable than the original.Now, the second issue surrounds the correct way to do this in Android. You should NEVER directly instantiate Activity instances. It is also not good practice to pass references to an Activity around any more than the framework already does. If your Activity needs to pass some information to your custom
ImageView, you should create a method on yourImageViewthat you can use for the Activity to pass the value forward (i.e.SecondClass.setCurrentAngle(angleCurrent))