In this lesson, you will:
- Learn how to include images and sounds in AppInventor
- Learn about data and different data types
- Learn how to use variables
- Learn to organize data into lists
- Make a magic 8 ball app that can answer two types of questions
Step 0: Learn about Data Types
At some point in your life, you’ve probably heard the word data. Data can mean a lot of things, but in computer science, data is the information that your app needs in order to work. To better understand this, let’s think about some apps and some of the information that they need in order to work.
This social app can message and call contacts. The data it needs is:
- Your username
- Your friends’ usernames
- Messages you want to send
- The time
- Your location
In this game app you shoot birds at pigs to defeat them. The data it needs is:
- Your score
- How many points each object is worth
- What levels you’ve completed
- How many birds you get in each level
The programmer needs to set up ways for the app to get all the information it needs. Remember, computers can’t do anything on their own without instructions. Here are a few ways that apps in App Inventor can get data to use:
- The programmer put the information in:
- In your slideshow app, you (the programmer) entered in your favorite images.
- In Angry Birds, the programmer entered in how many birds the player gets on each level.
- The user enters the information:
- In WhatsApp, the user needs to tell the app what she wants to send and who she wants to send it to.
- The app connects to another place to get information:
- WhatsApp connects to your phone to get the time so it knows what time you sent a message.
Sometimes an app will save information the user put in. For example, WhatsApp saves message history which allows you to see the last message you sent to a friend. To do this in, the programmer uses a database, which you will learn about in another lesson. You will also learn more about how to connect to other places to get information later.
If you were using an app that helps you find the nearest grocery store, what data do you think the app needs to have?
As you saw in the section above, data can be a lot of things! To make it easier for computers to understand what to do with the data they are given, data is put into categories. This is known as a data type. Programming languages revolve around three major data types: numbers, strings, and booleans. App Inventor also lets you use more complex data types such as colors and images. You don’t need to do anything with data types you’ll learn about in this section but it will be good to keep them in mind as you code more.
A number data type is just what you think it is! In App Inventor, you can use numbers by going to Math in blocks.
You will use Math blocks whenever you need to use numbers. Here are some examples of when you might use a number data type in an app:
- Calculating a player’s score in a game
- Counting how many times a user has tried to log in
- Counting how many times you want your app to do something
- Checking to see if your user is a certain age
Optional: To learn more about all the things you can do with math blocks check out MIT’s website: Math blocks
A string data type is text. In App Inventor, you can create a string by going to Text in Blocks. Here are some of the text blocks you can use.
You should use a string anytime you want to add a text field to your code. Here are some examples of when you might use a string data type in an app:
- Allowing the the user to enter a password or username
- Having the app speak words to the user
- Showing a message or an alert to the user
- Programming the app to open a new screen by giving it the screen name
Optional: Before moving on check out MIT’s website to see all the things you can do with text: Text blocks
A boolean can be one of two values: true or false. True basically means “yes” and false basically means “no”. To get a boolean, go to Logic in blocks and grab one of these blocks:
For now, there is not much to do with booleans other than keep them in mind. Booleans and logic will be covered in more detail in another lesson.
variable. A variable is a name for a piece of data that can change in value. An easy way to remember this is that a variable can vary, or change in value. There’s lots of information that is important to you every day that changes value. Here are some examples:
- Your age
- Your height
- Your location
- Today’s date
To better understand variables and how to use them in App Inventor, let’s walk through an example. Imagine you are creating a game where the user can earn and lose points. You want to have a score for the player to see in a text box. At the start of the game, the player has zero points so you added a block like this to the game.
The player sees zero in the textbox that contains her score. However, the player’s score will change as she plays the game. Each time she gains or loses points you have to update the text box. When she gets more points, you add a block like this.
That works, but now what about the next time the player earns 10 points? You’ll have to update the text again to say 20. Then what if the player loses points? You will have to change her score to 15. What if she gains points again? This can get confusing really fast.
In scenarios like this, you can create a variable to keep track of the player’s score. You can create a variable called score that always has the value of the player’s current score. As she plays the game, you can add and subtract points from score and you won’t need to worry about keeping track of what the her current score actually is. Here’s how it would work in App Inventor. First you would grab this block from the variables section.
This block tells the app that there will be a variable and asks you to give the variable a name and a value. Here’s what the block would look like for a game where the player’s score started at zero.
With this block, you are telling the app that there will be a piece of data called score and that it will change value as the game is played. Every time the app starts up, it is going to create a variable called score and set it zero. Now you can do what’s called “set” and “get” your score variable. “Get” will allow you to see what the value of the score is. Here’s how you would tell your app to display the score in a textbox.
“Set” allows you assign a new value for your user’s score. Every time the player earns points you can tell the app to do this.
This tells your app to change the value of the score to whatever it is now and add ten to it. If the current score is zero, the new score would be 10. If the current score is 25, the new score would be 35. Now you don’t have to worry about reassigning the score every time your player gains or loses points. The app will just take the current score and add 10 to it.
It is okay if you are still confused about variables! They are really hard to understand and the best way to understand them is by using them. You will use them today and again and again as you become a great coder!.
The final Magic 8-Ball App will deliver a prediction from a list that you have designed – and it will be able to answer both Number questions and Yes/No questions. To get started, first we’ll make our main screen, and program our app to play a sound when the user shakes the phone.
- Open a new tab or window and go to ai2.appinventor.mit.edu.
- If you have already made an app, 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).
- Download one image and one sound file from below to be used in your app. Right click (control-click) on the link of the image or sound, then choose “Download” or “Save As”. Save the media files to a convenient location that you will remember.
- On the left column of the Designer, the User Interface palette should be open. If it is not, click to open it. Drag an Image component over to the Viewer.
- Set the image to an 8-ball image:
Click on your newly added image to see its properties in the Properties pane on the right. Under “Picture” click on the word “None…” and a small selection window will pop up. Click the “Upload File” button and browser 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.
- From the Media palette, drag over a Sound component onto the Viewer pane. The Sound component plays sound files. Notice that since the sound component will not be a visible part of the app, it appears at the bottom of the Viewer pane, as a “Non-visible component.”
- 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. 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.
- We need one more piece to make our app work: a sensor that can tell when the phone is moving, so our user can shake the phone to get their predictions. From the Sensors palette, drag an AccelerometerSensor component onto the Viewer. Notice that it will show up below the screen, like the sound, because it’s another non-visible component.
- 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 user shakes the phone. This is actually very simple in App Inventor, because the “code” for the program only consists of two blocks!
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 AccelerometerSensor1 drawer. Drag the “when AccelerometerSensor1.shaking” block into the work area.
- From the blocks palette, click on the Sound1 drawer, drag the “Sound1.Play” block into the work area and insert it into the “when AccelerometerSensor1.Shaking” block. 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.
Go ahead and test your app! If something’s amiss, now’s your chance to break out your problem solving skills and figure out what’s going wrong.
Step 2: Get a Prediction
Go back to the Designer window in your browser and add some new things to your app.
- 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 Inventor will know that you want to line them up vertically (one on top of the other).
- 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)
- 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.
Now for the fun part! You’re going to make a list of predictions and program the app to pick one item from the list and display it inside Label2 when the user shakes the phone. The app will also still play the sound that you programmed in Part One. Here’s how to do it…
- 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 AccelerometerSensor1.Shaking” block automatically gets bigger to accommodate the new block.
- 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.
- 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.
- 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.
- 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.
- 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, which means it can be expanded or shrunk by clicking the blue button in the upper left corner.
- 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.
Step 3: Add a Number mode
Your app already works like a classic magic 8 ball, giving predictions for Yes/No questions. But since it’s a high tech magic 8 ball, it should have some high tech functionality! Let’s change our app so that the user can choose if they want to ask a Yes/No question or a number question, like “What’s my lucky number?” and get an answer!
- Go back to the Designer tab to add some more pieces to your app.
- From the User Interface palette, drag a Spinner component to the top of the Viewer screen. A Spinner is a component that lets the user choose from a list of options.
- In the Spinner’s properties (on the right), write “Choose a mode” in the “Prompt” property. In the ElementsFromString property, write “Yes/No, Number”. This sets the prompt the user will see when selecting options and the options available for the user to choose from.
Flip back to the Blocks tab.
- Create new global variable named “predictions” by pulling in the “initialize global name to” block from the Variables drawer. Rename the “name” to “predictions.” Drag your list of predictions over to your new variable. Your new code should look like this:
- From the Spinner1 drawer, get the “when Spinner1.AfterSelecting” block. Inside the AfterSelecting block, add two if/then blocks from the Control drawer.
- In the first if block, we want to set up a check to see if the user has chosen the Yes/No mode, and then set our predictions to be the Yes/No answers if they have. To do this, add the blocks below until your code matches:
- In the second if block, we want to set up a check to see if the user has chosen the Number mode, and then set our predictions to be the Number answers if they have. To do this, add the blocks below until your code matches:
- So far, the code we’ve built sets our predictions variable to have the right predictions stored in it when the user switches mode. Now, we need to change our code that prints the prediction label to use our predictions variable!
Change your “when AccelerometerSensor1.Shaking” block to set the Label2 text based on the predictions variable:
- That’s it! Test your app to see if it works! If it doesn’t, go back and see if you can hunt down the problem. When it does, time to peer deep into your future!
Congratulations for meeting the challenges this app presented and persevering through them!
This app is yours — so feel free to make it whatever you want it to be! Here are a few ideas for expanding the app to get you started:
- Are there other types of questions/answers you want to provide?
- What if you played different types of sounds based on good/bad answers?
- Could you build a similar future-predicting game as an app?
This tutorial is a melding of the following resources: