Java – Use Chaquopy to write your own python code in Android

Use Chaquopy to write your own python code in Android… here is a solution to the problem.

Use Chaquopy to write your own python code in Android

I tried using prototype python code in Android applications, and I found Chaquopy as a possible library.

The documentation is a bit sparse, so I wanted to clarify: can I use Chaquopy to call my own python methods (including passing variables) in Android Java code?

If yes, can you give an example to see how this works?
I would be very grateful to see an example of passing complex objects, not just strings, in particular.

Thanks!

Solution

Yes, you can call your own Python code just like library code. Simply place your Python file in the appropriate directory, such as the documentation describes

I’m not sure what kind of “complex object” you’re referring to, but here are some examples of passing various types of objects to the Python function f in the mod.py file:

Python py = Python.getInstance();
PyObject mod = py.getModule("mod");

 If the function knows what methods and attributes to use, Java objects
 can be passed directly.
mod.callAttr("f", someJavaObject);

 If the function expects an iterable, Java arrays can be passed directly.
mod.callAttr("f", new String[] {"one", "two", "three"});

 If the function expects a dict, it can be created as follows.
PyObject builtins = py.getBuiltins();
PyObject d = builtins.callAttr("dict");
d.callAttr("__setitem__", 1, "a");
d.callAttr("__setitem__", 2, "b");
mod.callAttr("f", d);

Related Problems and Solutions