Python for Android
Your Android emulator now is ready to run your custom Python script, so let's create one. Before you do though, note that the published SL4A API is a subset of the full Android API, so certain features either are not available, in the process of being made available or fully supported (see Resources for a link to the current list). Don't let this put you off. What's there is more than enough to produce usable Android apps in Python.
To get a feel for Python running on SL4A, let's port an existing script to the phone. The script in question is based on some code from Chapter 2 of O'Reilly Media's Head First Programming, which I cowrote with David Griffiths in 2009. This simple script connects to the Web site of a fictitious company called Beans'R'Us to grab the company's home page and extract the current price of coffee beans from the page's HTML. The code is straightforward, grabbing the HTML page from the server, searching for the pricing data, extracting it from the HTML page and then displaying it on screen:
from urllib import urlencode
from urllib2 import urlopen
pg = urlopen("http://www.beans-r-us.biz/prices.html")
text = pg.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
print "The current price of coffee is:", price
This is Python 2 code, which is a deliberate choice, as the Python that comes with SL4A is the 2.6.2 release. To take this program for a spin, either load it into Python's IDLE tool or execute it from the command line:
$ python LJapp-cmd.py The current price of coffee is: 5.52
As you can see, this small script displays the currently published price of coffee beans.
Turning this script into an Android app is just a matter of deciding on the Android UI elements you want to use, as the core functionality does not need to change. The Python on SL4A is fully functional, so the facilities you are used to with standard Python also are available on your smartphone.
To make this script more Android-like, let's display a friendly message on startup as well as one on exit. The makeToast() API call provides this functionality.
The dialogCreateSpinnerProgress() API call lets you display an Android spinner dialog, assuming you then remember to call the dialogShow() API call to make it visible. Let's display a spinner prior to requesting the Web page from the Beans'R'Us server, then dismiss the spinner dialog with the dialogDismiss() API call, once we have the data processed. And, let's vibrate the phone at this point too, just for the fun of it.
To conclude the script, use the dialogCreateAlert(), dialogSetItems() and dialogSetPositiveButtonText() API calls to display the price of beans within an Android dialog. To exit, simply tap the OK button.
Here's the Python code from earlier with the calls to the SL4A API added in:
import android
from urllib import urlencode
from urllib2 import urlopen
app = android.Android()
app.makeToast("Hello from LJapp")
appTitle = "LJapp"
appMsg = "Checking the price of coffee..."
app.dialogCreateSpinnerProgress(appTitle, appMsg)
app.dialogShow()
pg = urlopen("http://www.beans-r-us.biz/prices.html")
text = pg.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
app.dialogDismiss()
app.vibrate()
appMsg = "The current price of coffee beans:"
app.dialogCreateAlert(appMsg)
app.dialogSetItems([price])
app.dialogSetPositiveButtonText('OK')
app.dialogShow()
resp = app.dialogGetResponse().result
app.makeToast("Bye!")
Other than the addition of the Android UI code, no other changes are required to the code from earlier, other than removing the earlier script's call to print (which is no longer required).
To transfer your Python script to the emulator for testing, copy your code file into your Android directory, then use the adb utility within the tools directory to push your file to the SL4A scripts directory on the emulator:
$ tools/adb push LJapp.py /sdcard/sl4a/scripts 6 KB/s (748 bytes in 0.116s)
With the file transferred, check the list of scripts within SL4A and notice the addition of LJapp.py near the top of the list.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
- RSS Feeds
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- Dynamic DNS—an Object Lesson in Problem Solving
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Download the Free Red Hat White Paper "Using an Open Source Framework to Catch the Bad Guy"
- Tech Tip: Really Simple HTTP Server with Python
- Roll your own dynamic dns
1 hour 38 min ago - Please correct the URL for Salt Stack's web site
4 hours 50 min ago - Android is Linux -- why no better inter-operation
7 hours 5 min ago - Connecting Android device to desktop Linux via USB
7 hours 34 min ago - Find new cell phone and tablet pc
8 hours 32 min ago - Epistle
10 hours 57 sec ago - Automatically updating Guest Additions
11 hours 9 min ago - I like your topic on android
11 hours 56 min ago - This is the easiest tutorial
18 hours 31 min ago - Ahh, the Koolaid.
1 day 10 min ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
Looks like Paul's been time
Looks like Paul's been time travelling again. i like the article though. It covers exactly what i have spent the past hour searching for.
Well at least you got the
Well at least you got the info a week early! ;) This is a very comprehensive article about app programming. While I don't have the technical expertise to craft the SL4a technique without conquering a steep learning curve, it does open my eyes to a new way to do things. This is particularly helpful since I've been learning how mobile solutions are being tapped into by users. As one can imagine, a company that does mobile marketing(example: http://www.exacttarget.com) is going to have different needs then a company that specializes in manufacturing, or a user who wants to simplify his/her "mobile" life. Right now I fall into the latter category, but that doesn't mean I won't have a vastly different agenda in regards to app programming in the future.
Time will tell if Android development via Python is something I will tap into, but it's nice to have the programming app horizon broadened. Options are good!
Amazing!
this essay is posted on "Apr 30, 2011 By Paul Barry in Mobile". And today is Apr 23.
I noticed that to. I wonder
I noticed that to. I wonder what planet he was on when he published the article.