Android App with the Perl5 to Java compiler
We've had another hackathon at work.
Yati, Bas, Luca and I hacked on the Perlito Perl5-to-Java compiler and also a bit of Perl5-to-JavaScript.
The changes are in GitHub and will be published in the next CPAN release.
The latest cool addition is an Android App example:
Import to Perl space all Java libraries we will need:
use strict;
use warnings;
package header { java_path => 'org.perlito.perlitosample' };
package Android::Activity { import => 'android.support.v7.app.AppCompatActivity' };
package Android::Bundle { import => 'android.os.Bundle' };
package String {};
package Button { import => 'android.widget.Button' };
package TextView { import => 'android.widget.TextView' };
package EditText { import => 'android.widget.EditText' };
package View { import => 'android.view.View' };
Setup a class extending "Android::Activity" - this is our App entry point, and it involves a bit of Android-side magic using use Java::inline:
package MainActivity {
extends => 'Android::Activity',
decl => ['public'],
'Java::inline' => '
static {
Main.init();
}
public void onCreate(Bundle saved) {
super.onCreate(saved);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button_ok);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText txt = (EditText) findViewById(R.id.value);
String x = txt.getText().toString();
TextView tv = (TextView) findViewById(R.id.text);
String val = doit(x);
tv.setText(val);
}
});
}
',
methods => [
doit => {
decl => ['public'],
return => 'String',
args => ['String'],
code => 'main::doit',
}
],
}
The header declares that the "doit()" method is implemented in Perl, in the subroutine "main::doit".
Now we define the subroutine:
sub doit {
my $this = shift;
my $x = shift;
if ($x eq 'die') { die "Death to you"; }
if (0+$x eq $x) {
return "The result (calculated in Perl) is ". (2 * $x);
}
else {
return "The result (calculated in Perl) is ". ($x x 2);
}
}
We called this file "mainactivity.pl" [Perl5 source code] and it compiles to "MainActivity.java" [Java source code].
We then compiled this with Android Studio using an Android project file [project file] and tested on a real phone!
Leave a comment