Reputation: 78
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.
Upvotes: 2
Views: 892
Reputation: 63293
There are a couple big issues at play here. First, why the behavior is occurring:
You are not accessing the variable from the first MainActivity
instance inside of SecondClass
, you have created a new second instance of MainActivity
, 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 your ImageView
that you can use for the Activity to pass the value forward (i.e. SecondClass.setCurrentAngle(angleCurrent)
)
Upvotes: 1
Reputation: 3846
If you are looking to a View to access variables in the activity, it's not going to work. You need to add a setMethod to your custom view and set the value from the activity. Chthlu is right about why you aren't getting a value: new
creates a different instance than the one you have on screen. You should never call new
on an Activity class. You shouldn't even HAVE a constructor for an Activity, you should setup everything in the onCreate
method.
Upvotes: 0