(Android Unity plugin) i created a simple plugin, expected 123, got 0 - java

I'm trying to make a plugin for Unity, but not even the simplest class works.
In Android Studio I created a library module, and in it, the following class:
package com.vuforia.android.pluginlib;
import static android.os.Looper.getMainLooper;
public class Multi {
static public Multi mult=new Multi();
static public int testes =123;
}
After that I added to the gradle of lib, the following configurations of a Task,to create the aar:
task copyPlugin (type : Copy){
dependsOn assemble
from ('build/outputs/aar')
into ('../../Assets/Plugins/Android')
include(project.name+'-release.aar')
}
In unity, I created some sprite, and added such script to it:
using UnityEngine;
public class movetest : MonoBehaviour
{
private AndroidJavaClass javaClass = null;
void Update()
{
javaClass = new AndroidJavaClass("com.vuforia.android.pluginlib.Multi");
int i = javaClass.GetStatic<int>("testes");
Debug.Log("->>"+i);
}
}
and when clicking on run, then what is received "- >>0".

I assume you are running in the editor because you stated "when clicking on run"..
Java plugins will not work in the editor. You would need to deploy to an Android device to test the functionality.

Related

Custom reference contributor is not being called while running tests for Intellij Platform plugin

I'm developing a plugin for Intellij Platform (actually for PhpStorm).
My plugin is providing references within string literal expressions in PHP language.
I created a reference contributor and a few reference provider classes.
My plugin works perfectly when I run it within PhpStorm.
My plugin becomes bigger, so I decided to write a few tests for it.
I created an unit test using IntelliJ IDEA "Create test" action and choosed JUnit 3.
When I run test (see code below), the class MyPsiReferenceContributor is not being accessed at all, and test expectedly fails ("Test failed").
parent.getReferences() returns an empty array (parent is an instance of StringLiteralExpressionImpl).
Is seems that MyPsiReferenceContributor is not being registered in test environment.
What should I do to make my reference contributor available within tests?
I used this project https://github.com/Haehnchen/idea-php-symfony2-plugin as example,
but my plugin is not using Gradle as theirs does.
This is how I registered my reference contributor in plugin.xml:
<extensions defaultExtensionNs="com.intellij">
<psi.referenceContributor implementation="com.zenden2k.MyFrameworkIntegration.MyPsiReferenceContributor"/>
</extensions>
This is my reference contributor:
public class MyPsiReferenceContributor extends PsiReferenceContributor {
// This is not being called while running tests! :(
#Override
public void registerReferenceProviders(PsiReferenceRegistrar registrar) {
MyPsiReferenceProvider provider = new MyPsiReferenceProvider();
registrar.registerReferenceProvider(StandardPatterns.instanceOf(StringLiteralExpression.class), provider);
}
}
This is my test case:
package com.zenden2k.MyFrameworkIntegration.tests;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.testFramework.fixtures.BasePlatformTestCase;
public class MyPsiReferenceContributorTest extends BasePlatformTestCase {
public void setUp() throws Exception {
super.setUp();
myFixture.copyFileToProject("GetStaticDatasourceFixture.php");
myFixture.copyFileToProject("user.xml");
}
protected String getTestDataPath() {
return "src/test/com/zenden2k/MyFrameworkIntegration/tests/fixtures";
}
public void testThatStaticDatasourceReferenceIsProvided() {
final ElementPattern<?> pattern = PlatformPatterns.psiElement().withName("test");
myFixture.configureByText("user.php",
"<?php \n" +
"class MyClass extends CXMLObject {\n" +
" public function test() {\n" +
" $this->getStaticDatasource('t<caret>est');\n" +
" }\n" +
"}\n"
);
PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
if (psiElement == null) {
fail("Fail to find element in caret");
}
PsiElement parent = psiElement.getParent();
final PsiReference[] ref = parent.getReferences();
for (PsiReference reference : ref) {
PsiElement element = reference.resolve();
if (pattern.accepts(element)) {
return;
}
}
fail("Test failed");
}
}
First of all - using Gradle is a recommended way for the development of the plugin. You may check the Building Plugins with Gradle docs section for more details.
There is a Simple Language Sample project available in the IntelliJ Platform SDK Code Samples repository that covers testing of the PSI References.

I can't open my class just find a BuildConfig file

For unknown reason a java file in an android studio project
has a sub arrow to BuildConfig class from an other package of an other project
/**
* Automatically generated file. DO NOT MODIFY
*/
package alsayed.aly.maintenanceplaner;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "alsayed.aly.maintenanceplaner";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
I tried to revert it but it is not working as the file just created now.
At build time, Gradle generates the BuildConfig class so your app code can inspect information about the current build.
You can also add custom fields to the BuildConfig class from your Gradle build configuration file using the buildConfigField() method and access those values in your app's runtime code. Likewise, you can add app resource values with resValue().
android {
...
buildTypes {
release {
// These values are defined only for the release build, which
// is typically used for full builds and continuous builds.
buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"")
resValue("string", "build_time", "${minutesSinceEpoch}")
...
}
debug {
// Use static values for incremental builds to ensure that
// resource files and BuildConfig aren't rebuilt with each run.
// If they were dynamic, they would prevent certain benefits of
// Instant Run as well as Gradle UP-TO-DATE checks.
buildConfigField("String", "BUILD_TIME", "\"0\"")
resValue("string", "build_time", "0")
}
}
}
In your app code, you can access the properties as follows:
Log.i(TAG, BuildConfig.BUILD_TIME);
Log.i(TAG, getString(R.string.build_time));

Jeta: How to create custom annotation processors

There is plenty of features that already available on Jeta, but what if something is missing. Can I create my own annotations and generate metacode for them?
Needed a step-by-step tutorial how to create custom Jeta processors.
How to create custom processors, step-by-step tutorial
Step 1: Hello, World project
For this tutorial let's create a simple Gradle project with one module app and with a single class SayHelloApp. This class writes Hello, World! to standard output.
For the illustration we are going to create Hello annotation that sets Hello, Jeta! string to the annotated fields.
Step 2: common module
First, we need a module that will be accessible in app and apt (will create shortly) modules. In common module we need two classes - Hello annotation and HelloMetacode interface:
Step 3: apt module
apt - is a module in which we'll create all the required for code generation classes. For this tutorial we need a processor that will handle our Hello annotation.
Note that this module depends on common module so we used Hello annotation as a parameter for the super constructor. By doing that we're saying to Jeta that we need all the elements annotated with given type. The module also depends on jeta-apt in order to get access to the Jeta classes.
Step 4: Processor
Created SayHelloProcessor now does nothing. Let's add some logic in it. The idea here is to generate java code that sets Hello, Jeta string to the fields annotated with Hello.
Note that Jeta uses JavaPoet to create java source code. It's really great framework by Square. Please, check it out on GitHub.
First, we need that our metacode implements HelloMetacode. To do that we'll add super interface to the builder:
MetacodeContext context = roundContext.metacodeContext();
ClassName masterClassName = ClassName.get(context.masterElement());
builder.addSuperinterface(ParameterizedTypeName.get(
ClassName.get(HelloMetacode.class), masterClassName));
Next, implement HelloMetacode by creating void setHello(M master) method:
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("setHello")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(void.class)
.addParameter(masterClassName, "master");
Finally, the statements for each element annotated with Hello, that Jeta passes in process method via roundContext parameter:
for (Element element : roundContext.elements()) {
String fieldName = element.getSimpleName().toString();
methodBuilder.addStatement("master.$L = \"Hello, Jeta\"", fieldName);
}
Here is the complete SayHelloProcessor listing:
package org.brooth.jeta.samples.apt;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeSpec;
import org.brooth.jeta.apt.MetacodeContext;
import org.brooth.jeta.apt.RoundContext;
import org.brooth.jeta.apt.processors.AbstractProcessor;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
public class SayHelloProcessor extends AbstractProcessor {
public SayHelloProcessor() {
super(Hello.class);
}
#Override
public boolean process(TypeSpec.Builder builder, RoundContext roundContext) {
MetacodeContext context = roundContext.metacodeContext();
ClassName masterClassName = ClassName.get(context.masterElement());
builder.addSuperinterface(ParameterizedTypeName.get(
ClassName.get(HelloMetacode.class), masterClassName));
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("setHello")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(void.class)
.addParameter(masterClassName, "master");
for (Element element : roundContext.elements()) {
String fieldName = element.getSimpleName().toString();
methodBuilder.addStatement("master.$L = \"Hello, Jeta\"", fieldName);
}
builder.addMethod(methodBuilder.build());
return false;
}
}
Step 5: Metacode
All the required for code generating classes are created and we're ready to try. But first, we need to add jeta.properties file in order to configurate Jeta. You can find more details about this file on this page. The file should be located in the root package. For our tutorial its content would be:
metasitory.package=org.brooth.jeta.samples
processors.add=org.brooth.jeta.samples.apt.SayHelloProcessor
Next, modify SayHelloApp. Instead of initializing text field we'll put Hello annotation on it:
public class SayHelloApp {
#Hello
String text;
}
And build.gradle:
group 'org.brooth.jeta-samples'
version '1.0'
buildscript {
repositories {
maven {
url 'https://plugins.gradle.org/m2/'
}
}
dependencies {
classpath 'net.ltgt.gradle:gradle-apt-plugin:0.5'
}
}
apply plugin: 'net.ltgt.apt'
apply plugin: 'java'
sourceCompatibility = 1.7
repositories {
mavenCentral()
jcenter()
}
compileJava {
options.sourcepath = files('src/main/java')
}
dependencies {
apt project(':apt')
compile project(':common')
compile 'org.brooth.jeta:jeta:+'
}
Now we're ready to generate metacode. Run next command in your console:
./gradlew assemble
If there is no problems so far, we'll see SayHelloApp_Metacode file under app/build directory:
Step 6: Controller
Controllers are the classes that apply metacode to the masters. Let's create one for HelloMetacode in app module:
package org.brooth.jeta.samples;
import org.brooth.jeta.MasterController;
import org.brooth.jeta.metasitory.Metasitory;
public class SayHelloController<M> extends MasterController<M, HelloMetacode<M>> {
public SayHelloController(Metasitory metasitory, M master) {
super(metasitory, master, Hello.class, false);
}
public void setHello() {
for (HelloMetacode<M> metacode : metacodes)
metacode.setHello(master);
}
}
Step 7: MetaHelper
MetaHelper is a simple static-helper class. You shouldn't use it in your project if you are not comfortable with static helpers. You can read more details about this class on this page.
Anyway, let's create MetaHelper in app module:
package org.brooth.jeta.samples;
import org.brooth.jeta.metasitory.MapMetasitory;
import org.brooth.jeta.metasitory.Metasitory;
public class MetaHelper {
private static MetaHelper instance;
private final Metasitory metasitory;
public static MetaHelper getInstance() {
if (instance == null)
instance = new MetaHelper("org.brooth.jeta.samples");
return instance;
}
private MetaHelper(String metaPackage) {
metasitory = new MapMetasitory(metaPackage);
}
public static void setHello(Object master) {
new SayHelloController<>(getInstance().metasitory, master).setHello();
}
}
Note that we must pass to MapMetasitory the same package ("org.brooth.jeta.samples") that we specified as metasitory.package in jeta.properties.
Step 8: Usage
The last step - we invoke our MetaHelper's method. Here is the complete listing of SayHelloApp:
package org.brooth.jeta.samples;
public class SayHelloApp {
#Hello
String text;
public SayHelloApp() {
MetaHelper.setHello(this);
}
public void sayHello() {
System.out.print(text);
}
public static void main(String[] args) {
new SayHelloApp().sayHello();
}
}
Finally, we can run SayHelloApp. In the console we should see:
Hello, Jeta
Links
This tutorial on GitHub
Jeta Website
Jeta on Android
Happy code-generating! :)

Android Unity plugin

I want to use unity android plugin in my AR application. The app has an AR camera, an image target and a 3d object.
ON ECLIPSE :
I create a default android application on eclipse. I click build automatically and check project name -> proeprties -> isLibrary. I create a class named Bridge on eclipse project.
Bridge.java
package com.tutorial.pluginforunity;
public class Bridge {
public static int ReturnInt() {
return 5;
}
}
ON UNITY :
I create a BridgeForUnity.cs file. Conent of it :
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
public class BridgeForAndroid : MonoBehaviour {
#if UNITY_ANDROID
//&& !UNITY_EDITOR
public static int ReturnInt () {
AndroidJavaClass ajc = new AndroidJavaClass("com.tutorial.pluginforunity.Bridge");
return ajc.CallStatic<int>("ReturnInt") ;
}
#endif
void Start () {
}
void Update () {
}
}
I edit DefaultTrackableEventHandler.cs that attached to image target.
private void Update() {
#if UNITY_ANDROID
GUI.Label(new Rect(10, 10, 100, 20), "Return = " + BridgeForAndroid.ReturnInt());
#endif
if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); }
}
I copy jar file under bin folder in eclipse project. I paste it under Assets/Plugins/Android.When I run this application, I see only black screen.
To see the return value from a plugin, move the code to OnGUI from Update.

Issue Exporting .app Using Processing and Leap Motion SDK

I have been trying to export a standalone application for Mac using the "Export Application" function in Processing. The simple application, which involves updating a float value on the screen that corresponds to the y-axis position of a hand detected by a Leap Motion, works perfectly well within Processing. However, once I export the application and try to run it, the app opens for a brief second and quickly closes. I have exported applications from Processing successfully before, but not one that uses the Leap SDK. I am using the LeapMotion library for Processing to access the Leap SDK: https://github.com/heuermh/leap-motion-processing. Here is my code:
import processing.core.*;
import com.leapmotion.leap.processing.*;
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.Listener;
public class Test extends PApplet {
Controller controller;
MyListener listener;
float position = 0.0f;
class MyListener extends Listener {
public void onFrame(Controller controller) {
if (!controller.frame().hands().isEmpty()) {
position = controller.frame().hands().leftmost().palmPosition().get(1);
}
}
}
public void setup() {
size(600,600);
controller = new Controller();
listener = new MyListener();
controller.addListener(listener);
}
public void draw() {
background(0);
textAlign(CENTER,CENTER);
textSize(50);
text(position, 300,300);
}
public static void main(String args[]) {
PApplet.main("Test");
}
}
When I export the application, the contents of the application are as follows:
Info.plist
Java
-core.jar
-gluegen-rt-natives-macosx-universal.jar
-gluegen-rt.jar
-jogl-all-natives-macosx-universal.jar
-jogl-all.jar
-LeapJava.jar
-LeapMotion.jar
-libLeap.dylib
-libLeapJava.dylib
-Test.jar
MacOS
-Test
Plugins
-jdk1.7.0_45.jdk
Resources
-en.lproj
-sketch.icns
PkgInfo
Any help would be greatly appreciated!
P.S. I've already tried bundling the program into a runnable JAR file.

Categories