Click here to Skip to main content
15,122,406 members
Articles / Mobile Apps / Android
Article
Posted 28 Feb 2012

Tagged as

Stats

31.1K views
2 bookmarked

Calling Python from Java for Android using CLE and SL4A

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
28 Feb 2012CPOL1 min read
Calling Python from Java for Android using CLE and SL4A

Java is major language to develop applications on Android platform. But, in some cases, programmers want to call Python code from Java to perform some functions.

By now, there is no direct method to write programs with Python.

SL4A is an open project, which supports script languages including python, lua, etc. But calling python from Java has not been supported directly. Programmers have to use JNI method, and native code to write interface for python. This is more difficult, you have to manage relationship between Java objects and python objects, kinds of references, interface parameters conversion, and callback functions from python to Java.

CLE(Common Language Extension) is a middleware which presents functions to aid multi-language calls between scripts, including Java and python. Using CLE, the above problems can be solved easily. Architecture of CLE is as follows:

Java calls Python functions:

Python Function

C#
Obj=Service._New("TestClass");
def Obj_PythonAdd(self,x,y) :
    return x+y;
Obj.PythonAdd = Obj_PythonAdd;

Java Code

C#
StarObjectClass a = Service._GetObject("TestClass")._New();
a._Call("PythonAdd",12,34));
Callback of python to java:

Java Callback Function

C#
StarObjectClass a = Service._GetObject("TestClass")._New()._Assign(new StarObjectClass(){
   public int JavaAdd(StarObjectClass self,int x,int y){
       return x+y;
   }
});

Python Code

C#
Obj.JavaAdd(x,y)

Java gets object’s attributes defined in python.

Python: Obj.PythonValue = 200;

Java: a._Get("PythonValue")
Python gets object’s attributes defined in Java.

Java: a._Set("JavaValue",100);
Python: self.JavaValue

Method1 Source Code (Integrate CLE With Your Project)

  1. Install SL4A from http://code.google.com/p/android-scripting/downloads/list
  2. Download devfiles from http://code.google.com/p/cle-for-android, and then Open Eclipse
  3. Create project for Android.
  4. Add CLE libraries to project as follows:

  5. Python code:
    SrvGroup = libstarpy._GetSrvGroup()
    
    Service = SrvGroup._GetService("","")
    
    #Create objects
    Obj=Service._New("TestClass");
    
    #Define functions
    def Obj_PythonAdd(self,x,y) :
        print("Call python function...");
        return x+y;
    Obj.PythonAdd = Obj_PythonAdd;
    
    #Call java functions
    def Obj_PythonPrint(self,x,y) :
        print( "Value defined in java is ",self.JavaValue );
        print( "Function result from java ",self.JavaAdd(x,y) );
    Obj.PythonPrint = Obj_PythonPrint;
    
    #define Attributes
    Obj.PythonValue = 200;
  6. Java code:
    Java
    package com.cle.pythonfromjava;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.content.res.AssetManager;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    import com.srplab.www.starcore.*;
    
    public class PytonfromjavaActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            //--init CLE
            StarCoreFactoryPath.InitDefault(Runtime.getRuntime(),
    			"/data/data/com.cle.pythonfromjava");
            
    StarCoreFactory starcore= StarCoreFactory.GetFactory();
    StarServiceClass Service=starcore._InitSimple("test","123",0,0);
    Service._CheckPassword(false);
    
    AssetManager assetManager = getAssets();     
    
            try{
                String pythonbuf;
                
                   InputStream dataSource = assetManager.open("code.py");
                   int size=dataSource.available();
                   byte[] buffer=new byte[size]; 
                   dataSource.read(buffer); 
                   dataSource.close();        
                   pythonbuf=new String(buffer);
                   
                Service._RunScript("python",pythonbuf,"cmd","");
            }
            catch(IOException e ){
            }   
            
    StarObjectClass a = Service._GetObject("TestClass")._New()._Assign(new StarObjectClass(){
       public int JavaAdd(StarObjectClass self,int x,int y){
           System.out.println("Call java function...");
           return x+y;
       }
    });
            a._Set("JavaValue",100);
            System.out.println(a._Get("PythonValue")); 
            System.out.println(a._Call("PythonAdd",12,34));           
            a._Call("PythonPrint",56,78);
        }
    
    }

Method2 Source Code (Install cle from http://code.google.com/p/cle-for-android independently):

  1. Install SL4A from http://code.google.com/p/android-scripting/downloads/list
  2. Install CLE from http://code.google.com/p/cle-for-android/downloads/list
  3. Download devfiles from http://code.google.com/p/cle-for-android, and then Open Eclipse
  4. Create project for Android
  5. Python code:
    Same as method 1
  6. Java code:
    Delete the following code line. Others are the same as method1.
    Java
    StarCoreFactoryPath.InitDefault(Runtime.getRuntime(),
    			"/data/data/com.cle.pythonfromjava");

Examples may be downloaded from http://www.srplab.com/android/calling_python_from_java.rar.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

li9705
China China
No Biography provided

Comments and Discussions

 
QuestionApp Crashes Pin
Member 1247786822-Apr-16 0:55
MemberMember 1247786822-Apr-16 0:55 
I followed the complete flow as mentioned in above post, but while running the code , it shows and unknown error:
C#
Fatal signal 11 (SIGSEGV), code 2, fault addr 0xbe4b9bc4 in tid 29300 (w.pythonexample)

Please help Frown | :(

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.