Hi there;
I’m trying to communicate between an activity and mi sketch, but my sketch always expect static values, ¿is there any trick or mode to pass variable values?
Here you have an example:
I can do this in the activity:
public static int getInterger(){
int b =(int)(Math.random()*900);
return b;
}
And receive in the sketch:
public void draw() {
background(0);
ellipse(width / 2, height / 2, MainActivity.getInterger(),MainActivity.getInterger() );
}
But, what I want and I can’t, is to receive non-static values.
This is what I can’t do:
MainActivity:
public static float getValue(){
return (float) (carState.velocity);
}
Sketch:
public void draw() {
background(255);
ellipse(MainActivity.getValue() ,mouseY,100,100);
}
carState.velocity have the variable value
Thanks for the help
static
methods are stateless. That is, they can’t access the keyword this
, either explicitly or implicitly.
In your posted example:
public static float getValue() {
return (float) carState.velocity;
}
B/c variable carState isn’t declared anywhere in that method, neither as a local variable nor as a method parameter, it’s implied that carState is actually a field belonging to that method’s class
.
So it has an implicitly hidden this
keyword: return (float) this.carState.velocity;
Which isn’t valid inside static
methods under Java.
As a workaround, your method can request a MainActivity parameter in order to access carState:
public static float getValue(final MainActivity mainAct) {
return (float) mainAct.carState.velocity;
}
Or more directly as a parameter of the same datatype as carState instead:
public static float getValue(final DatatypeOfCarState carState) {
return (float) carState.velocity;
}
2 Likes
@GoToLoop thank you so much, couldn’t try till today.
Passing the MainActivity I can get the value; with the parameter is a little bit harder (other person code is implicated, and that complicate the things) and in this way is working perfectly
Thanks again