- Home /
How to get static int variables from Java?
For example, when I try to get Toast.LENGTH_LONG variable, using:
using (AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast")) {
int length = toastClass.GetStatic<int>("LENGTH_LONG");
}
I get an error: InvalidCastException. Funnily, there is no InvalidCastException when using uint instead of int, but then I get a zero, instead of correct LENGTH_LONG value (which is 1). Everything works ok if I try to get a non-static int variable from Java, or when using a method (even a static one) to retrieve an int value, but GetStatic just doesn't work.
@Fattie: I thought we'd been over this a while ago...static has its place; telling people to never use it isn't helpful. I suspect that lukiluk is well past the point of needing general help with variable types.
@Fattie: I use static, Unity uses static. What do you think functions like Vector3.Lerp and hundreds of others are?
I think static is misused by new programmers frequently, but is clearly a very important part of any language. Using statics as a way of communicating between classes compiles but ends up with the "one thing gets hit, they all get hit" problem.
I know I couldn't do without static methods, properties and fields.
This question is about getting something out of a Droid Java program though - so probably a bit more related to the conversion of variable types between the two languages...
@lukiluk I guess we can better help you if you post the definition of that static var so we can confirm if the type is wrong? The long route around if AndroidJavaClass can't do it for any unknown reason, you should be able to use AndroidJNI but this is way more verbose.
Wo'there - this is getting a bit flamy - can we leave that alone please. This thread is now getting spammed and that is very unfair to the OP.
@Fattie is entitled to his opinions and with 11k karma points he has clearly helped a lot of people solve a lot of problems - many times involving a lot of hard work on his behalf. He also has a unique sense of humour!!! ;)
We don't agree about statics (or coroutines :) - but there you go. If you all don't $$anonymous$$d can we please just stop this debate unless it is technical and relevant to the question?
Answer by zombiezen · Feb 05, 2013 at 09:26 PM
I ran into the same problem when trying to get the android.os.Build.VERSION.SDK_INT
value. Here's what I did:
private static function GetSDKLevel() : int {
var clazz = AndroidJNI.FindClass("android.os.Build$VERSION");
var fieldID = AndroidJNI.GetStaticFieldID(clazz, "SDK_INT", "I");
var sdkLevel = AndroidJNI.GetStaticIntField(clazz, fieldID);
return sdkLevel;
}
Storing it as a variable is necessary because it comes back as a long
, not an int
, and there's not a convenient way to cast otherwise.
I have no idea why using the AndroidJNIClass doesn't work as expected.