app lesson guide
DESCRIPTION
APPTRANSCRIPT
Page 1
Application Learn about… Expertise 1. Talk to Me Text to speech First Apps 2. Ball Bounce Ball object. Animation. First Apps 3. Digital Doodle Canvas drawing. First Apps 4. “I have a
dream” Display photos. Play sounds. Button controls Basic
5. Hello Zombie Utilize many different common controls on one app. Basic 6. Paint Pot Draw on the canvas. Change colors. Basic 7. Android Mash Timer events, randomness, and be introduced to animation Basic 8. Magic 8 ball Ask the 8 ball a question. Basic 9. Weather App Show weather data for any city in the US. Shows how to connect
to weather underground. Basic
10. Camera App Utilize the camera in your apps. Basic 11. President’s
Quiz Store data in lists. User controls. Intermediate
12. No Texting While Driving
Open this text answering machine app and it will auto-‐respond to incoming texts.
Intermediate
13. Get the Gold Intermediate 14. Pong Build the classic game Pong and learn how to animate image
sprites, deal with collisions, keep score, and define procedures to make your code better.
Intermediate
15. Space Invaders Use clock components and Timers, using Animation components such as Image Sprites and the Canvas, setting visibility, and detecting collisions
Intermediate
16. Mini Golf Multiple objects on the screen. Collisions Intermediate 17. Stock Market
Quote The Stock Market app displays the current price of any stock you enter. You'll learn how to web-‐enable your app and communicate with Web APIs, in this case Yahoo Finance
Intermediate
18. Logo Challenge Program the Android Logo to create shapes and learn about algorithms, procedures, and parameters
Intermediate
19. Voice Recorder Beat Box App. Use the Android SoundRecorder, Player, take another look at using list, logic and incremental programming.
Intermediate
20. Contact Database
Using Lists, List Pickers, TinyDB, TinyWebDB, Fusion Tables, and Texting.
Advanced
21. Chat App Send and store messages in an online database using TinyWebDB Advanced 22. Pizza Party Fusion Tables to share data among several users of a single app. Advanced 23. Advanced
Weather App Display the weather forecast for any US city. Forecast data comes from the US Government’s weather broadcast service.
Advanced
24. Where’s my car?
Use GPS data to find where you parked your car. Advanced
25. Map Locations Use GPS data to mark locations on a Google map. Advanced 26. Friend Locator Design and create an app that shows your friend’s location Advanced Items in BLUE do not have video tutorials but use text directions only.
Page 2
Table of Contents
First apps – (1) Talk to Me, (2) Ball Bounce and (3) Digital Doodle. ................................................. 4
4 – “I have a dream” ............................................................................................................................................ 5 5 – Hello Zombie .................................................................................................................................................. 6
6 -‐ Paint Pot ........................................................................................................................................................... 7 7 -‐ Android Mash ................................................................................................................................................. 9
8 – Magic 8 Ball .................................................................................................................................................. 10
9 -‐ Weather App ................................................................................................................................................ 16 10 – Camera App ............................................................................................................................................... 17
11 -‐ President’s Quiz ....................................................................................................................................... 18 12 -‐ No Texting While Driving ...................................................................................................................... 20
13 – Get the Gold ............................................................................................................................................... 22
14 – Pong ............................................................................................................................................................. 28 15 – Space Invaders ......................................................................................................................................... 30
16 -‐ Mini Golf ...................................................................................................................................................... 34
17 – Stock Market ............................................................................................................................................. 45 18 – The Logo Challenge ................................................................................................................................ 46
19 – Voice Recorder ......................................................................................................................................... 47 20 – Contact Database .................................................................................................................................... 48
21 -‐ Chat App ...................................................................................................................................................... 50
22 -‐ Pizza Order App ....................................................................................................................................... 52 23 -‐ Advanced Weather App ......................................................................................................................... 63
24 -‐ Where’s My Car? ....................................................................................................................................... 68
25 -‐ Map Locations ........................................................................................................................................... 72 26 -‐ Friend Locator .......................................................................................................................................... 77
Page 3
(1) Follow the online tutorial
video for each lesson. Pause the video as necessary. Open two tabs on your web browser – first the App Inventor page and the second tab for the video. If you have a second computer or tablet, you can watch both screens at the same time.
(2) (2) Use the programming blocks printed in this book for reference. (3) When finished with the app, add at least one improvement to the program. (4) Use the following form to write about your assignment. (5) Turn in the form (below) and the AIA source code file using MyBigCampus.com
1. Name Shad Sluiter 2. Assignment Number and Name #1 Talk to me 3. Things that I learned while doing this assignment. What were the main components that this app used? What new methods of programming did you see?
I created my first application with App Inventor. I had to create a APK file and transfer it to my phone to test it out. This program uses the text to speech abilities of Android.
4 Enhancements that I made to the program.
I added a second field and button to allow the program to speak more than one sentence.
Code Blocks.
Application Screen Shot
Page 4
First apps – (1) Talk to Me, (2) Ball Bounce and (3) Digital Doodle. When finished creating each app, copy the APK file to your cell phone for testing using the direction at the beginning of this book. Part 1 -‐ Block Code for Talk to Me.
Part 2 – Block code for Ball Bounce
Part 3 – Digital Doodle.
Page 5
4 – “I have a dream” "I Have a Dream!" is an educational "soundboard" app that plays the famous speech of Martin Luther King. It’s a great way to get started with App Inventor and programming. step 1: Introduction Check out the two apps you'll build
step 2: Build your first app: clicking on MLK plays "I
Have a Dream"
Download the starter app, setup the UI, then code it
so that tapping the picture plays the speech
step 3: Add complexity to the
app in a big way: Malcolm X
speaks! Add a second image and
Player component, then code it
so that you can pause the
speeches.
Page 6
5 – Hello Zombie This application tries to include as many different controls in one application as possible. This tutorial is in two videos. In part 1, I’ll cover how to install App Inventor and then use it to make an app that uses GPS, Opens Dialog Boxes, Opens other apps, vibrates devices, plays sounds, converts text to speech, uses the accelerometer, adapts to screen orientation and more. In part 2, I cover Location Sensor, global variables, changing label text, working with strings, Sound, Buttons, Event Handling, Text to Speech, Vibration, Accelerometers, Orientation changes, Dialog boxes and executing activities. Download the images and sounds here. http://www.newthinktank.com/2014/01/android-‐development-‐beginners-‐2/
Page 7
6 - Paint Pot Paintpot allows you to draw circles and lines on a picture you take with your camera. You'll learn about
the Canvas component, drawing, color, and the Camera component step 1: Introduction
Step 2: Build the user interface Drag out a canvas and sets its width to "fill parent". Then add the color
buttons within a horizontal arrangement.
Page 8
step 3: Draw Line and Circle In the blocks editor, drag
out a Canvas.touched event and then place a
Canvas.DrawCircle within it.
step 4: Add code so that the user can
draw in different colors. Drag out a
Canvas.Dragged event then place a
Canvas.DrawLine within it.
step 5: Add code so the user can
draw circles of different
sizes.. Change the size of the circle
step 6: Add Camera Code
the color button Click events
to set the Canvas.PaintColor
property.
Step 7: Add Slider
Page 9
7 - Android Mash Android Mash is a game in which an Android dude jumps randomly around the screen and you try to mash it. You'll learn about timer events, randomness, and be introduced to animation. Build It Follow the video steps below to build the app yourself. step 1: Professor Wolber introduces the AndroidMash app Check out the app
and see what you'll learn.
step 2: Build the basic game Add
a Canvas and image sprite, then
add blocks so that the mole
moves randomly and touching it
causes the phone to vibrate
step 3: Professor Wolber introduces a challenge Add blocks so that touching the mole
increments the score, the game ends at a certain score, and you can restart the game.
step 4: Add scoring, end game
and restart to the game Add
blocks so that the score is
incremented, the game ends at a
certain score, and the game can
be restarted (solution to
challenge)
Page 10
8 – Magic 8 Ball Magic 8 Ball does not have a video tutorial. Use the written instructions below to complete the app. Part One: Click a Button, Hear a Sound The final Magic 8-Ball App will deliver a prediction from a list that you have designed. To get started, first we'll make a button with a picture on it, and program it to play a sound when the button is clicked.
DESIGN: App Inventor Designer
1. To open the App Inventor Designer window, open a new tab or window in your browser and go to http://newblocks.appinventor.mit.edu. See setup instructions if you are not sure how to sign in.
2. If you have already made an app (such as Hello Purr), you will automatically be directed to the Designer with the last project you worked on showing. Click "Project" in the upper left corner of the screen and then "My Projects", which will take you to your list of projects. Click "New Project" and name your project something like "Magic8Ball" (note: spaces are not allowed).
3. Download images and sounds that you will use in this tutorial at http://www.studyoffice.org/appinventor/8BallImagesSounds.zip 4. On the left column of the Designer, the User Interface palette should be open. If it is not, click to open it.
Drag a Button component over to the Viewer (#1 below).
5. Set the button image to an 8-Ball image: Click on your newly added button to see its properties in the Properties pane on the right. Under "Image" click on the word "None..." and a small selection window will pop up (#2). Click the "Upload File" button and browse to where you saved the 8-Ball image. Select the file, then click “OK” to close the selection window. Click “OK” again on the properties pane to close the small popup window (#3).
Page 11
6. Go to the text field in the Properties pane and delete the display text of your button component (#4).
7. From the Media palette, drag over a Sound component onto the Viewer pane (#1). Notice that since the sound will not be a visible part of the app, it appears at the bottom of the Viewer pane, as a “Non-visible component”.
8. Set the sound component's source file: Click on your newly added sound component to see its properties in the Properties pane on the right. Under "Source" click in the small box on the word "None..." and a small selection window will pop up (#2). Click the "Upload File" button and browse to where you saved the sound file. Select the sound file, then click “OK” to close the selection window. Click “OK” again on the properties pane to close the small popup window (#3).
9. You have now completed the work in the Designer for Part One of this app. It's time now to go over to the Blocks Editor to program the behavior of these components.
BUILD: Blocks Editor
In the upper right corner of the Designer, click on the Blocks button.
Now you are going to tell your app how to behave when the button is clicked. This is actually very simple in App Inventor, because the "code" for the program only consists of two blocks!
Page 12
Once the Blocks Editor is open, there are several options running along the left side of the screen. We refer to these as "Palettes" with “Drawers.”
From the blocks palette located under Screen1, click on the Button1 drawer. Drag the when Button1.Click block into the work area (#1). From the blocks palette, click on the Sound1 drawer, drag the Sound1.Play block into the work area and insert it into the when Button1.Click block (#2). They will click together like magnetic puzzle pieces. Your blocks should now look like this:
That's it! You've written the program for Part One of Magic 8-Ball. Now it's time to test that it's working right.
TEST: Phone/Emulator
You have now built an app! To test that it works, you either have to launch an emulator, or connect to a phone. Go back to the Setup Instructions if you do not have a phone or an emulator running. Emulator: click on the picture, you will hear the sound play. Phone: tap the picture, you will hear the sound play.
Note: If you don't hear the sound, first be sure you have the volume turned up on your device (or computer if using emulator). Also, make sure your device has an SD card. App Inventor stores media files to the SD card. In some devices, the Play component does not work correctly. You will need to use the Player component instead of the Sound component.
Part Two: Click the Button, Get a Prediction + Hear a Sound Now that we've gotten the button to perform an action (play a sound), we want to extend that action to include giving the user a prediction. First we'll need two labels: Label1 will display the instructions, and Label2 will display the chosen prediction. We'll use blocks to program a "list picker" to choose from a list of predictions. Each time the button is clicked, the app will change the text of Label2 to display the chosen prediction.
DESIGN: App Inventor
Go back to the Designer window in your browser and add some new things to your app.
1. From the Screen Arrangement palette, drag over the Vertical Arrangement component (#1). At first it will just look like an empty box, but when you put things in it, App
Page 13
Inventor will know that you want to line them up vertically (one on top of the other).
2. From the Basic palette, drag over a Label component (#2) and drop it inside of the vertical arrangement component. In the Properties pane, change the "Text" property of Label1 to “Ask the Magic 8-Ball a question”.(#3)
3. From the Basic palette, drag over another Label component (Label2) into the Vertical Arrangement box so that it sits right below Label1. Change the "Text" property of the Label2 to “Touch the Magic 8-Ball to receive your answer.” Now drag the 8-Ball image so that it is also inside the Vertical Arrangement component on top of the two labels. This will cause them to line up with each other in a vertical line. (Note: this can be tricky mouse work, but get them in there just right and the vertical arrangement will resize itself to fit everything.)
Now it’s time to go back into the Blocks Editor to program the components you just added to your project.
BUILD: Blocks Editor
Now for the fun part! You're going to make a list of predictions and program the button to pick one item from the list and display it inside Label2. The button will also still play the sound that you programmed in Part One. Here's how to do it...
1. From the blocks palette, click on Label2 drawer to see all of its associated blocks. Drag over the green set Label2.BackgroundColor and insert it just above the Sound1.Play block. Notice that the when Button1.Click block automatically gets bigger to accomodate the new block.
2. Clicking on the word "BackgroundColor" will allow you to change the property that is being set. We want to change the Text so our block will look like set Label2.Text .
Page 14
3. From the Built-In palette, click on the Lists drawer. Drag over the pick random item block and connect it to the open socket of the set Label2.Text block.
4. From the Built-In palette, click on Lists again, then drag out the make a list block and plug it into the "list" socket on the right side of the pick random item block.
5. From the Built-In palette, click on the Text drawer, drag out a " " block and connect it to the item socket of the make a list block. Click directly on the space in the block. You can then type in text there. Think about the sayings you want in your list of predictions for the Magic 8-Ball. Type the first prediction into this new text block.
6. Notice after you plug in two text blocks, there are no more sockets to add more responses. To create more sockets, you need to click the dark blue button on the block. Make a list is called a mutator block and thus can be expanded or shrunk by clicking the blue button in the upper left corner.
7. Plug each text block into the pick random item block. (Ideas for answers: http://en.wikipedia.org/wiki/Magic_8-Ball)
Blocks should look something like this:
You've got a Magic 8-Ball App! Now your app is fully functional and will predict the future with absolute certainty. Test out that this works, and then come back for some challenge tasks to make the app even more fun.
TEST: Emulator or Phone
Emulator: Click on the picture of the 8-Ball, you should see one of your answers displayed in the Label2.Text field, followed by the sound. Phone: Tap on the picture of the 8-Ball, you should see one of your answers displayed in the Label2.Text field, followed by the sound. Part Three: Shake the Phone, Get a Prediction + Hear a Sound Even though you have a working Magic 8-Ball app, there is a way to make it even more fun. You can use the accelerometer component to make the phone respond to shaking instead of responding to a button click. This will make the app much more like a real Magic 8-Ball toy. Note: This part can only be done with an actual phone or tablet equipped with an accelerometer. If you are using an emulator, skip this part and go to Challenge 1 instead. DESIGN: App Inventor
Page 15
From the Sensors palette, drag over an AccelerometerSensor sensor component. Notice that it automatically drops down to the “Non-visible components” area of the Viewer window. This is the only new component you need, so go on over to the Blocks Editor to change your program. BUILD: Blocks Editor
1. From the blocks drawer, click on AccelerometerSensor, then drag out the block for when AccelerometerSensor.Shaking .
2. Disconnect all of the blocks from inside the Button1.Click block and move them inside the AccelerometerSensor.Shaking block. NOTE: you can move whole sections of connected blocks by clicking on the uppermost or leftmost block and dragging it. The connected blocks will come with it.
3. Delete the Button1.Click block to keep your work area tidy. The blocks should look something like this:
TEST: Phone/Emulator
Phone: When you shake the phone it should show an answer and play a sound. Emulator: unfortunately, you can not simulate shaking the phone when using the emulator. Package the App to Your Phone!
Your app would disappear if you were to disconnect your phone from the Blocks Editor. This is because the app is still stored on the App Inventor server and not on your phone. Follow these instructions to package your app to your phone or to make an ".apk" file that can be installed on any android phone. Or, if you want to make your app even cooler, try the challenges below. Challenge 1: Make the Magic 8-Ball Speak
Instead of (or in addition to) making the prediction appear as text, can you make the 8-Ball speak it aloud? Hint: the text-to-speech component is under theMedia palette in the Designer. Note: Most Android devices have the text-to-speech (TTS) capability, but if you have trouble getting the TTS component in App Inventor to work, you may need to find out how to install TTS and/or enable TTS on your device. Suggestions for Further Exploration
• Make the image rotate when the phone is shaken or have several images that the app rotates through while the phone is shaken. You could use this technique to make it look like the triangle piece inside the 8-ball window is surfacing. You could also make different images for different predictions and display the correct image for each prediction.
• Make a similar app but for a different purpose. The phone could be used in place of dice or yahtzee letters. It could simulate a coin toss or a random number or color generator for investigating probability.
• Ask end users to add choices to the list of predictions. • Make the 8 Ball app a "server" so that anyone who sends a text to it will receive a text message prediction in
return. • Complete change the list to humorous choices (e.g. an app for teacher to use when a student has an excuse for
not doing homework), or for useful purposes like randomly selecting a name from amongst people in the class.
Page 16
9 - Weather App This app uses maps from the Weather Underground and weather.com. All together it shows how to display images from the Internet, take pictures, retrieve images from the gallery, store pictures in TinyDB, resize your app to fit any device and more. Watch the first half of the video from 0:00 to 7:50 Part 1 – Design See the video for the layout of the controls on the screen. Part 2 – Blocks
Page 17
10 – Camera App This is a tutorial for an app that shows how to use the camera, image picker and TinyDB with App Inventor. Watch part two of the video from 7:50 to end Part 1 – Design Part 2 -‐ Blocks
Page 18
11 - President’s Quiz Step 1 – The app preview Step 2 – Design the Interface Add an Image component for the picture, a label for the question, and a Next button. There's only one screen-‐-‐ we'll just change the data in it.
Step 3: Define the questions/pictures and program the Next button so the user can navigate Create lists for the questions and pictures, and an index to keep track of your place. Then program the NextButton. Click to show the right question each time. Step 4: Complete the navigation code. Complete the code by adding an “if” block that checks if the user has reached the end of the list.
Page 19
step 5: Let the user answer, then check it Add a textbox and button for the user's answer, then use an if block to check whether the submitted answer is correct step 6: Turn the quiz into multiple choice Add a ListPicker component and code it so the user chooses an answer instead of typing it. step 7: Change it so there are different answer choices for each question. (click for details) Add an AnswerChoices list which is a list of lists, where each sublist is the answer choices for that question.
Page 20
12 - No Texting While Driving Driving or in a meeting? Open this text answering machine app and it will auto-‐respond to incoming texts.
Build It Follow the video steps below to build the app yourself.
step 1: Professor Wolber introduces the app. Understand what the "No Texting While
Driving" app does
step 2: Build a simple auto-‐responder When a
text comes in, send a text back.
step 3: Speak the text aloud. Add a TextToSpeech component and have it speak
out the text.
step 4: Let the user set the response message Add an input form and use the input to change the
response sent out.
step 5: Add option to choose whether text spoken aloud. Add a checkbox
Page 21
and only speak text aloud if it is checked.
step 6: Save the custom message in the database. Use a TinyDB component
to store the message so it
is available even if you
close and re-‐open the
app.
step 7: Code it so the input form appears on a button click. Set the input form as non-‐visible to
start, then have it appear when an "edit"
button is clicked.
step 8: Improve the user interface Place an image on the edit button and beautify the UI
Page 22
13 – Get the Gold Get the Gold does not have a video tutorial. Use the written instructions below. What You're Building
By building the Get The Gold App you will get practice with setting visibility, using Clock components and Timers, and detecting collisions in App Inventor. You'll program an application that has a pirate ship whose goal is to collect all the gold on the screen. Getting Started
Connect to the App Inventor web site and start a new project. Name it GetTheGold, and also set the screen's Title to "GetTheGold". Switch to the Blocks view and connect to a device or emulator. Introduction
This tutorial introduces the following skills, useful for future game development:
• Using the Clock component • Using Clock.Timer to move sprites • Using Sprite.Flung to move a sprite • Using collision detection
Getting Ready
For this game, you will have two types of imagesprites: pirate and gold coin. You can download these images at
http://www.studyoffice.org/appinventor/getthegold.zip
Set up the Components
Use the component designer to create the interface for GetTheGold. When you finish, it should look something like the snapshot below (more detailed instructions below the snapshot).
Page 23
To create this interface, put the following components into the Designer by dragging them from the Component Palette into the Viewer.
Component Type Palette Group
What you'll name it Purpose of Component
Canvas Drawing and Animation Canvas1
The background that we will be putting our imagesprites on
ImageSprite Drawing and Animation PirateSprite The pirate ship in our game
ImageSprite Drawing and Animation ImageSprite2 One of the gold coins in the game
ImageSprite Drawing and Animation ImageSprite3 One of the gold coins in the game
ImageSprite Drawing and Animation ImageSprite4 One of the gold coins in the game
ImageSprite Drawing and Animation ImageSprite5 One of the gold coins in the game
ImageSprite Drawing and Animation ImageSprite6 One of the gold coins in the game
Clock User Interface Clock1 We use the Clock for its Timer method to move the coins
Button User Interface ResetButton To reset the game so the player can play again
Set the properties of the components as described below:
Component Action
ResetButton Change Text property to "Reset".
PirateSprite Change Speed property to 6. Upload the pirateship image and set Picture property to pirateship.
ImageSprite(2,3,4,5,6) Upload the goldcoin image and set Picture property to goldcoin.
Clock Change TimerInterval property to 2000.
Moving the Pirate
To move the PirateSprite, we want the user to be able to "fling" the sprite in the direction that they choose. To do this, we will use the PirateSprite.Flung event handler.
Page 24
You may notice that PirateSprite.Flung takes in 6 attributes: x, y, xvel, yvel, speed, and heading. We want to reassign PirateSprite's current heading to the heading given to us from PirateSprite.Flung. This means that the user can now control the direction of the pirate ship with their fingers by flinging on the screen.
To prevent the pirate from moving off the screen, we will also use PirateSprite.Bounce when an edge is reached.
Moving the Coins
We want the coins to move to random positions on the screen. We will use Clock1.Timer and the ImageSprite's MoveTo method to do this. When the Clock1.Timer goes off, we want all of our gold coin ImageSprites to move to a new random location on the Canvas. We will do this by using the Sprite.MoveTo block. MoveTo takes in two arguments: the x and y coordinates on the canvas of the new position we want the sprite to move to. We want the Sprite to move to a new random location so we will use the random integer block found in the Math box. Since we want each Gold ImageSprite to move to a new location, we repeat this process for each sprite's MoveTo function. For ImageSprite2, we want x to be a random integer from 0 to Canvas1.Width-ImageSprite2.Width and y to be a random integer from 0 to Canvas1.Height-ImageSprite2.Height. This is to be repeated for all the Gold Image Sprites. Remember that sprites are measured at the upper left corner as (0,0) so if we don't want them to go off the screen, we need to take the sprite's height/width into account when setting the range for our random numbers.
We will do this by setting up our blocks as in the image below:
Page 25
Detecting Collisions
App Inventor detects collisions by checking for an intersection between the bounding rectangles of each ImageSprite. We call this rectangle-based collision detection. As you can see in the image below, sprites with circular or polygon shape will appear to collide because of the rectangular bounds around them when they might not actually be colliding.
We can use the PirateSprite.CollidedWith event handler to detect whenever the pirate ship collides with another sprite or gold coin. You may notice that PirateSprite.CollidedWith takes in an argument. This argument is the object that PirateSprite just collided with. We will be testing inside the handler for which object so the name of this argument is not significant. You can name it other. Whenever the pirate collides with a gold coin, we want the coin to disappear. We can do this by setting the coin's visibility to false. To find which coin the pirate collided with, we will use the PirateSprite.CollidingWith . We can use PirateSprite.CollidingWith to take in a component (each of the gold coin sprites) to detect which sprite was hit. This is a component block and NOT a text block with the words ImageSprite inside. The component block can be found in the drawer for each component. If a sprite was hit, we will set its visibility to false.
Page 26
Reset Button
After the user hits all of the gold sprites with the pirate ship, none of them will be visible. The reset button should set all of the gold sprites' visibility to true.
Complete Program
Here's the complete GetTheGold program.
Page 27
Once you get this program running, you may want to do the following additional features to extend it. For example,
• Create a label to display the time that it took you to get all the gold • Change the speed of the ship or gold coins • Add an enemy sprite that when collided with, causes your pirate to lose speed • Use one of the phone's sensors to control movement of the pirate ship
Page 28
14 – Pong
Build the classic game Pong and learn how to animate image sprites, deal with collisions, keep score, and define procedures to make your code better.
Build It Follow the video steps below to build the app yourself.
step 1: Code it so a ball moves downward (animated) Add blocks so that clicking on the start button enables the ball and
sets its speed/heading to move downward.
step 2: Code it so the ball moves in a random direction downward to start the game. Get a random number for a range of numbers and
set the heading to the randomly generated
number.
step 3: Code it so the ball bounces off edges and the paddle Program the
ball.EdgeReached event and
use the Bounce operation.
For the paddle, program
CollidedWith and change
the Heading.
step 4: Code it so the user can drag the paddle horizontally Program the
Page 29
Paddle.Dragged event and modify only the X property of the paddle
step 5: Code it so you get a point every time the paddle hits the ball Modify the
ball.CollidedWith to modify the score. Use a procedure which adds one to the score and updates the label showing the
score. Be sure and s et the Score to 0 at proper times.
step 6: Code it so game over when ball hits bottom edge. Check the particular edge that is hit on EdgeReached and game over if bottom.
step 7: Code it so there is sound effects for paddle, edges, and game over Add some sound files in the
designer then play them in the various events.
step 8: Code is so the user can check a box to turn sound off (or no) Add a checkbox. Anytime
you are playing a sound, check to see if checked-‐-‐ us a procedure to simplify.
Page 30
15 – Space Invaders Space Invaders What You're Building
By building the Space Invaders App you will get practice with using Clock components and Timers, using Animation components such as Image Sprites and the Canvas, setting visibility, and detecting collisions in App Inventor. You'll program an application that has a shooter ship whose goal is to shoot all the flying saucers on the screen. Getting Started
Connect to the App Inventor web site and start a new project. Name it SpaceInvaders, and also set the screen's Title to "SpaceInvaders". Connect to a device or emulator. Introduction
This tutorial introduces the following skills, useful for future game development:
• Using the Clock component • Using Clock.Timer to move sprites • Using Sprite.Flung to move a sprite • Using collision detection • Setting visibility of sprites
Getting Ready
For this game, you will have two types of sprites: an imagesprite represented by a shooter ship and flying saucers represented by a ball sprite. Download the image files for your rocket ship sprite and flying saucer sprite.
http://www.studyoffice.org/appinventor/spaceinvaders.zip
Set up the Components
Use the component designer to create the interface for SpaceInvaders. When you finish, it should look something like the snapshot below (more detailed instructions below the snapshot).
To create this interface, put the following components into the Designer by dragging them from the Component Palette into the Viewer and set the properties of the components as described below:
Page 31
Component Type
Palette Group
What you'll name it Purpose of Component
Action
Canvas Drawing and Animation
Canvas1 The background that we will be putting our sprites on
Change Width property to "Fill parent" and Height property to 300. Set the BackgroundColor property to Black.
ImageSprite Drawing and Animation
RocketSprite The rocket ship in our game
Upload the rocketship image and set the Picture property to "rocket.png". Set the Y property to 230. This will place the rocket at the bottom of the canvas.
ImageSprite Drawing and Animation
SaucerSprite The flying saucer in our game
Upload the saucer image and set the Picture property to "saucer.png".
BallSprite Drawing and Animation
Bullet The bullet from the rocket ship.
Change PaintColor to Green and set the Radius property to 8.
Clock User Interface
Clock1 We use the Clock for its Timer method to move the the saucer
Change TimerInterval property to 3000.
Horizontal Arrangement
Layout HorizontalArrangement1 To contain Label1 and ScoreLabel
Label User Interface
Label1 To contain the word "Score: "
Change Text property to "Score: ".
Label User Interface
ScoreLabel To contain the current numerical score
Change Text property to "0".
Button User Interface
ResetButton To reset the game so the player can play again
Change Text property to "Reset".
Now that you have all the essential properties configured, feel free to change the colors of any components that you want to.
Moving the rocket
In this game, the user will move the rocket from side to side. This means we will only be changing the X-direction of the rocket sprite. To do this we will use the RocketSprite.Dragged event handler. When the rocket is dragged, we will adjust it's X property to be the currentX that we dragged the sprite to. Once you put these blocks together, connect your phone and test this feature out!
Programming the Bullet's Behavior
There are several features we want our bullet to have in this game. We want it to shoot from the rocket, collide with the saucer, and be invisible after the collision and before being shot.
Let's start by using the Screen1.initialize block. When the screen is initialized, we will program the bullet to be invisible. We do this by setting the bullet's visibility property to False.
Page 32
Next, we want to make sure that the bullet appears again when we shoot from the rocket. When we touch the rocket, we want the bullet to start heading towards the saucer. We will do this by using the RocketSprite.Touched event handler. When the rocket is touched, we not only want to set the rocket to be visible, but we also want to set the speed and heading of the rocket. Heading is a value from 0 to 360 that indicates what direction the sprite should be moving towards. 0/360 is to the left, 90 is up, 180 is right, and 270 is down. The speed is measured in pixels/sec. The last thing we need to program is what happens when the bullet hits the saucer. We will use the Bullet.CollidedWith event handler. This event is called whenever the bullet collides with another sprite. Since our rocket sprite is locked into a Y at the bottom of the screen, the bullet will never collide with the rocket and only with the saucer. On collision we want two things to happen. 1. The score should increase by 1. 2. The bullet should become invisible.
If you have started testing this game out, you may have noticed that once you shoot the bullet, it doesn't appear to let you shoot it again. We need to program the bullet to return to the place in front of the rocket when we shoot it. We can do this using the Bullet.MoveTo block.
Now, test it out!
You may have noticed that if you miss the saucer, the bullet moves to the top of the screen and gets stuck there until you try shooting again. To make the bullet disappear when it hits the top edge of our canvas, we need to use the Bullet.EdgeReached event handler.
Programming the Reset Button
Sometimes, users might want to restart the game and reset their score. When this happens, we need to set the score
Page 33
back to 0.
Increasing the Difficulty -- Changing the Position of the Saucer
Let's make the game a little more challenging! Now, when the bullet collides with the saucer, let's change the location of the saucer. The saucer will keep the same Y value so we'll only have to change the X. We can do this by using the random block.
To make it even more difficult, we'll also change the position of the saucer when the Timer goes off.
Complete Program
Here's the complete SpaceInvaders program.
Page 34
16 - Mini Golf Fling, TouchUp, TouchDown Gestures for sprites. This is a text tutorial, rather than video. To play this mini golf app, the player first positions his/her ball within the confines of the tee, and then flings the ball toward the hole. The ball will bounce off of the rectangular obstacle and the sides of the course. For each fling of the ball, the stroke count goes up by one. The total score is the number of strokes it takes to complete the entire course. This tutorial covers:
• Using the Sprite component and the TouchUp, TouchDown, and Flung events
• Using a Clock component • Dynamic Positioning of sprites on a canvas, based on the size of the
screen • Sprite Collisions
This tutorial assumes you are familiar with the basics of App Inventor-- using the Component Designer to build a user interface, and using the Blocks Editor to specify the app's behavior. Images Download the images used in this tutorial at www.studyoffice.org/adppinventor/minigolf.zip
Part I: Start a new app and make a ball that responds to fling events
We'll build this app in stages, adding a little bit of the game at a time. Log into App Inventor and start a new project. Name it "MiniGolf". When the Design window opens notice that App Inventor automatically names the screen "Screen1", but you can set the Title of the screen, which will show up in the top bar of the app. Think of a title related to Mini Golf, or feel free to use the suggested title "Fling It Mini Golf", and type it into the Properties pane on the right side of the Designer.
In the Screen Properties (shown in right-hand pane): Uncheck the checkbox labeled "Scrollable" so that the screen will not scroll when the app is running. Screens that are set to scroll do not have a height. We’ll need our screen to have a defined height in order to set up the golf course properly.
Add the following components in the Designer:
Page 35
Component Type
Palette Group
What You'll Name It Purpose Properties
Canvas
Drawing and Animation Canvas1
The canvas serves as the golf course
Height: 300 Width: FillParent BackgroundColor: Green (or whatever you like!)
Ball
Drawing and Animation GolfBall
This is the ball the player will fling to try to hit the Hole
Radius = 10 Color: White (or your choice!) Speed: 0 Interval: 1 (ms) Z = 2 (when sprites are overlapping, the one with the higher z will appear on top)
Ball
Drawing and Animation Hole
This will be the target for the GolfBall
Radius = 15 Color: Black Speed: 0
Clock User Interface Clock1
The clock will fire continuously to control the movement of the ball
Timer Always Fires Timer Enabled TimerInterval: 100
Open the Blocks Editor Program the behavior of the Ball: First, use the GolfBall.Flung event handler to move the golf ball when it is flung. Notice how this event handler takes in 6 different arguments:
• x, the x position on the Canvas grid of the user's finger • y, the y position on the Canvas grid of the user's finger • speed, the speed of the user's flinging gesture • heading, the direction (in degrees) of the user's fling gesture • xvel, the speed in the x direction of the user's fling • yvel, the speed in the y direction of the user's fling
Essentially, you want to set the GolfBall’s speed and heading to match the speed and heading of the player’s fling gesture. You may want to scale up the speed a little bit because the speed of the fling is a little slower than how a golf ball would move. You can play with this "scaling factor" to make the ball more or less responsive to a fling.
Page 36
Program the behavior of the clock: Use timer event to slow ball down so it doesn’t bounce around forever.
Each time the clock fires, it will reduce the speed of the ball slightly. Notice that if the ball is not moving then these blocks will do nothing. If you don’t have this then the ball will just bounce forever.
You'll need to use the if mutator function to change the if block into an if-else block. For a summary of mutators, check out the Mutators page
Program a new procedure called SetupNewHole: This procedure will be called when a hole is scored and the ball has to be placed back at the starting point. Note that the Hole.MoveTo block sets the hole up in a new random location for the next play.
Program the Behavior of the Hole: When the ball collides with the hole, the ball disappears and resets at the bottom of the screen. Note: When you first drag out the GolfBall.CollidedWith event handler, the named parameter is called "other". Notice that the if then block tests to see if the object involved in the collision with the golf ball ( other ) is the black ball sprite representing the hole. You can't just put a text block with the word "Hole" in it, you must use the Hole block, that can be found in the drawer for the Hole image sprite. Do not use a text block here.
Test this Behavior. Connect your device to AppInventor, or start the emulator to load your app. When you fling the ball it should move in the direction of your fling, with a speed similar to the strength of your fling. The ball should slow down as it moves, eventually stopping. When the ball hits the hole, the ball should reset at the bottom of the screen and the hole should move to a new random location.
Page 37
Does your ball get stuck if it hits the edge? This is easy to fix with the when EdgeReached event. Note that you can find the "edge" value block by using a get block and selecting "edge" from the dropdown.
Double check to make sure your code is right: fling the ball a few times and see that that ball now bounces off the edges of the course.
Part II: Keeping Score
Games are more fun if you have a way to see how you’re doing. Let’s add a stroke counter. In mini golf your score goes up as you take more strokes. The goal is to have the lowest score possible. Let’s show the player how many strokes she or he has taken on this hole. Let’s also show the number of strokes taken during the whole game.
Go back to the Designer and set up the following components:
Component Type Palette Group
What You’ll Name It Purpose Properties
Horizontal Arrangement Layout
HorizontalArrangement1
Contains LabelScore and LabelStroke
Place at top of screen
Label User Interface LabelScore
Displays the total stroke count for the entire game
Label User Interface LabelStroke
Displays the stroke count for the hole the player is currently on
In the Blocks Editor, you can program updates to the Score and Stroke labels. First, set two new global variables called StrokeCount and Score , and set their initial values to 0.
Then add the following blocks to the GolfBall.Flung event (red rectangle indicates new blocks):
Page 38
Next add the following blocks to the Event that handles the ball hitting the hole:
Test the behavior. With these new changes, you should have a "Total Strokes" count and "This Hole" count at the top of the screen. When you fling the ball, the "This Hole" count and "Total Strokes" count should both increase by one, and when you make the ball go into the hole the "This Hole" count should reset to 0.
Part III: Positioning Ball on Tee using TouchUp and TouchDown events
Ok, so now you’ve got a working game! Now let’s make it a little more interesting and fun. First we’ll add a Tee and let the player position the golf ball on the tee before they fling the ball.
Go back to the Designer and add three new image sprite components:
Component Type Palette Group
What You’ll Name It Purpose Properties
ImageSprite Drawing and Animation Tee
A rectangular area in which the player can position their ball before teeing off.
Upload the Tee image
Page 39
ImageSprite Drawing and Animation LeftSprite
This is a left pointing arrow that the player will use to move the ball to the left on the tee
Upload the left arrow graphic
ImageSprite Drawing and Animation RightSprite
This is a right pointing arrow that the player will use to move the ball to the left on the tee
Upload the right arrow graphic
Program the size of the canvas, and the placement of the ball and image sprites on the canvas: First, program the setup of these components on the screen. It’s best to accommodate all different screen sizes by placing the sprites on the screen relative to the size of the screen. The blocks below show how to set up the screen dynamically so that everything fits the right way. We start off by making the canvas size based on the screen size, and then we place each sprite in relation to the width and height of the canvas. We'll make a procedure to do this for us. Try to understand all of these blocks before you move on.
Position the Golf Ball on the Tee using TouchUp and TouchDown on the Arrow sprites: To handle this, first set up two global variables that are toggled each time an arrow is pressed.
Program the behavior of the Right and Left Arrows
Page 40
The left and right arrows are image sprites, so they come equipped with the ability to know when the player is is holding his/her finger down on them. The following blocks toggle the global variables based on whether the user is pressing either of these arrows.
Procedure MoveBallOnTee: Make a new procedure moveBallOnTee that makes the golf ball move left or right on the tee depending on the global variables. Although the math here looks complicated, it’s pretty simple. If the ball is supposed to move left, you first check to make sure that moving the ball 2 pixels left will not exceed the left-most coordinate of the Tee. If moving the golf ball to the right, you first check that moving the ball right 2 pixels will not move it past the right-most coordinate of the Tee. Note: if blocks look different in this image than on your own screen, this is because they were aligned differently. If you right click on the blocks, a list of options will appear and one of them is external inputs. When you select this, it will change how the blocks are configured. It does not change how the blocks function. If you want to change this, right click again and select internal inputs.
Page 41
MoveBallOnCourse Procedure Note that the blocks that we had inside the Clock1.Timer event are now moved over to a new procedure called moveBallOnCourse:
On each new course, players can position the ball on the tee before attempting to fling the ball toward the hole. To program this, you first have to check to make sure this is a new course and the ball has not been flung yet. If StrokeCount = 0 then we know this course is brand new and the player has not yet attempted to get the ball into the hole.
As the blocks above show, after verifying that the StrokeCount is 0, you then want to proceed to move the golf ball left or right depending on which arrow is being pressed.
Test the behavior. Make sure your app is doing what you expect: play the game on your device or emulator. Before you tee off, are you able to move the ball left and right on the tee by using the left and right arrows? After you tee off, you should no longer be able to use the left and right arrows (pressing them will do nothing). After the ball goes into the hole and the screen resets, you should then be able to move the ball left and right on the tee before teeing off again.
Keep track of the number of holes played, and allow a game reset The game is working pretty well now, but what about giving the player a way to reset the game? Also, it would be nice to give the player some instructions so they know how to play the game. While we’re at it, let’s also give an indication of how many holes the player has completed. Add the following components in the Designer:
Component Type
Palette Group
What You’ll Name It Purpose Properties
Horizontal Arrangement Layout
Horizontal Arrangement2
Contains the NewGame button and the HoleNum label
Button User ButtonNewGame Resets the game to Hole #1 Text: "New Game"
Page 42
Interface with a score of 0.
Label User Interface LabelHoleNum
Displays the current hole number, increments by one each time a hole is completed.
Text = "Hole # 1" Font: bold, 28, blue
Label User Interface LabelInstruct Displays instructions
Text = "Use arrows to position ball on tee. Hit the ball by flinging it with your finger."
Define a new global variable to keep track of the Hole Number:
Add the following blocks to the setupNewHole
procedure: set global HoleCount and set LabelHoleNum.Text...
Program the "New Game" button’s behavior, which is pretty simple. When the button is pressed, set up a new course and reset both the hole stroke counter and total stroke counter to zero. Also set the hole number back to 1, by displaying "Hole #1" in LabelHoleNum. The blocks look like this:
Page 43
Test the behavior.
Go back to your device or emulator and play the game some more. Now you should see the Hole # displayed in the lower right. Hitting "New Game" button should reset the game, returning both scores to 0, resetting the screen, and setting the Hole number to #1.
Part IV: Introduce an Obstacle
Most mini golf courses have obstacles on them. Let’s add a simple rectangular obstacle that will randomly position itself on the course somewhere between the Tee and the Hole. Each time a new course is presented, the obstacle will move, just the same way the Hole moves each time a new course is set up.
Add the following component in the Designer:
Component Type
Palette Group
What You’ll Name It Purpose Properties
ImageSprite Drawing and Animation ObstacleSprite1
This sprite will be somewhere between the golf ball and hole and will make it harder to get the ball into the hole
Upload the obstacle (rectangle) graphic
Program the behavior of the obstacle in the blocks editor. First, set the behavior for when the ball hits the obstacle. *Note: Using Heading = 0 - heading works because we are dealing with bouncing off of horizonal surfaces, this will not work for bouncing off of vertical or inclined surfaces. For our purposes, it works all right. See Challenge #2 below for more information.
Each time the course is reset, position the obstacle will be positioned randomly. Add these blocks to the setupNewHole procedure:
Page 44
Test the behavior. Play the game again. Notice that the ball bounces off when it hits the obstacle. When the ball goes into the hole, or when the New Game button is pressed, the obstacle appears in a new location somewhere between the tee and the hole.
That’s it! Share your game with friends by building an APK or by downloading the source and sharing the zip file with other App Inventors!
Part V: Challenges
Here are some extra challenges to make your game better.
Challenge 1: Program the Ball to Hole collision so that the ball only goes into the hole if the golf ball’s speed is not too fast. In real mini golf, the ball will bounce right over the hole if you hit the ball too hard. Challenge 2: There is a slight bug when the ball hits the vertical sides of obstacle. Figure out how to program the ball to obstacle collision so that it bounces the way you would expect when the ball hits the vertical sides. Challenge 3: Limit the number of holes per game. Keep track of the number of holes and end the game after a set number. (A typical mini golf course has 18 holes.) Below is a summary of all of the components:
Page 45
17 – Stock Market
The Stock Market app displays the current price of any stock you enter. You'll learn how to web-‐enable your app and communicate with Web APIs, in this case Yahoo Finance
Build It Follow the video steps to build the app yourself. step 1:
Create an app that shows current Google stock price Use the Web component, call Web.Get, and then process the response
in Web.GotText
step 2: Parse the returned data to show only the price Put the returned data into a
list, then extract the
first item only
step 3: Change the app so that the user can enter any stock symbol Add a Textbox then build the API call by
joining the fixed part with
the user's entry
Page 46
18 – The Logo Challenge Program the Android Logo to create shapes and learn about algorithms, procedures, and parameters Build It Follow the video steps below to build the app yourself.
step 1: Learn about algorithms and brushing your teeth Listen as Professor Wolber introduces algorithms,
procedures, and repeat blocks
step 2: Professor Wolber introduces the Logo
Challenge Learn about the app and how to get started.
step 3: Create procedures for drawing squares of different sizes Code an algorithm for drawing a square using forward and turn blocks.
step 4: Professor Wolber introduces the 2nd Logo Challenge Learn about procedure parameters and
how to code procedures that are more reusable.
step 5: Create procedures with parameters to draw polygons Create a drawSquare(L) procedure where L is the length of the sides, and a drawPolygon(L,sides) procedure.
Page 47
19 – Voice Recorder In this tutorial we make an Android Beat Box App. It could also be converted into a voice note app, or anything else that would benefit from being able to record and later play back sounds. I’ll specifically cover how to use the Android SoundRecorder, Player, take another look at using list, teach more about logic and incremental programming. All of the blocks used can be found below. The answer for the Reset Button homework is also down there. Watch the video to see the design view (buttons and other controls).
Page 48
20 – Contact Database Through making this app I will cover most everything about using Lists, List Pickers, TinyDB, TinyWebDB, Fusion Tables, and Texting. I start off simply here by focusing on creating Lists through an interface. Part 1 – Screen Design
Page 49
Part 2 – Blocks
Page 50
21 - Chat App In this part of my App Inventor tutorial, I will provide an App Inventor TinyWebDB Example. It will allow you to chat with anyone who also has the app. TinyWebDB is one of several methods for saving data on a server which allows apps to communicate with each other. Part 1 – Display
Page 51
Part 2 – Blocks
Page 52
22 - Pizza Order App This application shows how to share information between different cell phones. The app must store information in an online database operated on Google servers called a FUSION TABLE. You will create an app that lets people enter food orders for a pizza party. All members of the party will be able to see each other’s requests. 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. A Fusion Table is a Google service to support the gathering, managing, sharing, and visualizing of data. Data are stored in multiple tables on Google's cloud. Individual tables can be merged (or fused) if they contain a common column, and they can be easily visualized on maps and in various kinds of charts and graphs. All of the data are stored in a public table that can be accessed via Google Drive, and allows different users to add information to the tables. This tutorial introduces:
• Using the FusionTables component • Using a WebViewer component
This tutorial assumes you are familiar with the basics of App Inventor-- using the Component Designer to build a user interface, and using the Blocks Editor to specify the app's behavior. IF YOU DOWNLOAD THE SOURCE CODE you will need to supply your own API KEY, your own Table ID, and your own TABLE URL in the global variables in the blocks editor. This source code will not work without these additions. Creating your own Fusion Table
Creating your own Fusion Tables is as easy as creating a Google document.
1. On the web, login to your Gmail account or any other Google service (e.g., Drive, YouTube).
2. Go to Google Drive (http://drive.google.com ) and click the red Create button, you will see Fusion Table in the list of choices. Click Fusion Table. (If you do not see Fusion Table in the Google Drive Create menu, click
Connect more apps. Scroll down until you find Fusion Table and click on
it. Click the + Connect button, then click ok. Now, when you click on the
Create button, Fusion Table should appear. If not, then you may need to
contact your school's network administrator. See Troubleshooting section
at the bottom of this page.)
Page 53
3. You will be given a few different options for
the new table. Select Create an empty table. 4. You will see that the new table automatically comes with four columns. Change the
column names for your Pizza 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). .
5. 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.
6. Click on the Share button (top right) to modify the table's permissions. For this tutorial, you can specify a few friends who will use the app. Only people who are explicitly given permission will be able to enter pizza party preferences through your app.
NOTE about Sharing Fusion Tables: To share a FusionTable with others, you have to share it with each person individually, or you can share with a Google Group the same way you would share a private google doc. There is no way to share write privileges to a FusionTable with the public. Public access is restricted to read-only. To share a FusionTable with many people, rather than by entering email addresses individually, you can create a dedicated Google Group for your app and let all the app users know how to join the group (maybe through the web page for your app). From the moment you create your app, you share the Fusion Table once with your Google Group (using its email address), and make sure to give to the group editing rights. Every user who joins the group will inherit the editing rights automatically.
You will use this URL in the app. You can try it now by copying and pasting it into a web browser. You should see an empty table.
You will have to invite other Google users or groups to have update / write access so the app can be shared.
Page 54
Getting an API Key
In order to use the FusiontablesControl Component you need to acquire a Google Applications Programming Interface (API) key, an API Key. To get an API key, follow these instructions:
1. Go to your Google APIs Console and log in with a google account if not already logged in.
2. On the left-hand menu, select the APIs & auth item. The top sub-item "APIs" should be selected. If not, select it.
3. In the list of APIs, scroll down to find the Fusion Tables API and click the toggle button to "on" (if it already says "on" then leave it as is.)
4. If prompted, read and agree to the terms of service. On the Devlopers Console API page you'll see that the on/off switch next to Fusion Tables API is now "On" and green.
5. Go back to the menu on the left of the screen and select the Credentials sub-item under "APIs & auth.
6. Your API key will show up under "Public API Access". If you do not see an API key, click the button "Create New Key" and then click the "Android Key" button in the popup box. Don't worry about the pop-up box asking about SHA keys. Just click the "Create" button.
7. Your API Key will be show up under "Key for Android applications". You will need to use the "API Key" property of the Fusiontables Control component in any app that you make that uses Fusion Tables.
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 lessons. Use the component designer to create the interface for the Search Party. When completed, the designer should look like this:
You will copy and paste this API KEY number in the app.
Page 55
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,
Page 56
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
Page 57
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:
1. In your browser, navigate to the new Fusion Table you just created.
2. Go to the menu and select Tools > Publish. 3. You'll see a notice saying: "This table is private and will not be visible". Click the blue link
that says "Change Visibility".
4. In the list of "Who Has Access", click the blue "Change..." link next to "Private - Only people listed below..."
5. 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.
6. Click the Save button, then the Done button.
7. 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).
8. You can find the Table ID by browsing to your table, then selecting File>About this table in the menu.
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 API_KEY Variables
Initialize this global variable to your own API Key for Google Fusion Tables. See instructions above.
You will copy and paste this URL in the app.
Page 58
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 API Key property (set to global API_KEY) and the WebViewer component's HomeURL property (set to global TABLE_URL). We also tell the app to forget the user's login credentials. This will prompt the user to login to their Google account and give permission to the app to access the Fusion Table. This authentication step will happen only once when the app first tries to access the Fusion Table. Remember, Fusion Tables are only writeable by users who have been given permission by the table's owner. You specify this in the Sharing settings for the Fusion Table (easy to do from the Google Drive webpage.)
Set up the resetForm procedure as shown below. After recording an entry, this procedure resets the interface back to the original state.
Copy and paste these three values from the Fusion Table setup you did earlier.
Page 59
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.
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 (not blank), 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:
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. This procedure involves two steps: (1) constructing the insert query and then (2) sending the query to Google's Fusion Table service. The query we want to send will take this format: INSERT INTO (, , ...) VALUES (, , ...) The words in CAPS are part of the query's syntax. The words in parentheses are values that we need to plug in. First there is a list of (column names) followed by VALUES followed by a list of (value names). The order of the column names and value names must be in the same order so that
Page 60
they match up. An example of what this might look like is shown below. Notice that the values must be enclosed in single quotes: INSERT INTO 191GHtZ_B2 (Name, Date) VALUES ('Sam', '10/10/2012') 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.
To construct the query we use App Inventor's join text block. Be sure to PUT SPACES where needed, such as before and after the words INSERT INTO and VALUES:
Page 61
Did you remember to put a space after the word INTO and before and after the word VALUES? 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. Don't forget the FusiontablesControl.SendQuery command at the very end of this procedure. It's small in size compared to rest of the procedure, but very important. 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 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. Remember, you have to give each user permission to access the Fusion Table. You do this through the Google
Page 62
Fusion Tables interface, not through App Inventor. Luckily, this means you don't have to change the app in order to add more users who can access the table. 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 working, 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; perhaps 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 API Key into the API Key property field on the FusionTables component in the Design Window.
To familiarize yourself with fusion tables, have a look around the Fusion Tables Web Site. http://support.google.com/fusiontables/bin/answer.py?hl=en&answer=2571232 Check out the example gallery to see what kinds of things are possible. Work through this Fusion Table tutorial http://earth.google.com/outreach/tutorial_fusion_sample.html , 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. NOTE about Sharing: To share a FusionTable with many people, rather than by entering email addresses individually, you can create a dedicated Google Group for your app and let all the app users know how to join the group (maybe through the web page for your app). From the moment you create your app, you share the Fusion Table once with your Google Group (using its email address), and make sure to give to the group editing rights. Every user who joins the group will inherit the editing rights automatically.
Page 63
23 - Advanced Weather App This is a professional looking application. It displays the weather forecast for any US city. Forecast data comes from the US Government’s weather broadcast service. This series of six videos takes you from the creation of icons using a drawing tool like Illustrator to the finishing touches of a weather service program. Android for Beginners 9 : In this video I will show how to parse JSON Data with App Inventor. JSON (JavaScript Object Notation is a message format) I also cover the App Inventor Web component, using Location Sensor, converting JSON data into an App Inventor List. Android for Beginners 10 : In this tutorial I’ll walk you step-‐by-‐step through the process of using App Inventor to Parse JSON data. I’ll pull JSON weather data from Weather.gov and show how App Inventor organizes that data. I’ll also show you how to add padding to components in App Inventor. Android for Beginners 11 : I will start covering Android interface design. I want the weather app we have been creating in parts 9 and 10 of this series to look very nice. Here I’ll show you how I created the layout and I’ll also walk you through the techniques needed to draw all of your icons in Inkscape. Android for Beginners 12 : I’ll focus on creating App Inventor interfaces. I’ll take the vector art I made in the last tutorial and convert it into a App Inventor interface. I create regular non-‐App Inventor interfaces in pretty much exactly the same way. Android for Beginners 13 : Covers how to create a dynamic interface, pull data from a web service, work with colors and cover logic in App Inventor. This is basically a large review. Android for Beginners 14 : I completely finish the Android weather app. I show how to make App Inventor wait for an operation to complete before proceeding. We also will allow the user to pull up latitude and longitude data when they enter their city and state. We use that data to pull current weather data. We teach are app to speak the weather to us.
“Mostly sunny with a high near 40”
Page 64
Page 65
Page 66
Page 67
Page 68
24 - Where’s My Car? You parked somewhere near the stadium, but when the concert ends you don't have a clue where the car is. The friends you came with are equally as clueless.
Fortunately you haven't lost your Android phone that never forgets anything, and you remember you have the hot new app, Android, Where's My Car?. With this app, you click a button when you park your car, and the Android uses its location sensor to record the car's GPS coordinates and address. Later, when you reopen the app, it shows you a map from where you are to the remembered location-- problem solved! Getting Started
The app demonstrates how to communicate with the Android location sensor, how to record data in the phone's long-term memory (database), and how you can open the Google Maps app from your app to show directions from one one location to another. It makes use of the following App Inventor components:
• Location Sensor • TinyDB -- to store the data • ActivityStarter -- to open a map
The User Interface
Here are the components for the Android, Where's My Car? app, as shown in the Component Designer:
Page 69
The user interface consists of labels to show location data and buttons to initiate events. Some labels just show static text, e.g., GPSLabel is the text "GPS:" that appears in the user interface. Others, such as CurrentLatLabel, will display dynamic data one the location sensor gets its readings. For these labels, a default value is set (0) here in the Component Designer.
The ActivityStarter1 component is used to launch the map when the user asks for directions. Its properties are only partially shown above. Here is how they should be specified:
Property Value
Action android.intent.action.VIEW
ActivityClass com.google.android.maps.MapsActivity
ActivityPackage com.google.android.apps.maps
The App's Behavior
Here are the blocks for the Android, Where's My Car app (the yellow annotations will also appear when you load this app into App Inventor):
Page 70
Let's examine the four different event-handlers of the app, starting in the top-left and working around in counter-clockwise order.
LocationSensor1.LocationChanged : This event occurs when the phone's location sensor first gets a reading, or when the phone is moved to produce a new reading. The event-handler just places the readings--latitude, longitude, and current (street) address-- into the corresponding "Current" labels so that they appear on the phone. The RememberButton is also enabled in this event-handler. Its enabled setting should be unchecked in the Component Designer because there is nothing for the user to remember until the sensor gets a reading. RememberButton.Click : When the user clicks the RememberButton , the location sensor's current readings are put into the "remember" labels and stored to the database as well. The DirectionsButton is enabled as it now makes sense for the user click on it to see a map (though it will make more sense once the user changes location). DirectionsButton.Click : When the user clicks the DirectionsButton , the event-handler builds a URL for a map and calls ActivityStarter to launch the Maps application and load the map. join is used to build the URL to send to the Maps application. The resulting URL consists of the Maps domain along with two crucial parameters, saddr and daddr , which specify the start and destination for the directions. For this app, the saddr is set to the latitude and longitude of the current location, and the daddr is set to the latitude and longitude of the location that was "remembered" (the location of your car!). Screen1.Initialize : This event is always triggered when an app opens. To understand it, you have to envision the user recording the location of the car, then closing the app, then later re-opening the app. When the app re-opens, the user expects that the location remembered earlier should appear on the phone. To facilitate this, the event-handler queries the database ( call TinyDB.GetValue ). If there is indeed a remembered address stored in the
Page 71
database-- the length of the stored address is greater than zero--the remembered latitude, longitude, and street addres are placed in the corresponding labels. Variations
• Create "Android, Where is Everyone?", an app that lets a group of people track each other's whereabouts. Whether your hiking or at the park, this app could help save time and even lives.
• Create a "breadcrumb" app that tracks your (phone's) whereabouts by recording each location change. One interesting refinement would be to only record a new "breadcrumb" if the location has changed by a certain amount. Review
Here are some of the ideas covered in this tutorial:
• The LocationSensor component can report the phone's latitude, longitude, and current street address. Its LocationChanged event is triggered when sensor gets its first reading and when the reading changes (the phone has moved).
• The ActivityStarter component can launch any app including Google Maps. For Maps, you set the DataUri property to the URL of the map you want to display. If you want to show directions, the URL will be of the form: http://maps.google.com/maps/?saddr=0.1,0.1&daddr=0.2,0.2, where the numbers are GPS coordinates.
• join is used to piece together (concatenate) separate text items into a single text object. It allows you to concatenate dynamic data with static text. With the Maps URL, the GPS coordinates are the dynamic data.
• TinyDB allows you to store data persistently in the phone's database. Whereas the data in a variable or property is lost when an app closes, the data you store in the database can be loaded into your app each time it is opened.
Page 72
25 - Map Locations Map It: Displaying Locations on a Google Map This tutorial shows how you can develop an app that allows you to record list of addresses and view the address on the Google Maps. It will also show you how view your current location on the Google Map. This tutorial assumes you have completed the basic tutorials of App Inventor. Viewing Current Location On the Map
This tutorial introduces:
• List manipulation – creating lists, appending items to lists
• ListPicker – adding items to lists, saving list data • LocationSensor – detecting current location for
displaying on Google Maps • ActivityStarter – used to start-up Google Maps for
current or predefined address • Notifier – displaying messages • TinyDB – saving data into a persistent database • Misc. – text manipulation, basic validation
We will be working toward the design shown in figure blow:
The figure below shows how the components are arranged in the design editor. It also shows you the non-visible components (e.g. TinyDb, ActivityStarter, LocationSensor, Notifier) that are used in the app.
Page 73
Blocks
We define 2 global variables.
• tagAddress – a variable that is a constant and will be used, as a tag, for storing and retrieving data from our database.
• listLocations – a variable that can be used to store and manipulate list of addresses. We now create a procedure that can be invoked when the app is started (initialized). The procedure sets up the initial state of some of the
Page 74
components. Some of these settings could have been done from the design editor, but for demo purpose and clarification, we are using a procedure. In the procedure, we also check our database to find out if there are any stored addresses. If no data, then we just use an empty list.
Adding a New Addresses
We use AddLocationButton to add a new address, CancelButton to cancel the process of adding, and LocationHelpButton to display what type of addresses can be entered. The blocks to make these actions work are here:
When AddLocationButton is clicked, we make our address data entry visible (using screen arrangement), allowing user to enter address. If user clicks on Cancel, we make the arrangement hidden again. Using this approach, we keep the screen simple and avoid the clutter. We also provide the SubmitButton to allow the user to indicate that they want to store data.
When the user clicks on SubmitButton, we perform basic validation to ensure data has been submitted. If validation does not pass, we display an error message. Otherwise, we invoke a procedure that appends the new address to our list. We also store the updated list into our database. Once address is added, we hide our arrangement again. The blocks below show how this logic is done:
Page 75
Selecting an Addresses
When the user clicks on ListPicker1 ‘Select Location’ and selects an address, this action calls the blocks below:
This displays the address in the device and allow the user to tap on ViewOnMapButton to see the blocks selected address on the Google Map — see the figure below:
When ViewOnMapButton is clicked, we validate to ensure that an address already has been selected. If not, an error message is displayed. Otherwise, we use blocks below to show address:
Page 76
The above blocks will open the map and the output will be like image below:
Viewing Current Location On the Map
We have dropped in a button, MyLocationButton ‘My location On the Map’ that can be clicked to view one's current location. It will use
Page 77
26 - Friend Locator In this activity you design your own app.
• Build an app that stores the GPS location of you and your group of friends in an online database. Update every 5 minutes.
• Your app reads the location of other friends who use the app.
• An icon appears on a Google Maps screen to show their location.
Use the techniques in assignments 21 (chat app), 24 (Where’s my car?) and 25 (Map Locations) to complete this assignment.
Online database (FusionTable) to
store GPS coordinates, name
and time. Report your GPS location Report your GPS
location
Read GPS locations for people in your
group.
Read GPS locations for people in your group.