EzDevInfo.com

pyjnius

Access Java classes from Python Welcome to Pyjnius — Pyjnius 1.0a1 documentation

Kivy/pyjnius: get android.app.Application object of my app

Testflight api needs pointer to android.app.Application object for API methods like this:

TestFlight.takeOff(this, "your-token-***-***-***")

how can I get it for my kivy App object?


Source: (StackOverflow)

Open a URL with default broswer?

I'm new developer in QPython (experienced with python), I want to open an url with user's default browser.

I tried AndroidBrowser().open("...") but, to my surprise, I got Segmentation Fault! So I said OK, let's try to open it manually as activity, then I tried to import jnius and got Segmentation Fault as well.

Any suggestion how to fix it or other ways to open the browser?


Source: (StackOverflow)

Advertisements

pyjnius "Class not found" when importing jar file

I'm trying to make pyjnius work with a jar file I built from java application, but I keep getting the "Class not found" error:

>>> import os
>>> os.environ['CLASSPATH'] = "~/workspace/myapp-Tools/Admin/Console/couchdb/myapp-web.jar"
>>> from jnius import autoclass
>>> bla = autoclass('com/myapp/webapp/server/helpers/licensee/CalculationHelper')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/home/sam/workspace/myapp-Tools/Admin/Console/couchdb/virtualenv/local/lib/python2.7/site-packages/jnius/reflect.py", line 150, in autoclass
   c = find_javaclass(clsname)
 File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:12815)
jnius.JavaException: Class not found 'com/myapp/webapp/server/helpers/licensee/CalculationHelper'
>>> 

of course I've checked:

jar tf myapp-web.jar

and com/myapp/webapp/server/helpers/licensee/CalculationHelper.class is in there

I've also tried setting the classpath this way:

import jnius_config
jnius_config.set_classpath('.', '~/workspace/myapp-Tools/Admin/Console/couchdb/')
#import jnius
from jnius import autoclass

But this gave me the same result. I'm working on a virtualenv btw. I've tried all approaches I could find online, but it is simply not working. I had to manually install pyjnius because using pip got me an old version of it. Any help would be greatly appreciated.


Edit: tried this with a jar not created by me and I see a different error

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import jnius_config
>>> jnius_config.add_classpath('/home/sam/workspace/someproject/*')
>>> jnius_config.expand_classpath()
'/home/sam/workspace/someproject/annotations.jar:/home/sam/workspace/someproject/junit-4.10.jar:/home/sam/workspace/someproject/    postgresql-8.1-408.jdbc3.jar'
>>> import jnius
>>> from jnius import autoclass
>>> test = autoclass('org/postgresql/geometric/PGcircle.class')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/sam/workspace/myapp-Tools/Admin/Console/couchdb/virtualenv/local/lib/python2.7/site-packages/jnius/reflect.py", line 150,     in autoclass
    c = find_javaclass(clsname)
  File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:12815)
jnius.JavaException: Class not found 'org/postgresql/geometric/PGcircle/class'
>>> test = autoclass('org/postgresql/geometric/PGcircle')
Exception in thread "main" java.lang.NoClassDefFoundError: org/postgresql/geometric/PGcircle/class
Caused by: java.lang.ClassNotFoundException: org.postgresql.geometric.PGcircle.class
  at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
  at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/sam/workspace/myapp-Tools/Admin/Console/couchdb/virtualenv/local/lib/python2.7/site-packages/jnius/reflect.py", line 156,     in autoclass
    for constructor in c.getConstructors():
  File "jnius_export_class.pxi", line 562, in jnius.JavaMethod.__call__ (jnius/jnius.c:19385)
  File "jnius_export_class.pxi", line 649, in jnius.JavaMethod.call_method (jnius/jnius.c:20409)
  File "jnius_utils.pxi", line 43, in jnius.check_exception (jnius/jnius.c:3533)
jnius.JavaException: JVM exception occured
>>> test = autoclass('org/postgresql/geometric/PGcircl')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/sam/workspace/myapp-Tools/Admin/Console/couchdb/virtualenv/local/lib/python2.7/site-packages/jnius/reflect.py", line 150,     in autoclass
    c = find_javaclass(clsname)
  File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:12815)
jnius.JavaException: Class not found 'org/postgresql/geometric/PGcircl'
>>> 

and here are the contents of jar tf on that jar:

sam@lambda ~/workspace$ jar tf ./someproject/postgresql-8.1-408.jdbc3.jar
META-INF/
META-INF/MANIFEST.MF
...
org/postgresql/geometric/PGbox.class
org/postgresql/geometric/PGcircle.class
org/postgresql/geometric/PGline.class
org/postgresql/geometric/PGlseg.class
org/postgresql/geometric/PGpath.class
org/postgresql/geometric/PGpoint.class
org/postgresql/geometric/PGpolygon.class
...
sam@lambda ~/workspace$ 

Again... any help will be greatly appreciated!


Source: (StackOverflow)

Android notifications to the notification bar in kivy

I want to create a notification on android in the notification bar. When i click on the notification i want to open my kivy application. The notification should be made from a background service.

How can i do that in kivy? I would prefer pyjnius and java but plyer is ok.


Source: (StackOverflow)

Installing Python sikuli package (problems installing pyjnius) Windows 7 Python 2.6

I am working on a Windows7 PC with Python 2.6. I want to import sikuli into Python. I have a problem installing pyjnius. Here are some of the errors I have been encountering:

C:\Users\x\Documents\Public\pyjnius\pyjnius-master>easy_install sikuli
Searching for sikuli
Reading https://pypi.python.org/simple/sikuli/
Best match: sikuli 0.1
Downloading https://pypi.python.org/packages/source/s/sikuli/sikuli-0.1.tar.gz#md5=c83294c6860858437572e6322ea03daf
Processing sikuli-0.1.tar.gz
Writing c:\users\x\appdata\local\temp\easy_install-dbost9\sikuli-0.1\setup.cfg
Running sikuli-0.1\setup.py -q bdist_egg --dist-dir c:\users\x\appdata\local\temp\easy_install-dbost9\sikuli-0.1\egg-dist-tm
p-c7taex
Searching for jnius>=1.1-dev
Reading https://pypi.python.org/simple/jnius/
No local packages or download links found for jnius>=1.1-dev
error: Could not find suitable distribution for Requirement.parse('jnius>=1.1-dev')

and then for pyjnius I get:

C:\Users\x\Documents\Public\pyjnius\pyjnius-master>easy_install pyjnius
Searching for pyjnius
Reading https://pypi.python.org/simple/pyjnius/
Best match: pyjnius 1.3.0
Downloading https://pypi.python.org/packages/source/p/pyjnius/pyjnius-1.3.0.tar.gz#md5=a65f17fdc95e08f5d3de3188359f4104
Processing pyjnius-1.3.0.tar.gz
Writing c:\users\x\appdata\local\temp\easy_install-or9uvd\pyjnius-1.3.0\setup.cfg
Running pyjnius-1.3.0\setup.py -q bdist_egg --dist-dir c:\users\x\appdata\local\temp\easy_install-or9uvd\pyjnius-1.3.0\egg-d
ist-tmp-kujh4w
warning: no files found matching '*COPYING'
error: Setup script exited with error: None

I downloaded pyjnius and run the setup:

C:\Users\bsprott\Documents\Public\pyjnius\pyjnius-master>python setup.py install
C:\Python26\lib\distutils\dist.py:266: UserWarning: Unknown distribution option: 'install_requires'
  warnings.warn(msg)
running install
running build
running build_py
running build_ext
skipping 'jnius\jnius.c' Cython extension (up-to-date)
building 'jnius' extension
error: None

Source: (StackOverflow)

Cannot create AdRequest instance by pyjnius

I'm trying to install AdMob on Kivy. I import AdRequest successfully but cannot create its instance.

AdRequest = autoclass("com.google.android.gms.ads.AdRequest")
print "AdRequest: ", AdRequest
print dir(AdRequest)

In the logcat, I can see the properties and methods of AdRequest by dir() :

AdRequest <class 'jnius.reflect.com.google.android.gms.ads.AdRequest'>
['DEVICE_ID_EMULATOR', 'ERROR_CODE_INTERNAL_ERROR', 'ERROR_CODE_INVALID_REQUEST',        
'ERROR_CODE_NETWORK_ERROR', 'ERROR_CODE_NO_FILL', 'GENDER_FEMALE', 'GENDER_MALE',   
'GENDER_UNKNOWN', 'MAX_CONTENT_URL_LENGTH', '__class__', '__cls_storage', 
'__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', 
'__init__', '__javaclass__', '__javaconstructor__', '__module__', '__new__',   
'__pyx_vtable__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'equals', 'getBirthday', 
'getClass', 'getContentUrl', 'getCustomEventExtrasBundle', 'getGender', 'getKeywords', 
'getLocation', 'getNetworkExtras', 'getNetworkExtrasBundle', 'hashCode', 
'isTestDevice', 'notify', 'notifyAll', 'toString', 'wait']

AttributeError: type object 'com.google.android.gms.ads.AdRequest' has no attribute    
'Builder'
Python for android ended.

I cannot find the Builder method https://developer.android.com/reference/com/google/android/gms/ads/AdRequest.html It's a class method to build AdRequest


Source: (StackOverflow)

kivy android : write public files

I'm coding an Android app using Kivy, and would like the app to write to the android filesystem, some PUBLIC directory/files.

Currently, if my app writes a file (using Python), the file CAN be read by the android local File Manager, but CANNOT be read by my computer mtp (these files don't appear in the InternalStorage). The adb shell CAN see the files though.

[EDIT] The solution could be to scan the files for mtp using MediaScannerConnection with Pyjnius, however as shown in my next answer, it didn't work for me. [/EDIT]

It seems to me that I'm looking for an equivalent of the Java getSharedPreferences described here : http://developer.android.com/guide/topics/security/permissions.html.

I thought that there is a similar option in the buildozer spec : the android.private_storage field described here : https://raw.githubusercontent.com/kivy/buildozer/master/buildozer/default.spec.

However, I'm not getting this to work... maybe I'm not using correctly the buildozer command : after settings in the spec "android.private_storage = False", I tried several commands like "buildozer android release --dir public my_dir" , or "buildozer android release --public my_dir", etc... , without success.


Source: (StackOverflow)

Installaton error when doing 'make tests' pyjnius in osx 10.9 : Class not found etc

I have these elements installed :
cython v0.20
python v2.7.5
osx 10.9.2
jre 8u45
jdk 8u45
nosetest 1.3.7

i’m trying to install pyjnius on my mac osx 10.9.2 I have python+kivy+cython+jdk+jre installed. Kivy is running properly, now i want to add pyjnius. It's compiled without error, but when doing 'make tests' i got a lot of error. Btw, inside kivy, i can import jnius only if i'm in the pyjnius installation folder. If i'm in other folder, i will got error msg "ImportError: No module named jnius". Below are the steps taken from the setup until make tests.

so my questions are :
1. how to fix the make tests error ?
2. In Kivy, How can i import the jnius /pyjnius without having to be in the pyjnius folder? Anyone got the solution ?

Here's the output of the error. The setup and make give no error, but make tests produce a lot of error.

$ sudo python setup.py install

14 warnings generated.
cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F. build/temp.macosx-10.9-intel-2.7/jnius/jnius.o -o build/lib.macosx-10.9-intel-2.7/jnius/jnius.so -framework JavaVM
running install_lib
copying build/lib.macosx-10.9-intel-2.7/jnius/jnius.so -> /Library/Python/2.7/site-packages/jnius
running install_egg_info
Removing /Library/Python/2.7/site-packages/jnius-1.1_dev-py2.7.egg-info
Writing /Library/Python/2.7/site-packages/jnius-1.1_dev-py2.7.egg-info

$ sudo make

14 warnings generated.
cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F. -g build/temp.macosx-10.9-intel-2.7/jnius/jnius.o -o /Users/andi/Documents/temp/pyjnius/jnius/jnius.so -framework JavaVM

$ sudo make tests
i got a lot of error :


JavaException: Class not found 'org/jnius/BasicsTest'

JavaException: JVM exception occurred: org/jnius/BasicsTest : Unsupported major.minor version 52.0

JavaException: Class not found 'org/jnius/BasicsTest'

JavaException: Class not found 'org/jnius/BasicsTest'

JavaException: Class not found 'org/jnius/BasicsTest'

JavaException: JVM exception occurred: org/jnius/NativeInvocationHandler

JavaException: Unable to find the class org/jnius/HelloWorld


Ran 47 tests in 0.349s

FAILED (errors=37) make: *** [tests] Error 1


Source: (StackOverflow)

Kivy start android intent with pre-filled contact fields

I want to start an android add contacts activity.But i also want to start the contact's intents insert action. What is wrong with my code here.

Simply i want to start a add contacts activity with pre filled data like phone and number already added.

import kivy

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from jnius import cast
from jnius import autoclass
PythonActivity = autoclass('org.renpy.android.PythonActivity')
Intent = autoclass('android.content.Intent')
Uri = autoclass('android.net.Uri')
Intents = autoclass("android.provider.ContactsContract$Intents")
ContactsContract = autoclass("android.provider.ContactsContract")
Contacts = autoclass("android.provider.ContactsContract$Contacts")

class Main(FloatLayout):
    def go_site(self):
        # create the intent
        '''
        intent = Intent()
        intent.setAction(Intent.ACTION_INSERT)
        intent.setData(Uri.parse("content://contacts/people/"))

        #############################################################

        intent = Intent()
        intent.setAction(Intent.ACTION_INSERT_OR_EDIT)
        intent.setType(Contacts.CONTENT_ITEM_TYPE)
        '''


        intent =  Intent()
        intent.setAction(Intents.Insert.ACTION)
        intent.setType(ContactsContract.RawContacts.CONTENT_TYPE)
        #intent.putExtra(Intents.Insert.EMAIL, "")



        # PythonActivity.mActivity is the instance of the current Activity
        # BUT, startActivity is a method from the Activity class, not from our PythonActivity.
        # We need to cast our class into an activity and use it

        currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
        currentActivity.startActivity(intent)



class MainApp(App):

    def on_pause(self):
        # Here you can save data if needed
        return True

    def on_resume(self):

        # Here you can check if any data needs replacing (usually nothing)
        pass
    def build(self):
        return Main()         
if __name__ == '__main__':
    MainApp().run()

Source: (StackOverflow)

adding properties to a pyjnius MetaJavaClass

pyjnius inspects Java and produces, for a Java class, a Python metaclass (of type MetaJavaClass).

I want to improve on those classes so that there are some @property methods that invoke some of the built-in methods.

I wrote:

def autoclass_with_decoration(name):
    base = orig_autoclass(name)
    for item in dir(base):
        if item.startswith('get'):
            itemb = lower_name(item)
            base[itemb] = property(lambda self: getattr(self, item)())
    return base

No such luck; base contains the metaclass, and you can't just add methods to the metaclass this way. (orig_autoclass is the function provided to look at a Java class and cook up a metaclass.) How do I approach this? Can I use multiple inheritance to add an ordinary 'mixin' class (invented on the fly here) to the mixture, or is there some more straightforward path?


Source: (StackOverflow)

How to select java version for pyjnius

I have Java 1.6.0_17 installed in /usr/local/bin. My Java program is compiled with 1.7.0_11.

pyjnius fails in a call X = autoclass('HelloWorld')

When HelloWorld.java is compiled with 1.6, everything works.

I cannot get pyjnius working with 1.7.

I've tried setting JAVA_HOME before importing jnius:

import os
os.environ['JAVA_HOME'] = '/usr/local/pkgs/jdk-1.7.0.11'
from jnius import autoclass
XX = autoclass('HelloWorld')

I've also set JAVA_HOME in .bash_profile and added /usr/local/pkgs/jdk-1.7.0.11/bin the first in my PATH.


Source: (StackOverflow)

creating apk using Kivy showing some error

When after I give the command:

buildozer android debug deploy run

I am getting the following error. Its showing syntax error ?

# Install distribute
# Run 'curl http://python-distribute.org/distribute_setup.py | venv/bin/python'
# Cwd /root/Bt/.buildozer
% Total     % Received  % Xferd   Average  Speed    Time    Time     Time  Current 
Dload Upload  Total Spent    Left Speed
100  1395  100  1395    0     0    276      0  0:00:05  0:00:05 --:--:--   276
File "<stdin>", line 1
<HTML><HEAD>
^
SyntaxError: invalid syntax
# Command failed: curl http://python-distribute.org/distribute_setup.py | venv/bin
/python

Source: (StackOverflow)

How To Bundle .jar Files with Pyinstaller

How do you get pyinstaller to bundle .jar files as archives for a python project that utilizes them?

For instance, to make an exe with (I am using pyjnius for handling the sikuli-standalone jar):

# test.py
import os
import sys

# set the classpath so java can find the code I want to work with
sikuli_jar = '/sikuli-api.standalone-1.0.3-Pre-1.jar'
jarpath = os.path.dirname(os.path.realpath(__file__)) + sikuli_jar
os.environ['CLASSPATH'] = jarpath

# now load a java class
from jnius import autoclass
API = autoclass('org.sikuli.api.API')

Pyisntaller creates the (one folder) exe with:

pyinstaller -d test.py

But the jar to the best of my knowledge is not bundled and is inaccessible to the exe unless you manually place it in the folder generated by Pyinstaller

According to the Pyinstaller manual:

"CArchive contains whatever you want to stuff into it. It's very much like a .zip file."

I then try editing the previously auto-generated test.spec file with:

jar = 'sikuli-api.standalone-1.0.3-Pre-1.jar'
jar_path = 'C:\\Python27\\Lib\\site-packages\\sikuli-0.1-py2.7.egg\\sikuli\\' + jar
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               [('sikulijar', jar_path, 'PKG')],
               strip=None,
               upx=True,
               name='test')

And I try building the exe based on this spec file with:

python C:\workspace\code\PyInstaller-2.1\PyInstaller\build.py --onefile test.spec

But nothing happens and no error returns. Can someone provide a simple step by step tutorial how this could be done? Many thanks!


Source: (StackOverflow)

Using DatePickerDialog with jnius

I recently tried to create an Android DatePickerDialog with jnius, but apparently did not manage to do it.

from jnius import autoclass
from android.runnable import run_on_ui_thread

context = autoclass("org.renpy.android.PythonActivity").mActivity
dialog = autoclass("android.app.DatePickerDialog")

@run_on_ui_thread
def run() :
    callback = dialog.OnDateSetListener()
    dialog(context, callback, 2000, 1, 1).show()

run()

How do I get it to work?


Source: (StackOverflow)

Kivy and android sharedpreferences

I am looking for a method to store settings persistently on android device, from Kivy framework.

I found Kivy documentation, overall informative, vague in this particular area. It mentions three methods (sorry, dont have enough reputation to provide clicable links, relative paths to kivy.org provided, I'd be glad if someone could fix those links):

  1. [Storage] ./docs/api-kivy.storage.html#module-kivy.storage
  2. [Settings] ./docs/api-kivy.uix.settings.html
  3. [Config] ./docs/api-kivy.config.html

In addition to those, I'm aware that I could store data in a file, via pickle or database, but I'd like to use specifically sharedpreferences, or at least any Android/Kivy specific persistent storage.

  1. However, I was unable to find any comparison, or explanation how they are different, and how they are used. Could anyone shed some light, had used them already?

  2. Actually, I'm 80% sure that neither of this method uses Android's shared preferences, thus I thought about using jnius (4), and to do that I've tried (methods 1,2/3?,4), based on simple hello world example:

    from kivy.app import App
    from kivy.uix.button import Button
    
    import jnius  
    from kivy.config import Config  
    from kivy.storage.dictstore import DictStore  
    
    class MyApp(App):
    
        def build(self):
    
            path = "DEFAULT"
            try:  
                path = Config.get('kivy', 'my_important_variable')  
                print "\t\t\t KIVY 1:", Config.get('kivy', 'my_important_variable')  
            except Exception as err:
                print ("KIVY, 1, error: {}".format(repr(err)))  
    
            try:
                store = DictStore("MY_SETTINGS")
                path = store.get("my_important_variable")
                print "\t\t\t KIVY 2:", path
            except KeyError as err:
                print ("KIVY, 2, error: {}".format(repr(err)))
    
            try:
                prefs_m = jnius.autoclass('android.preference.PreferenceManager')
                prefs = prefs_m.getSharedPreferences()
                path = prefs.getString("my_important_variable", None)
                print "\t\t\t KIVY 3:", path
            except jnius.jnius.JavaException as err:
                print ("KIVY, 3, error: {}".format(repr(err)))
    
            btn1 = Button(text=path)
            btn1.bind(on_press=app.callback) #
            return btn1
    
        def callback(self, instance):
            print('The button <%s> is being pressed, SAVING...' % instance.text)
    
            try:
                Config.set('kivy', 'my_important_variable', "my_value_1")
            except Exception as err:
                print ("KIVY, 4, error: {}".format(repr(err)))
    
            try:
                store = DictStore("MY_SETTINGS")
                store.put("MY_SETTINGS", my_important_variable="my_value_2")
            except Exception as err:
                print ("KIVY, 5, error: {}".format(repr(err)))
    
            try:
                prefs_c = jnius.autoclass('android.content.SharedPreferences')
                prefs_m = jnius.autoclass('android.preference.PreferenceManager')
                prefs = prefs_m.getSharedPreferences()
                prefs_e = prefs.Editor()
                prefs_e.putString("my_important_variable", "my_value_3")
                prefs_e.commit()
            except Exception as err:
                print ("KIVY, 6, error: {}".format(repr(err)))
    
            try:
                context = jnius.autoclass('android.content.Context')
                # do I actually get context or a class here?
                prefs = context.getPreferences(0).edit();
                prefs.putString("my_important_variable", "my_value_4")
                prefs.commit()
            except Exception as err:
                print ("KIVY, 7, error: {}".format(repr(err)))
    
    if __name__ == '__main__':
        app = MyApp()
        app.run()
    

and here are logcat's results

... each time app is launched 
I/python  ( 5973): KIVY, 1, error: No option 'my_important_variable' in section: 'kivy'
I/python  ( 5973): KIVY, 2, error: KeyError('my_important_variable',)
I/python  ( 5973): KIVY, 3, error: JavaException('Unable to find a None method!',)

... button pressed
I/python  ( 5973): The button <DEFAULT> is being pressed, SAVING...
I/python  ( 5973): KIVY, 6, error: JavaException('Unable to find a None method!',)
I/python  ( 5973): KIVY, 7, error: AttributeError("type object 'android.content.Context' has no attribute 'getPreferences'",)

Notice, that 4, 5 "error msg's" didn't get called, so in theory they should have worked, but second launch I get same errors. I've run out of ideas how to crack it.


Source: (StackOverflow)