Mobile Application Development
Now that you can design interfaces, it's time to make them functional. In MIT App Inventor, you program application logic using the Blocks editor — a visual, drag-and-drop programming environment where you snap together blocks to define what happens when users interact with your app. This lesson covers event-driven programming, variables, conditionals, lists, procedures, sensors, and persistent data storage.
Learning Objectives
- 11.5.4.3 Apply block-based programming to implement mobile application logic
- 11.5.4.4 Use event handlers, variables, and procedures in a mobile application
- 11.5.4.5 Use device sensors and features in a mobile application
Conceptual Anchor
The Stage Director Analogy
Think of blocks as stage directions in a play. Events are cues ("When the curtain rises..."). Handlers are instructions ("...the actors walk to center stage"). Variables are props the actors carry. Procedures are choreographed routines they can perform on demand. You're the director, arranging instructions so the performance (your app) runs smoothly.
The Blocks Editor
Switch to the Blocks editor by clicking "Blocks" (top right). Block categories appear on the left — these are called drawers.
Block Categories
| Category | Colour | Contains |
|---|---|---|
| Control | Brown | if/else, for each, while, open screen, close app |
| Logic | Green | true, false, and, or, not, comparisons (=, ≠, <, >) |
| Math | Blue | Numbers, arithmetic (+, −, ×, ÷), random, min, max, round |
| Text | Pink | Text strings, join, length, contains, replace, split |
| Lists | Teal | Create list, add to list, select item, remove, length |
| Variables | Orange | Initialize global/local variable, get, set |
| Procedures | Purple | Define procedure (with/without return value), call |
Event-Driven Programming
App Inventor uses event-driven programming: nothing happens until an event occurs. Every block program starts with a when block (an event handler). Events include button clicks, screen loads, timer ticks, sensor data changes, etc.
Common Events (Pseudocode Representation)
// Event: Button clicked
when ButtonLogin.Click do
if TextBoxUsername.Text = "admin" AND PasswordTextBox1.Text = "1234" then
set LabelResult.Text to "Welcome!"
set LabelResult.TextColor to Green
else
set LabelResult.Text to "Invalid credentials"
set LabelResult.TextColor to Red
end if
end when
// Event: Screen initialized
when Screen1.Initialize do
set LabelDate.Text to Clock1.Now
set LabelWelcome.Text to "Welcome back!"
end when
// Event: Text changed
when TextBoxSearch.TextChanged do
// Filter results as user types
call FilterList(TextBoxSearch.Text)
end whenBlocks ↔ Pseudocode
In App Inventor, you drag and snap blocks visually. In exams, you may need to write the logic as
pseudocode. The structure is the same: when [event] do [actions].
Always describe what the event is and what the response should be.
Variables & Data Types
| Concept | In App Inventor | Example |
|---|---|---|
| Global variable | initialize global [name] to [value] |
initialize global score to 0 |
| Local variable | initialize local [name] to [value] in do |
initialize local temp to TextBox1.Text |
| Set variable | set [global name] to [value] |
set global score to global score + 10 |
| Get variable | get [global name] |
set Label1.Text to get global score |
| List | create empty list or make a list |
initialize global tasks to create empty list |
Working with Lists
// Initialize a list
initialize global tasks to create empty list
// Add item to list
when ButtonAdd.Click do
add items to list: list = get global tasks, item = TextBoxTask.Text
set TextBoxTask.Text to ""
set ListView1.Elements to get global tasks
end when
// Remove selected item
when ButtonDelete.Click do
remove list item: list = get global tasks, index = ListView1.SelectionIndex
set ListView1.Elements to get global tasks
end when
// Count items
set LabelCount.Text to join("Tasks: ", length of list: get global tasks)Procedures (Functions)
Procedures are reusable blocks of code. In App Inventor, there are two types:
| Type | Block | Purpose |
|---|---|---|
| Procedure (no return) | to procedure [name] do |
Performs actions (like void in C++) |
| Procedure with result | to procedure [name] result |
Returns a value (like int/string functions in C++) |
// Procedure without return value
to procedure showMessage(msg)
set LabelMessage.Text to msg
set LabelMessage.Visible to true
end procedure
// Call it
when ButtonSubmit.Click do
call showMessage("Form submitted successfully!")
end when
// Procedure with return value
to procedure calculateBMI(weight, height) result
return weight / (height * height)
end procedure
// Call it
when ButtonCalc.Click do
initialize local bmi to call calculateBMI(TextBoxWeight.Text, TextBoxHeight.Text)
set LabelBMI.Text to join("Your BMI: ", round(get local bmi))
end whenDevice Sensors & Features
App Inventor can access phone hardware features through non-visible components (added from the Palette but don't appear on screen).
| Component | Category | What It Does |
|---|---|---|
| AccelerometerSensor | Sensors | Detects device tilt and shake |
| LocationSensor | Sensors | Gets GPS coordinates (latitude, longitude) |
| OrientationSensor | Sensors | Detects device orientation (angle, pitch, roll) |
| Camera | Media | Take photos with the device camera |
| Sound / Player | Media | Play audio files |
| TextToSpeech | Media | Convert text to spoken audio |
| Clock | Sensors | Timer events, get current date/time |
| TinyDB | Storage | Store data locally on the device (persists after close) |
| Web | Connectivity | Make HTTP requests (connect to APIs) |
| Notifier | User Interface | Show alerts, confirmations, progress dialogs |
1 Example: Shake to Roll Dice
// Add: AccelerometerSensor, Label (LabelDice), Sound (for effect)
when AccelerometerSensor1.Shaking do
initialize local roll to random integer from 1 to 6
set LabelDice.Text to get local roll
call Sound1.Play // dice rolling sound
end when2 Example: Save & Load Data with TinyDB
// Save user's name when they click Save
when ButtonSave.Click do
call TinyDB1.StoreValue(tag: "username", valueToStore: TextBoxName.Text)
call Notifier1.ShowAlert(notice: "Saved!")
end when
// Load saved name when screen opens
when Screen1.Initialize do
initialize local savedName to call TinyDB1.GetValue(tag: "username", valueIfTagNotThere: "")
if get local savedName ≠ "" then
set LabelWelcome.Text to join("Welcome back, ", get local savedName)
end if
end whenComplete Worked Example — To-Do App
✓ Full To-Do List Application
UI Components (Designer): TextBoxTask, ButtonAdd, ButtonDelete, ButtonClear, ListView1, LabelCount, TinyDB1
Blocks (Logic):
// Global list to store tasks
initialize global tasks to create empty list
// Load tasks on screen start
when Screen1.Initialize do
set global tasks to TinyDB1.GetValue(tag: "taskList", valueIfTagNotThere: create empty list)
set ListView1.Elements to get global tasks
call updateCount()
end when
// Add task
when ButtonAdd.Click do
if TextBoxTask.Text ≠ "" then
add items to list: list = get global tasks, item = TextBoxTask.Text
set ListView1.Elements to get global tasks
set TextBoxTask.Text to ""
call TinyDB1.StoreValue(tag: "taskList", valueToStore: get global tasks)
call updateCount()
else
call Notifier1.ShowAlert(notice: "Please enter a task!")
end if
end when
// Delete selected task
when ButtonDelete.Click do
if ListView1.SelectionIndex > 0 then
remove list item: list = get global tasks, index = ListView1.SelectionIndex
set ListView1.Elements to get global tasks
call TinyDB1.StoreValue(tag: "taskList", valueToStore: get global tasks)
call updateCount()
end if
end when
// Clear all tasks
when ButtonClear.Click do
set global tasks to create empty list
set ListView1.Elements to get global tasks
call TinyDB1.StoreValue(tag: "taskList", valueToStore: get global tasks)
call updateCount()
end when
// Procedure: update task count
to procedure updateCount()
set LabelCount.Text to join("Tasks: ", length of list: get global tasks)
end procedurePitfalls & Common Errors
List Index Starts at 1
Unlike C++ arrays (which start at 0), App Inventor lists are 1-indexed. The first element is at position 1, not 0. Accessing index 0 causes an error.
Not Validating Input
Always check if text boxes are empty before processing. An empty TextBox.Text in a math operation
causes a crash. Use if TextBox.Text ≠ "" before any operation.
Forgetting to Store Data
TinyDB must be explicitly called to save data. Changing a global variable does NOT automatically
save it. Always call TinyDB.StoreValue after modifying data you want to persist.
Confusing Global and Local Variables
Global variables persist throughout the app. Local variables exist only within their block. If you initialize a variable inside "when Button.Click", it resets every time the button is clicked.
Pro-Tips for Exams
Writing App Inventor Logic in Pseudocode
- Start with
when [Event] do— always identify the trigger - Use
set [Component].[Property] to [value]for changing UI - Use standard IF/ELSE, FOR, WHILE for control flow
- For lists: use
add to list,select item at index,length of list - Always mention TinyDB if the question asks about persistent data
Graded Tasks
Define: event handler, global variable, local variable, procedure. Name 3 sensors available in App Inventor.
Explain the difference between a procedure with a return value and one without. Give an example of when each would be used.
Create a BMI calculator app: two text boxes (weight in kg, height in m), a "Calculate" button, and a label showing the BMI result and category (Underweight/Normal/Overweight/Obese).
Create a quiz app with 5 questions. Track the score using a global variable. Show the final score when the quiz ends. Save the high score using TinyDB.
A student's app crashes when the user presses "Calculate" without entering a number. Explain why this happens and write the pseudocode to fix it with input validation.
Design and build a "Contact Book" app that allows adding names and phone numbers to a list, displaying all contacts, and deleting selected contacts. Data must persist using TinyDB.