Lists and loops - Hello App Inventor!: Android programming for kids and the rest of us (2015)

Hello App Inventor!: Android programming for kids and the rest of us (2015)

Chapter 6. Lists and loops

Chapter 5 showed you how apps can remember things. In this chapter, we’ll build on that idea to make apps that remember and use collections of things using a special type of variable: the list. You’ll also find out how to make apps that repeat an action several times using loops.

Lists are all around you—especially in the technology you use. If you think about it, we bet you can think of at least five lists you’ve used today. Here are some examples:

· Choosing a person to send a message to from your contacts list

· Choosing a ring tone from a list of sound files

· Reading a list of updates from your friends on social media

· Choosing a TV program to record from a TV planner list

· Selecting a way to pay from a list of options when internet shopping

These are all visible lists, where you choose one or more items. Computers also use invisible lists like these to track activities:

· Your internet history —A list of which pages you’ve visited.

· Actions you’ve taken in a program —They’re saved in a list so they can be undone using the Undo button.

· Game saves —When you quit a game, your PC or console saves a list of parameters like your score, your current location or level, which objectives you’ve achieved, and so on.

In the first part of this chapter, you’ll learn how to create visible lists to help users choose items. Then we’ll move on to invisible lists, which are a flexible way to store lots of data items without having to create a bunch of separate variables.

Readymade lists

Your phone already contains lists of useful information, and App Inventor can access and use a few of them. You access these lists using list pickers.

Let’s do a quick experiment to see how two of the readymade pickers work:

· ImagePicker opens the phone’s gallery so you can pick an image. Click an image, and a copy is saved on your SD card. The pathname is automatically stored in the ImagePicker Selection property.

· PhoneNumberPicker lets you pick one of your phone contacts. App Inventor can access and use the contact’s name, phone number, and picture.

For this experiment, you’ll need a real phone (not the emulator) that already has some images saved, and some phone contacts to choose from—if you don’t have any, add some before you begin. Because this example isn’t a full app and has just a few simple components, we’ll go ahead and tell you how to build it without presenting the usual app table. You’ll put the two pickers on a screen, and whenever the user clicks one to make a choice, you’ll show them the gallery picture or contact picture they selected, along with some additional information.

Start a new project called ListExperiments, and lay out the screen as follows:

These pickers will work (to display the list) even before you code any blocks—try clicking the list-picker buttons. You can choose a contact (if you click the top button) or an image from the gallery (bottom button). So far, App Inventor isn’t doing anything with that information. But each time you click a picker button and make a choice, you’re generating an AfterPicking event. It’s called AfterPicking because it fires only after you’ve chosen an item from the list. There’s also a BeforePicking event that fires when you first click the list-picker button. You’ll use theAfterPicking event to trigger your blocks (you saw something similar with the AfterTextInput Notifier event in chapter 5’s Flattery app).

For the PhoneNumberPicker, you’ll grab the contact’s name and phone number and display them as a joined text string with “Tel:” in the middle, like this: “Martin Cooper Tel:555-12345678”. You’ll also change Image1 to a picture of the contact. Here are the blocks:

The ImagePicker saves a temporary copy of the image you select and provides you with the path and filename. You’ll use these to display the file information and picture like so:

Here you can see the results of the two pickers.

Of course, now that you’ve grabbed this information, you could do something much more interesting with it. For example, you could send an automatic text message to the contact or dial their number using the PhoneCall or Texting component (in the Social group of the Palette). Here are a couple other ideas:

· ContactPicker —Lets you pick one of your contacts. App Inventor can access and use their name, email address, and picture.

· EmailPicker —Like the ContactPicker, but lets you type the beginning of a name rather than choose from a list of people.

Later in this chapter, you’ll use the in-built list pickers to select a new background for the Graffiti app you made way back in chapter 3. You’ll also use the ContactPicker and Texting to send encrypted messages. Before that, let’s take a look at how you can make your own list picker from scratch.

Making your own list picker

You can use a list picker whenever you want to give the user a choice of options: for example, choosing a drawing color from a palette of options or even something simple like whether they’re male or female. This is a lot more efficient than creating lots of separate buttons or check boxes. List pickers are expandable, so you can create a long, scrollable list with more options than can fit on a single screen. But list pickers only let you pick a single option at a time—just like a multiple-choice quiz.

At right are some keywords we’ll use when talking about list pickers.

We hope it’s obvious why you need elements (so the list has something in it) and a selection (so you know what was chosen), but why do you need a selection index? For some simple lists like choosing Male or Female, the position of each element doesn’t matter. But there are lots of times when it’s useful:

· When you’re sorting lists into order. For example, it’s important to know where to put each name in a telephone directory.

· When you’re searching or processing a list of elements. It’s useful to know which position you’re up to and whether you’ve reached the last element, so you know it’s time to stop the search.

· When you’re working with parallel lists. Sometimes you’ll have several lists that all correspond to one person or thing. For example, if you know the First Name list is in the same order as the Eye Color list, you can work out that Ellie (in Search Index position 6) has blue eyes (because the eye color found at Search Index position 6 is Blue).

Ready for ice cream?

Let’s experiment with a custom list picker by making a simple list of ice cream flavors. When the user picks one, you’ll output a message that says “Out of these flavors [list of the flavors] you chose [chosen flavor] which was at position [number] in the list”. The app works as follows:

Again, this is a really simple experiment, so no app table for this one. Jump right in and set up your screen like this:

You can type in your own list of flavors, or use ours: vanilla, strawberry, mint choc chip, chocolate, toffee, raspberry ripple, lemon, melon, kiwi, blueberry, apple, bubblegum, rocky road, cherry, banana, mango, passion fruit, none (although we’ve never met anyone who doesn’t like ice cream).

The block follows exactly the same format as the PhoneNumberPicker:

Have you noticed that you’ve typed \n several times in these text blocks? Run the app on your phone, choose an ice cream flavor, and see if you can work out what \n does. What happens if you remove \n from the text blocks?

Get yourself some ice cream if you worked out that typing \n in a text string inserts a new line at that point in the text (just like pressing Enter). This splits up the text neatly—each sentence starts its own line. If you want to add a blank line, you just add \n twice. Of course, you could have created three different labels in the Designer screen and then changed each of their Text properties to one of the sentences, but using \n is much simpler and keeps everything contained in a single label.

At the beginning of the chapter, we talked about visible and invisible lists. Everything you’ve done so far has been visible—now let’s turn our attention to invisible lists that you program in blocks.

Excuse Generator app

PURPOSE OF THIS APP

This app generates a unique excuse if you forget to do your homework. It uses 4 hidden lists, each with 10 elements. There are 10,000 possible combinations of excuses. Some are sensible—but most are very silly!

APP RATING

ASSETS YOU’LL NEED

keep-calm-and-make-excuses.png.

1. Setting up the screen

Here’s the screen layout. Every time you click the button, a new excuse will appear at the bottom of the screen:

2. Coding the blocks: a slot-machine algorithm

The rules (or steps) that programmers think about and then turn into code are called an algorithm. In this case, you’re going to use an algorithm that works like a slot machine. On a slot machine, symbols spin around on three wheels, and if all three match, you get a payout. In your algorithm, you’ll have four wheels (lists); and instead of symbols, you’ll write parts of a sentence that make up an excuse. As long as you write the sentence parts so that they follow the same structure and fit together when you read them, you can mix and match any combination of the four lists.

The sentence structure must always be the same. It starts with an apology, followed by a person who did some kind of action at a location, like so:

Sentence part list:

Apology

Person

Action

Location

Example:

I’m sorry,

my sister

set fire to my homework

at the swimming pool.

Example:

A thousand apologies,

my dog

ate my homework

in the Principal’s office.

If you write 10 elements for each list (Apology, Person, Action, and Location), then the number of possible combinations is 10 x 10 x 10 x 10 = 10,000 sentences.

Learning Point: Algorithms

An algorithm is a precise set of instructions that solve a problem. Algorithms exist outside of the world of computer programs. You’ll find them everywhere—in math, science, engineering, English, art, and even in your day-to-day life. Here are some examples of algorithms you’ve probably come across:

· A recipe to bake a cake

· Working out the area of a shape

· Folding a paper model like a bird or airplane

· Following the rules of a game

These algorithms might appear in lots of different ways: a recipe is usually written down; to work out a math problem, you might have written instructions or an example to follow; to fold a paper model, you’ll probably follow a diagram or copy someone else; and to learn a game, you may listen to instructions. Computer scientists do all these things, too, when they want to figure out and share an algorithm—they may imagine it and talk it through, write down the steps, or draw a diagram like a flowchart.

One thing that is often very important in computer algorithms is that programmers want to build an efficient algorithm. This is because computers can do millions of operations every second, so even a small change in the time to complete some instructions can make a big difference in how quickly the overall program or app runs. Think about it like this: saving 5 seconds when you bake a cake is no big deal; but if you make a million cakes, the overall saving is about 58 days!

3. Setting up the lists

First set up the Apology list with 10 elements. This is almost the same as setting up any other variable. As with any other variable, you start with an initialize global block from the Variables group of the blocks. Change the name of the variable to something sensible: Apology. Now, instead of a number or text string, you use a make a list block from the Lists group. Your block will look like this.

In some apps, you may not know what the list will contain in the future—for example, if you’re setting up lists to store users’ contacts or high scores, you can only fill in the list elements once the user is running the app. In that case, you would stop here, leave this variable definition block as it is (with empty sockets after make a list), and move on to programming the rest of the app. But in this app, you’re going to build the sentence elements right into the program—so you can add the 10 apologies to the list as text blocks, like so:

Now add the other three lists to the blocks. The fastest way is to select, copy, and paste the previous block three times; change the variable names (to Person, Action, and Location); and then change the text blocks. Feel free to change these or add additional text blocks to any of the lists. Here’s the way ours looked when we finished:

4. Building the sentence

You’ve finished all the hard work. When ExcuseButton is clicked, you need to choose a random element from each of the four lists. In some programming languages, you do this by picking a random number and then choosing the element at that position (or index) in the list. App Inventor makes things even simpler using a block called pick a random item. You tell it which list to use, and it randomly selects an item from that list. If you do that for the four lists and display the elements together in ExcuseLabel, your blocks look like this:

Try it—each time the button is clicked, you should see 1 of 10,000 possible excuses. You could use this as the basis for a game with friends where each player clicks the button and then has to explain what happened to their homework, starting with that sentence. The more plausible, creative, and imaginative they are, the more points you should give them.

You could enhance the app by having it play some sad music as you give your excuse—maybe it will sway your teachers. You could also have the text-to-speech component speak the excuse (we guarantee it will sound more plausible than you—because it won’t snicker or laugh).

Learning Point: Lists can contain (almost) anything

In this example, your lists just contain text strings. But we wouldn’t want you to think that lists have to be text. App Inventor lists are very flexible and can contain any variable types, including text strings, numbers, boolean (True/False), and color variable types.

You can even mix and match different types of variables in the same list.

In the next app, you’ll combine everything you’ve learned about lists to improve the Graffiti Artist app you first made in chapter 3.

Graffiti Artist 2: the spray-paint returns!

PURPOSE OF THIS APP

Now that you know how to create list pickers, you can go back and improve the chapter 3 Graffiti Artist app by making the following changes:

· Users can select a background image from their gallery instead of the wall.

· Users can choose the size of the lines and dots they draw.

· Users can select from a wider range of colors.

· The user interface is improved by using icon buttons at the top of the screen.

APP RATING

Assets you’ll need

Icon images: clear_icon.png, color_icon.png, size_icon.png, and background_img_icon.png.

1. Updating the screen layout

Load a copy of your Graffiti Artist app, and use Save As to save the project as GraffitiArtist2. You’ll start by creating a new toolbar in the existing ColorBar horizontal arrangement. You’ll do these things:

· Replace the five color-choice buttons with a single list-picker button.

· Move the wipe button (from the bottom of the screen) up into your new toolbar.

· Add new buttons to pick a background and change the line size.

Begin by deleting the five color buttons (ignore any warnings that appear—click OK). Then move the “Clean it off!” WipeButton from the bottom to the top of the screen.

Now add three new buttons, and update WipeButton as follows:

BackgroundPicker is an image picker just like you used earlier in this chapter. It will take the user to their phone Gallery, and you’ll code some blocks that make the image they choose appear on the WallCanvas.

SizePicker is a regular list picker that lets the user choose the size of the lines and dots they draw. A good range of sizes to give them is 1, 3, 5, 7, 9 (pixels)—enter these into the Elements property of SizePicker. You can experiment with some other choices if you like by adding to or changing this list of elements.

ColorPicker gives the user a range of color names to choose from—this means you can offer many more choices than the five they had in the old version of Graffiti Artist. Here’s the full list of colors you need to type into the Elements property of ColorPicker: Black, Blue, Cyan, Dark Gray, Gray, Green, Light Gray, Magenta, Orange, Pink, Red, White, and Yellow.

WipeButton works exactly as before—you don’t need to change anything other than its position and icon.

2. Coding the blocks: choosing a background image

You’re using exactly the same sort of code here that you saw in the ImagePicker experiment earlier in this chapter. The only change is that you’re setting the WallCanvas BackgroundImage property rather than changing an Image object’s Picture property.

3. Changing the line and dot sizes

You can set the line width of any lines drawn by using the canvas LineWidth property. So the first job is to set this property to whatever the user chose in the SizePicker. Here are the blocks:

You’ve finished the line size, but changing the size of the dots (which appear when the user taps the screen) is trickier. If you look at your original Graffiti Artist blocks, you’ll see that you drew a circle for each dot and set the circle radius to 5 pixels. You need to change this so that instead of directly coding a value (5) into the blocks, you use a variable instead. You’ll store the user’s SizePicker choice in the variable; and whenever they dot the screen, you’ll set the circle’s radius to the variable’s value. To do this, define a global variable called DotRadius with an initial value of 5, and then replace the number 5 block with the DotRadius variable block. Here are the before and after:

Now you have a way to change the line size and the dot size—all that’s left is to have the SizePicker’s AfterPicking event trigger the changes. Here are the AfterPicking event blocks:

Note that in this example we created just one list picker to set both the line and dot size, because they both use the same units (pixels). But you could have separate list-picker buttons and events—one for dots and one for lines. That would mean the user could set each property independently: if they clicked the line-size list picker and changed lines from fat to thin, their dot size wouldn’t change until they clicked its list picker.

4. Offering a rainbow of colors

In the original Graffiti Artist, you gave a choice of colors by using five separate buttons that set the WallCanvas PaintColor property to five different premade color blocks like this one:

In Graffiti Artist 2, you need an easy way to translate text color descriptions in the ColorPicker list into premade color blocks. If the user clicks the ColorPicker button and chooses Red, then you want to set WallCanvas.PaintColor to a red color block. You might think, “Why not plug color blocks into the ColorPicker list in the first place? Why type the names of all those colors?” If you try it, you’ll see that the premade color blocks in App Inventor are just a bunch of numbers. Asking a user to choose between -65536 or -16776961 is a lot less helpful than saying Red or Blue. So the task becomes how to link the text Blue with the App Inventor blue color block (-16776961). The easiest way to do this is to set up a new list of color blocks that matches the order of the elements in the ColorPicker. Then you can use the SelectionIndex of a selected color name to look up the color value, like so:

When the user picks a color from the ColorPicker (left), you can use its index position to set the same WallCanvas.PaintColor from the matching ColorBlocks list (right). Here are the blocks that are triggered when the user chooses a color from the ColorPicker:

An example will help explain this:

1. The user clicks the ColorPicker icon and chooses Blue, which is second in the list of colors (index=2).

2. The AfterPicker event is triggered.

3. WallCanvas.PaintColor is set to whichever color block is at position 2 in the ColorBlocks list.

Which is ... Blue (phew!). We hope you can see why being able to use the index position of an item in a list is useful—in this case you have two lists, but because they’re paired up (in the same order), you can translate from one to the other. The Graffiti Artist 2 app is complete, and at the end of this chapter we give you some suggestions for how you could take it even further.

We’ve covered a lot of ground so far in this chapter. We’re about halfway through, so this is a good point to take a break if you need one. In the next section we’ll look at how apps can repeat actions using loops, and how this can help you make and use lists efficiently.

Loop the loop

Computers (including smartphones) are really fast at carrying out instructions; they can perform literally millions of instructions in a second. This speed becomes most obvious and useful when we ask computers to repeat an action many times over—this is called a loop.

Loops are programmable blocks (rather than components), so you’ll find them in the Blocks Editor under Control. There are three types of loop, as we’ll show you next.

for range ... do ...

This block runs a set of blocks (in the do section) for a fixed number of times (the range).

Example

You set the range by plugging in a start value, an end value, and a step value. The start and end values are straightforward—they say what number you want to start at and when the loop should stop. The step value is how quickly and in what direction you want to count. Usually you want to count up in single steps, so step will be 1. But you can change step to a larger value; for example, if you wanted to count up in fives, then you’d set step to 5. You can also count down instead of up: if start = 10, end = 0, and step = -1, then the loop will start at 10 and count down until it reaches 0. The i in the block is a counter variable that keeps track of how many times the app has gone around the loop. You don’t always need to know this information, but sometimes it’s very useful—as in the example we just showed you, where we output the value of i into a notifier to make a simple counting app (also see the next app for a further example).

You might wonder why the variable is called i. It’s a habit programmers have developed because it’s the first letter of the word index. Just like any variable, you can rename it something meaningful like LoopCounter by clicking the i and typing a new name. It’s a local (rather than global) variable, which means you can only use it within the do part of the loop—other blocks can’t “see” it.

When you might choose it

Use a for range ... do ... loop whenever you know in advance how many times you need to execute a loop. It’s safer than a while ... do ... loop (explained in a minute) because you can be sure it will end after a specific number of times.

for each ... in list ... do ...

This block runs a set of blocks (in the do section) for every item in a specified list.

Example

The local variable i refers to the value of an item in the list. At first the value of i is the same as the value of the first item in the list. Once the do part of the loop has finished, the value of i is set to the next item in the list, and so on, until the last item of the list has been processed.

When you might choose it

Use a for each ... in list ... do ... loop whenever you want to work through a whole list of items. It’s safer than a while ... do ... loop (discussed next) because you can be sure it will end once it reaches the end of the list.

while (test) do ...

This loop tests if something is true (just like an If block). If the test is true, all the blocks in the do section are run, and then the whole process starts again. The loop continues until the test is false. At that point the loop stops, and any blocks after the loop are run.

Example

When you might choose it

Use a while (test) do ... loop if you can’t use one of the other loops—for example, because you don’t know how many times the loop needs to run. You could use it to process a list if you didn’t want to search through every element (for each) but instead wanted to stop when a particular element is found.

Learning Point: Infinite loops and loops that take too long!

INFINITE LOOPS

We suggested that the two for ... type loops might be better than the while loop because you can be sure they’ll stop after a certain number of loops. This is important because you could accidentally make a while loop that never ends—an infinite loop. The only way to stop this kind of loop is to quit the app. As an example, if you change the DiceThrow blocks in the earlier while (test) do ... example to choose a random integer from 1 to 5, then you can never throw a 6—the loop would run forever!

LONG LOOPS

Sometimes loops can take a long time to finish, and the Android operating system worries that your app has crashed. At this point, it will ask the user if they want to wait a little longer or force the app to close. At the time of writing, you can’t stop this from happening in App Inventor—so if a loop takes a long time when you test the app, make sure you use a pop-up notification or message onscreen to warn the user that they will need to click Wait.

Multiplication Table Generator app

PURPOSE OF THIS APP

This app generates a multiplication table. This is a good way to find out how a for range loop works, because you know how many times you want the loop to run: 12 times.

APP RATING

Assets you’ll need

None.

The user will type in a number. When they click the Generate Table button, the app will multiply their chosen number by 1, then 2, then 3, and so on, until it reaches 12. The output will look like what is shown above.

Notice that the first number (or factor) in each calculation starts at 1 and increases by 1 each time, all the way up to 12. The second factor is what the user typed in the text box: in this case, 5.

Multiplication Table Generator

Screen1 properties:

Title: Multiplication Table Generator

Components

What do I rename it?

What does it do?

What properties do I set?

Label

InstructionLabel

Tells the user what to do.

Text: “Which Multiplication Table would you like to generate?”

TextBox Palette group: User Interface

FactorTextBox

Lets the user input a number.

NumbersOnly: Yes (selected)

Button

GenerateButton

Produces the multiplication table.

Text: “Generate Table”

Label

ResultLabel

The multiplication table is displayed in this label.

Text: None

1. Setting up the screen

Here’s the screen layout:

2. Coding the blocks: defining the programming problems

You need to solve two programming “problems” for this app. The first problem is displaying a single calculation so that it looks something like “1 x 5 = 5”. The second problem is repeating this process 12 times while changing the first number—so the next calculation says “2 x 5 = 10”, then “3 x 5 = 15”, and so on.

Without a loop, you would need to program 12 sets of blocks—one for each line. Even worse, what if the user wanted more flexibility—say, multiplication tables that go beyond 12 for the first factor? There are lots of ways to solve these problems. Stop reading now, and have a go at writing some step-by-step instructions before you read our suggested solution.

You may have a different solution than the one we present—it may be shorter or more efficient, or it may be longer and less efficient. Making these judgment calls is one of the ways in which programming is a creative (some would say artistic) process as well as a logical one. Try our solution app, and then try turning your ideas into an app, and see which works best.

Here’s the step-by-step for the app:

1. Set up a variable for the user’s multiplication factor. Call it UserFactor.

2. When the user clicks the Generate Table button ...

1. Set the value of UserFactor to whatever number they typed in the text box.

2. Clear the ResultLabel (in case they already have an old table displayed there).

3. Set up a loop that counts from 1 to 12. Keep track of how many times the loop has run using a local variable called LoopCounter.

4. For each loop, add a line to the current ResultLabel with the following text joined together:

o The value of LoopCounter

o The letter X (to represent multiplying)

o The value of UserFactor

o The character =

o The result of LoopCounter * UserFactor (* means “multiply” when using a computer)

o A new line \n

5. Repeat step d until you reach the 12th line.

We’ve chosen to loop 12 times because children commonly learn multiplication tables from 1–12. But you can experiment with higher values—why not try a 100X table? Also see “Taking it further” at the end of this chapter for a challenge to give the user control of this value.

Here are the finished blocks. One loop does all 12 calculations:

When you run the app, you may notice a slight delay between clicking the button and seeing the result (particularly if you try increasing the end range value in the loop). This is because App Inventor does one thing at a time, so it runs through the loop, prepares the label, and updates the display only once the loop has finished.

3. Looping the loop: nested loops

If you put one loop inside another, the inner loop will run as many times as the outer loop tells it to. This is a little like multiplying loops together. Putting one loop inside another is called nesting.

What’s the point of nesting? Here’s a simple example of the power of putting one loop inside another. At the moment, you have an app that can use a single loop to generate 12 calculations for a value the user types in. What if instead of just one multiplication table, you wanted to generate allthe multiplication tables from 1 up to the value the user chose? In other words, if the user typed 3, they would get three multiplication tables:

1X table

2X table

3X table

1 X 1 = 1

1 X 2 = 2

1 X 3 = 3

2 X 1 = 2

2 X 2 = 4

2 X 3 = 6

3 X 1 = 3

3 X 2 = 6

3 X 3 = 9

... (up to)

... (up to)

... (up to)

12 X 1 = 12

12 X 2 = 24

12 X 3 = 36

1. This extra power requires very little modification to the code: Save As your project with the name AllMultiplicationTablesUpTo.

2. Detach (but don’t delete) the for range loop block you created previously (you’re going to reuse it in a moment).

3. Add a new for range loop block that counts from 1 to UserFactor (this is your new outer loop). Call its index Factor1.

4. In the new loop, add a couple of blank lines to ResultLabel (this splits the tables so you can tell where each begins).

5. In the new loop, add the old for range block that you detached earlier (this is your new inner loop).

6. Change the multiplication calculation from LoopCounter*UserFactor to LoopCounter*Factor1.

7. The final result will look like this:

You can try this out with some large numbers—it will take a little while, but it’s still much faster than a human could calculate all those multiplication tables.

Now that you know about lists and loops, this chapter’s final app brings them together in a top-secret app we call ...

Secret SMS Sender app

PURPOSE OF THIS APP

This app takes a message you type and turns it into a secret code. The app lets you send the coded message by SMS text to one or more of your agents (or friends) from your phone’s Contacts list. Your fellow agents can decode the message by copying and pasting it into their own version of the app.

APP RATING

ASSETS YOU’LL NEED

Image: authkey.png. Sounds: coding_completed.mp3 and message_sent.mp3.

Warning!

Before you start this app, you need to know that sending messages may cost money—and this app can send lots of messages all at once. Check with whoever pays your mobile phone bill to be sure this is OK. You can test the app without sending messages; we’ll tell you how as you work through it.

1. Setting up the screen

Here’s the screen layout:

Depending on your phone, you may find that the list of agents the user selects overlaps the image of the key (on the screen background). You can improve this by putting AgentsLabel into a VerticalArrangement so it’s contained in a column on the left of the screen.

2. Coding the blocks: encrypting the message

Here’s an encrypted message: suineg a era uoy. Can you tell what it says? Chances are you can crack this code very quickly (if not, we’ll explain how to decode it in a minute). But the code is probably sufficient to stop someone from glancing over your shoulder and reading the message, and later we’ll make some suggestions about how you can strengthen the encryption.

Learning Point: Cryptography in the real world

The science of secret codes is called cryptography. This word comes from parts of two ancient Greek words: crypt, meaning hidden; and graph, meaning writing. Turning a message into a code is called encryption (which rhymes with “description”).

This app is for fun, and the code can be easily cracked; but real computer programmers are paid to figure out how to send secret messages that can’t be read even if they’re intercepted. This isn’t just for secret agents—whenever you buy something online, you want to be sure that only you and the online shop have your personal payment details.

An algorithm that encrypts a message has a special name: a cipher (pronounced “syfer”). Our example cipher is incredibly simple—if you haven’t guessed it yet, we just reversed the message. That’s a simple idea for a human to understand, but how do you explain it to a computer? Try explaining the process step by step to a friend now. You could even write it down.

Did you come up with something like this?

1. Start at the last letter of the message.

2. Repeat the following for as many letters as are in the message:

1. Write down the current letter.

2. Move one letter towards the start of the message.

Look back at the three types of loops that we showed you earlier in the chapter. Which kind makes the most sense here? Before you run the loop, you do know how many times it should run: the same as the number of characters in the message. App Inventor can tell you the number of letters in any text string using a block called length in the text section. So, you can use a for range loop. Step 1 says you start at the end of the message and work backward, so you need the for range start value to be the length of the message. You’re working back to the first letter, so theend value needs to be 1 and because you’re working backward, you set the step value to -1, like this:

The do part of the loop needs to perform step 2a: “Write down the current letter.” In programming terms, you set up a variable called CodedMessage and keep joining the current letter to it as you run through the loop. How do you look at just the current letter? You worked out the solution to that particular problem in the chapter 5 Prankster app—the segment block lets you extract any part of a text string. In this case, you want to extract a single letter at the current position or loop counter. Once the loop is complete, you’ll change the MsgTextBox to show the new encrypted message, and you’ll also play a sound so the user notices that the coding has finished. Here are the final blocks:

Try it now. A single button click encrypts the message; clicking the button a second time decrypts the message. Next you need to figure out how to send the message to a list of contacts.

3. Adding agent contacts

The idea here is that you can add a list of agents to receive the message. The user can keep clicking and adding agents until they’re happy. You’ll put the names and numbers of all the selected agents in two lists called AgentNames and AgentTels. You’ll also display their names onscreen so the user can be sure they’re sending the coded message to the right people. You set up the two lists just like any other variables (in this case, you want them to be empty lists).

To choose an agent, you use your telephone picker (called AddTelPicker), processing the agent’s details using the AfterPicking event. Add two new list blocks: one for AgentNames and one for AgentTels. Finally, you want to output the names of all the agents chosen so far into theAgentsLabel. Here are the completed blocks to select an agent:

You’re using a quick option here—outputting all the AgentNames elements into the label, as you did in the ice cream example earlier. This means the names appear one after another with no breaks in between. You could make this better by having a for each loop output each name on a separate line (using \n).

4. Deleting agent contacts

Letting the user delete an agent from the lists is a two-step process. First you need to fill the DeletePicker list picker with all the agents the user has selected so far, to give them a choice of whom to delete. Then, when they pick an agent, you need to delete that agent’s name fromAgentNames and their telephone number from AgentTels.

When the user clicks a list picker, they trigger a BeforePicking event. At that point, you can set the list picker’s elements. Even though the list picker is empty when the user clicks it, the app immediately fills it. Because you already have all the chosen agents’ names in the AgentNameslist, you just need to set the DeletePicker Elements property to the AgentNames list. A diagram of this process might help:

The blocks to do this are actually simpler than the explanation! Here’s the block to fill (or populate) the DeletePicker list picker:

Then, to delete the agent from the two lists, you can use the SelectionIndex of the agent the user chose from the onscreen list. You also need to update the onscreen label so the user knows the agent is no longer selected:

5. Sending the message

To send an SMS text message, you’ll use a new Texting component that includes blocks to send a text messages to a phone number. You’ll call this block once for each agent in the AgentTels list, sending the same coded message to each agent.

Learning Point: Short Message Service text messages

What is SMS? SMS means Short Message Service. It’s a system that lets mobile phone users send and receive texts. The messages are limited to 160 characters (letters, numbers, or symbols). Longer text messages are sent as multiple messages and are put back together by the receiving phone service.

REMINDER!

Before you start this section, remember that sending messages may cost money—and this app can send lots of messages all at once! Check with whoever pays your mobile phone bill to be sure this is OK. You can test the app by leaving out the texting block call TextSender.SendMessage until you’re sure the rest of the app is working perfectly.

1. Here’s the basic idea broken into steps. When the user clicks SendButton ...

2. Set the text message to be whatever the coded message says (we have this stored already in the variable CodedMessage).

3. For each agent in the AgentTels list:

1. Set the texting phone number to that agent’s number.

2. Send the SMS text message.

4. Once all the SMS texts have been sent, play a confirmation sound and display a notification message.

Turning these ideas into blocks gives you the following:

This is a complex app. You could make it simpler, especially if you only wanted to send a message to a single agent at a time. And it’s by no means perfect—we’ve given you some suggestions for improvement in the “Try it out” section. But we hope you can see how mastering lists and loops gives you a great deal of programming power to create apps that do things humans would take a long time to do manually.

What did you learn?

In this chapter, you learned a huge amount, including the following:

· Apps can contain visible lists that users can select from, called list pickers; and invisible lists you can create that hold data, in the form of List blocks.

· App Inventor gives you access to ready-made lists for selecting images from your gallery and choosing contact details and photos of people you’ve added to your phone.

· The items in a list picker are called elements.

· The position of an item in a list is called its index.

· You make a data list by declaring a variable with a make a list block.

· You can select an item from a data list using its index or randomly.

· Lists can contain any data types (text string, number, or Boolean).

· The BeforePicking event fires when a user clicks a list picker, and the After-Picking event fires when they select an item from a list.

· There are three types of loops in App Inventor: for range, for each, and while.

· Loops can be nested inside each other.

· Encryption is the process of turning a message into code.

· Decryption is the process of decoding a message.

· The Texting component provides methods for sending and receiving text messages.

· Inserting \n into a string causes a line break in the text.

· A step-by-step plan in computing is called an algorithm.

Test your knowledge

1

Which loop (for range, for each, or while) would you choose in the following cases?

1. Working through a list (called Haystack) of one million items of data to find the first time the word needle appears

2. Adding up all the numbers from 1 to 100

3. Counting the number of times the name Smith appears in a list of 1,000 surnames

4. Guessing numbers at random until three lottery numbers are matched

2

What are the two properties of a Texting component that need to be set in order to send a text message?

3

How many elements are in this list, and what data is contained at index 6?

[bright, smart, clever, intelligent, talented, genius, wise]

4

Is each of these statements true or false?

1. Lists always have to contain elements.

2. A for range loop can have start, end, and step values set by variables.

3. Lists must contain only one sort of data.

4. Users can select only one item of data at a time from a list picker.

Try it out

1

Add the ability to select a contact’s picture in the Graffiti 2 app.

2

Find out how App Inventor lets you create custom colors, and add three new colors to the Graffiti 2 app (see http://mng.bz/58mP.

3

Create a slot-machine game using three lists of kinds of fruit. Award points and play a sound when three matching fruits are selected. Take it further by adding delays and animation sprites (see chapters 7 and 8).

4

Super Challenge: Write a nested-loop app that makes a list of every possible excuse from the Excuse Generator app.

5

Make the Multiplication Tables Generator display the tables in reverse order, from highest to lowest.

6

The Secret SMS Sender app generates errors if the user tries to delete an agent or send a message when no agents have been selected. Add validation rules to stop this from happening.

7

Improve the encryption of the Secret SMS Sender app. Here are some ideas:

1. Add a fixed number of random characters to the beginning and end of the coded message.

2. Create a list of all the keyboard letters and a corresponding list of substitute letters. For example, the first list might read “abcdefg” and the second rfzyabpl”. Make sure the second list contains no duplicates. Then create a loop that works through the message one letter at a time, substituting each letter by finding its index position in list 1 and creating a string from the letter with that index position in list 2.

Note

When you change the way the encryption works, you’ll probably have to split the Code/Decode functions into two separate buttons in the app. You may find creating separate procedures for each function helps.