AndroidJavaClass. Call returns null ptr.

Hey everybody. So, I have a java class, as such:

package com.example.test;

import android.app.Activity;
import android.os.Bundle;

public class test extends Activity {
	
	public static test instance;

	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        test.instance = this;
	}

	
	public String getHello() {
		return "Hello";
	}
}

And in Unity, I have placed the .jar file in the Plugins → Android folder. I have a c# class on the main camera, as such:

using UnityEngine;
using System.Collections;

public class CheckSDK : MonoBehaviour {

	public AndroidJavaClass _nabiSDK;
	private string str = "NOTHING";

	void OnGUI() {

		if(GUI.Button(new Rect(300, 0, 100, 50), "Get mode...")) {
			AndroidJavaClass jc = new AndroidJavaClass("com.example.test.test" );
			AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("instance");
			print(jo.Call<string>("getHello"));
		}
	}
}

UPDATE: So, I am pressing the button on the device, but I only get an exception that reads: JNI: Init’d AndroidJavaObject with null ptr! Can anyone explain what I’m not doing, and why it is required? I’m going crazy trying to figure it out!

I am deploying to android -- thanks for the update! I'll try it out, and keep you posted. Cheers, Simon

–

1 Answer

1

After obtaining the Java class reference you have to get an instance reference to the actual object and then do your method call on this:

AndroidJavaClass jc = new AndroidJavaClass("com.example.test.test" );
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("instance");
str = jo.Call<string>("getHello");

This requires an instance variable in the Java class:

public static test instance;

which would typcially be set in the onCreate method of your Java activity

test.instance = this;

Best,
Ben

To avoid confusion I would recommend to name your class Test with capital T.

–

Oh! Really? That's it? But what does "instance" refer to? Does it have to be "instance"? Why use that word? How do you know to use it? You're the man, Simon

–

Please see my extended answer, I've edited it...

–

Awesome. You are the man. Again.

–

OK, great. Thanks for accepting it as the answer.

–