How to properly access an Android java class using Pyjnius

1.7k Views Asked by At

I am having a hard time trying to use Pyjnius to access a Android Java class "ContactsContract.Intents.Insert".

I have been following this example provided here:

Pyjnius: http://kivy.org/planet/2012/08/pyjnius-accessing-java-classes-from-python/

Java class to access: MediaRecorder

But really what I want to access using Pyjnius is the "ContactsContract.Intents.Insert" in Android and get working code to add a new contact to my Android phone.

Android class: https://developer.android.com/reference/android/provider/ContactsContract.Intents.Insert.html

This is what I have so far but I am confused on the arraylist:

from jnius import autoclass

Data = autoclass("ArrayList")
data = Data()

MyContacts = autoclass("ContactsContract.Intents.Insert")

mycontacts = MyContacts()
data.put(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE)
data.put(Organization.COMPANY, "Android")
data.add(mycontacts)
1

There are 1 best solutions below

2
On BEST ANSWER

Intents.Insert is a static class which contains static string constants. I had the same problem when I wanted to add contacts from the app I was building. I ended up writing a class containing a static method which would add a contact in java and adding it into my buildozer.spec file for compilation. I know its not exactly what you are after but it gives you a fair idea when running into these kinds of issues there is a work around. It's actually fairly easy to mix Python code with Java. Kivy is great for prototyping Android apps but like pyjnius the documentation is very limited.

Java code

import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Intents;
import android.app.Activity;
import android.content.Intent;

public class Contact{

    public static void addContact(Activity pyActivity, String name, String phone, String email){
        Intent i = new Intent(Intent.ACTION_INSERT);
        i.setType(Contacts.CONTENT_TYPE);
        i.putExtra(Intents.Insert.NAME, name);
        i.putExtra(Intents.Insert.PHONE, phone);
        i.putExtra(Intents.Insert.EMAIL, email);
        pyActivity.startActivity(i);
    }

}

python script

PythonActivity = autoclass("org.kivy.android.PythonActivity")
Contact = autoclass("Contact")
Contact.addContact(PythonActivity.mActivity, "Steve", "666", "[email protected]")

and then finally add the Conact.java to the buildozer.spec file

android.add_src = Contact.java