Pizza Party with Fusion Tables for App Inventor 2
In this tutorial, you will create an app that allows people to enter food orders for a pizza party. Orders are stored in a Fusion Table, providing one easy-to-access place for the data. By reading from the table, the app can easily display the orders that have been entered.
A Fusion Table is a Google service to support the gathering, managing, sharing, and visualizing of data. Data is stored in Google's cloud. All of the data are stored in a public table (or tables) that can be accessed via Google Drive, and allows different users to add information to the tables.
For example, coupled with a location sensor, an App Inventor app could post periodic updates of each user's location to a public fusion table. Users could post notes to mark noteworthy locations, such as a team of botanists could use a Fusion Table app to create an annotated catalog of the trees or plants within a certain geographical area. See the Google Documentation on Fusion Tables for more information.
This tutorial introduces:
- Using the FusionTables component
- Using a WebViewer component
This tutorial assumes you are familiar with the basics of App Inventor, including using the Component Designer to build a user interface, and using the Blocks Editor to specify the app's behavior. If you are not familiar with the basics, try stepping through some of the basic tutorials before continuing.
IF YOU DOWNLOAD THE SOURCE CODE you will need to supply your own service account keyfile and email, and your own Table URL and Table ID in the global variables in the blocks editor. This source code will not work without these additions.
Setting up a Service Account
Before App Inventor can access any fusion tables you create, you need a special "Service Account Email Address." This special account and its keyfile allows your users to edit your Fusion Tables without logging in- your service account handles all the access. Instructions are here:
How to create a Service Account for Fusion Tables
Creating your own Fusion Table
Creating your own Fusion Tables is as easy as creating a Google document.
- On the web, login to your Gmail account.
- Go to Google Drive and click the red New button and navigate to More. Select Google Fusion Tables in the list of choices. (If you do not see Google Fusion Tables in the menu, click +Connect more apps. Scroll down until you find Fusion Tables and hover over it. Click the + Connect button, then click OK. Now, when you click the New button, Fusion Tables should appear. If not, then you may need to contact your school's network administrator. See Troubleshooting section at the bottom of this page.)
- You will be given a few different options for the new table. Select Create empty table.
- You will see that the new table automatically comes with four columns. Change the column names for your pizza party app by going to Edit > Change Columns.You'll rename the four default columns to Date (type=Date), Name (type=Text), Pizza (type=Text), Drink (type=Text). Click save and then add a fifth column by going to the Edit > Add Column. Name this fifth column Comment (type=Text).
- Leave this window open so that you can come back and get the URL, which you'll need when you set up the properties of the WebViewer component in your app.
Share the Fusion Table with the Service Account
The service account acts as a virtual user who can read and edit the table. This prevents your user from having to log in.
- In the Fusion Table, click "Share"
- Find "Invite people"
-
Enter your service account email, from the Developer Console (e.g.
)
- Ensure "Can Edit" is selected.
- Unlick "notify people" (the service account isn't a real person so it doesn't care about the notification)
- Click "OK", and when it says "skip sending notification?" click "OK".
Building the App
Connect to the App Inventor web site and start a new project. Name the new project PizzaParty, set the screen's orientation to Portrait and uncheck the Screen's scrollable property. You may also wish to set the Screen's Title property to something other than 'Screen 1'.
The User Interface
In addition to the FusiontablesControl component, the Pizza Party app makes use of several other types of components. It is assumed that you have learned how to use these in previous tutorials. Use the designer window to create the interface for the Pizza Party. When completed, the designer should look like this:
The components are:
Component Type | Palette Group | What you'll name it | Purpose of Component | Settings of Component |
Label | User Interface | LabelName | Shows the text "Your Name:" | |
TextBox | User Interface | TextBoxUserName | Gets input from user | Set the width property to Fill Parent |
HorizontalArrangement | Layout | HorizontalArrangement1 | Contains Name Label and Textbox | |
ListPicker | User Interface | ListPickerPizza | Accesses the list of available pizza types. |
Set the Width property to Fill Parent Set the Text property to "What type of pizza?" Set the ElementsFromString to "Cheese, Pepperoni, Anchovies, Hawaiian" |
ListPicker | User Interface | ListPickerDrink | Accesses the list of available drinks. |
Set the Width property to Fill Parent Set the Text property to "What type of drink?" Set the ElementsFromString to "Coke, Diet Coke, Sprite, Ginger Ale" |
Label | User Interface | LabelComment | Shows the text "Comments:" | |
TextBox | User Interface | TextBoxComments | Takes user input | Set the width property to Fill Parent |
HorizontalArrangement | Layout | HorizontalArrangement2 | Contains Comments Label and Textbox | |
Button | User Interface | ButtonSubmit | Adds new data to the public fusion table |
Set the Text to "Submit" Set the width property to Fill Parent |
WebViewer | User Interface | WebViewer1 | Displays Fusion Table |
Set width property to Fill Parent Set height property to Fill Parent |
FusiontablesControl | Storage | FusiontablesControl1 | Manages interactions with the app's Fusion Table | |
Clock | User Interface | Clock1 | Used to provide a timestamp each time an order is placed. | |
Notifier | User Interface | Notifier1 | Notifies the user of any errors |
Determining your Fusion Table URL and Table ID
In the blocks editor, you will set the WebViewer component's HomeURL property to point to the URL of your table. To find your Fusion Table's URL:
- In your browser, navigate to the Fusion Table you just created.
- Go to the menu and select Tools > Publish.
- You'll see a notice saying: "This table is private and will not be visible". Click the blue link that says "Change Visibility".
- In the list of "Who Has Access", click the blue "Change..." link next to "Private - Only people listed below..."
- Choose"Public on the Web" or "Anyone with the link". Either of these settings will work for this tutorial. In the future, you should decide this setting based on the sensitivity of your data.
- Click the green Save button, then the blue Done button.
- Back on the Fusion Table page, go to the menu bar and select Tools > Publish. Select the URL from the top text box (labeled "Send in an email or IM"), copy the URL and return to App Inventor. You will paste the URL into the definition block for the TABLE_URL (see below).
- You can find the Table ID by browsing to your table, then selecting File > About this table in the menu.
Upload your .p12 key file
In the designer, upload the the key file you downloaded from the Developer Console. Upload it under Media, the same way you would upload an image file.
Click on the FusiontablesControl1 component, and find the KeyFile property. Click where it says "none" under KeyFile, and select the .p12 file you previously uploaded.
Blocks Editor
Open the Blocks Editor so you can program the app's behavior. First, you will describe the app's variables. Variables whose names are ALL_CAPS are constants -- that is, variables whose values do not change while the program is running. It is good to get into the habit of using this naming convention. Define the following variables and give them the initial values shown in the table.
Block type | Drawer | Purpose |
initialize global TABLE_URL | Variables | Initialize this global variable to the "published" URL of your fusion table. See instructions above. |
initialize global TABLE_ID | Variables | Initialize this global variable to your table ID (e.g. a long string of characters unique to your fusion table). See instructions above. |
initialize global SERVICE_ACCOUNT_EMAIL | Variables | Initialize this global variable to the own service account ID (email address) for you service account. To find this, go to your developer console and select IAM & Admin from the three horizontal lines menu at the upper left. You should see your service account listed (there might be only one) together with its email address (service account id). |
initialize global UserName | Variables | Records the name of the user. (Starts off as an empty text string.) |
initialize global pizza | Variables | Stores the pizza choice input by the user. (Starts off as an empty text string.) |
initialize global drink | Variables | Stores the drink choice input by the user. (Starts off as an empty text string.) |
initialize global comment | Variables | Stores the comment input by the user. (Starts off as an empty text string.) |
Initializing the App
It is important to perform some initialization steps whenever the app is started. These are done in the Screen1.Initialize block. For this app we need to set the initial values for the FusionTable component's service account property (set to global SERVICE_ACCOUNT_EMAIL) and the WebViewer component's HomeURL property (set to global TABLE_URL).
Set up the resetForm procedure as shown below. After recording an entry, this procedure resets the interface back to the original state.
List Picker Blocks
In the designer, you set the choices for the pizza and drink types by filling in the "Selection" property with comma separated lists. These pre-programmed choices will be displayed on the user interface so the user can select their food and drink. Their selections are stored in the pizza and drink variables.
Inserting Data into the Fusion Table
The FusiontablesControl component is used to send the data to the Fusion Table. This action will create a new row in the Fusion Table, setting the values of the various columns involved. App Inventor makes this easy to do, but you have to be careful that the insert query is formatted correctly.
First there is a list of column names, followed by a list of values. The order of the column names and value names must be in the same order so that they match up. An example of what this might look like is shown below.
First, setup a new Procedure With Result that takes a string as an argument and returns that same string surrounded by single quotes. The procedure quotify is used in the InsertDataInTable procedure to place quotes around all of the values in the query. It also takes care of "escaping" any single quotes or apostrophes that are input by the user. You can send single apostrophes as part of a value in the query, so the "replace all" block adds an extra single quote. Two single quotes in a row are interpreted as one single quote. The figures below show how to make the procedure. Notice that you have to tell the procedure block to add a parameter. You do this with the blue icon that pops up a small window where you specify how many items you need to act as parameters. In this case, you just need one. App Inventor will automatically name the parameter "x" but you can rename it to "str" by clicking on the x and typing directly into the block. Similarly, you can rename the procedure from "procedure" to "quotify" by typing directly into the block.
Use the Fusion Table component's InsertRow block. To construct the list of values, we use App Inventor's join text block.
For this app, the column names must match the column names of the table we created earlier (with columns Date, Name, Pizza, Drink, Comment). Their respective values are taken from the procedure's global variables. Note: If you did not use these exact words for your table's columns, then be sure to use your table's column names when you build your query.
Submitting Data
Once the user has entered their name, food choices, and comments, they will click the Submit button. The app tests to make sure that the name, pizza, and drink fields have values in them, and prompts the user to try again if any of the required answers are missing. Notice that the compare texts block is used (find it under Built-in palette, Text drawer). This block compares two strings of text to see if they are equal. If all required information is present, it calls the procedure InsertDataInTable (see below). The blocks for the ButtonSubmit.Click are shown here:
A note about Invalid Query/Parse Error Messages: There are a few different reasons your app may get a response from Fusion Tables that gives an Error related to Parsing or Invalid Query. This could be because you are missing spaces in the query string or have not handled single quotes (see the quotify procedure above). It may also be that you have used one of the Fusion Table RESERVED WORDS as a column name (More info about reserved words).
Handling the Response from the Fusion Tables Service
The FusiontablesControl.GotResult event will be fired when the app receives a response from Google's Fusion Tables Service. For an insert query, the service will return the rowID of the new row that was inserted or an error message if something went wrong. In this simple example, we use the "contains" block (find it under Built-in palette, Text drawer) to check whether the result string has the rowID in it. If so, then we know that the rowID was received, and we then invoke the WebViewer.GoHome procedure, which reloads the "HomeURL" as specified in the WebViewer's properties. Note that this set of blocks also calls the resetForm procedure. After recording an entry, it resets the interface back to the original state.
You're done! Package the app by going to Package for Phone on the Designer. You can now test the app for the purposes of the pizza party. Once you understand this tutorial, you'll be ready to make new Fusion Tables and modify the app to collect different types data from users.
Challenges
This app has the Fusion Table hard-coded into the blocks. Find a way to let users specify their own Fusion Table ID so that they can host their own Pizza Party.
Variations
Now that you have a simple app that uses Fusion Tables and a WebViewer, you might want to build some other apps with Fusion Tables. For example:
- Include a LocationSensor so that the user's location can be added to the Fusion Table to create a map with notes.
- Make the WebViewer display something other than the table of stored values, like a map or a chart.
Troubleshooting
If you are using a Google Apps for Education account, and you are not able to create a new Fusion Table (in the "Create" menu of Google Drive you won't even see an option for Fusion Tables), you will need to ask your system administrator to turn this option on for you. Or, you can switch to a standard Gmail account. Fusion Tables are not automatically turned on for Google Apps for Education Accounts, your system administrator must make Fusion Tables available to the accounts in your domain.
If you are receiving errors when trying to submit to the Fusion Table, especially if the error mentions Authentication, be sure that you have put the correct service account email address in set, either as a variable that is set during Screen1.Initialize, or in the property field on the FusionTables component in the Design Window. Also make sure the key file (.p12) is uploaded as media, and the KeyFile property in the Design Window is set to that file.
If you are getting an error that says "403 Forbidden" with no other detail, make sure the fusion table is shared with your service account email. The service account email comes from your developer console, and looks like
. It is not the same as your usual google account email.
To familiarize yourself with Fusion Tables, have a look around the Fusion Tables Web Site. Check out the example gallery to see what kinds of things are possible. Work through this Fusion Table tutorial, which shows how import some data, create a Fusion Table, and view the data on a map with your browser. You'll need to log in with your Google account.
STILL HAVING TROUBLE? Check out the FusionTables Help put together by Taifun Bär: http://puravidaapps.com/fusionerror.php
Done with PizzaParty? Return to the other tutorials.
Download Source Code
If you'd like to work with this sample in App Inventor, download the source code to your computer, then open App Inventor, click Projects, choose Import project (.aia) from my computer..., and select the source code you just downloaded.
Tutorial Version:
Tutorial Difficulty:
- Advanced
Tutorial Type:
- Clock Timer
- Data Storage