Call Java methods and getting result (toString and other)

Let see on this code:

using UnityEngine;
using System.Collections;

public class javause : MonoBehaviour {
    public UnityEngine.UI.Text my_text;
    private AndroidJavaObject jo;

    void Start () {
        jo = new AndroidJavaObject("java.lang.String", "some_string");
    }
   
    void Update () {
        my_text.text = jo.CallStatic<string>("valueOf", "Hi!");
    }
}

In this case I will see the text “Hi”. If I write:

    void Update () {
        my_text.text = jo.CallStatic<string>("toString");
    }

I get nothing and see defaul text “New Text”.

Questions:

  • How to set Unity variable to value of string jo which is java string object?
  • How to call toString() method of the AndroidJavaObject?

I found the answer to second question:

void Update () {
    my_text.text = jo.Call<string>("toString");
}

You should use the AndroidJavaObject and AndroidJavaClass objects to interact with Android native (Java) classes.

When using these classes, always remember that:

  • AndroidJavaObject is the equivalent of an object instance. When you initialize it like you show in your example, it’s the same as invoking the java.lang.String constructor with a single string parameter “some_string”. The “jo” reference you get back is a reference to a java.lang.String object (wrapped as a AndroidJavaObject).
  • When invoking static methods, you should probably use the AndroidJavaClass object, which can be used for invoking static methods (or accessing static fields of a Java class).

To your questions:

In order to get the string from the ‘jo’ object reference you have:

jo = new AndroidJavaObject("java.lang.String", "some_string");
my_text.text= jo.Call<string>("toString");

Note that ‘toString’ is not a static method, so you should use Call and not CallStatic

1 Like

Thanks.
How to rewrite this code:

jo = new AndroidJavaObject("java.lang.String", "some_string");
my_text.text= jo.Call<string>("toString");

To the form like the next:

void Update () {
        my_text.text = jo; // error
                                          // jo as string ; error
                                          // (string) jo ; error
}

my_text.text= jo.Call(“toString”);

This already does that…