Page 312 -
P. 312
android query
Android Code Magnets Solution
Here is the code to a program that queries your web server for the list of names as a JSON array
and then displays the list on the smartphone. The only trouble is, the second half of the program
is a bunch of mixed-up code magnets at the bottom of the screen. Your job was to rearrange the
magnets to complete the program.
import android
import json
import time
from urllib import urlencode
from urllib2 import urlopen
hello_msg = "Welcome to Coach Kelly's Timing App"
list_title = 'Here is your list of athletes:'
quit_msg = "Quitting Coach Kelly’s App."
web_server = 'http://192.168.1.33:8080'
get_names_cgi = '/cgi-bin/generate_names.py'
def send_to_server(url, post_data=None):
if post_data:
page = urlopen(url, urlencode(post_data))
Create an Android
else:
app object. page = urlopen(url) This is a little
return(page.read().decode("utf8")) function for Send the web request
displaying short to your server, then
app = android.Android() messages on the turn the JSON response
def status_update(msg, how_long=2): phone. into a sorted list.
app.makeToast(msg)
time.sleep(how_long)
Say status_update(hello_msg)
“hello”.
athlete_names = sorted(json.loads(send_to_server(web_server + get_names_cgi)))
app.dialogCreateAlert(list_title)
Create a two-buttoned
app.dialogSetSingleChoiceItems(athlete_names) dialog from the list of
app.dialogSetPositiveButtonText('Select') athlete names.
app.dialogSetNegativeButtonText('Quit')
app.dialogShow()
Wait for the user to tap a button,
resp = app.dialogGetResponse().result then assign the result to “resp”.
status_update(quit_msg) Say “bye bye.”
276 Chapter 8