App Inventor Code Snippets


This page lists useful code snippets for App Inventor.



App Inventor Code Snippets Overview

Canvas

Web Viewer and App Inventor

Activity Starter

Other Stuff

For questions about App Inventor,
please ask in the App Inventor community.Thank you.



Canvas



How to save a canvas

This is a small add on to the Paint Pot tutorial. Add additionally a Button and a TinyDB component. Then in the block editor add these two blocks.
The function Canvas.Save and Canvas.SaveAs return the directory and filename. Therefore you have to define something (e.g. a variable or a label) which is able to receive this information. In the example this information is stored in a TinyDB, so the next time the app starts, the drawn picture is still there.

In this example the image will be stored in the root directory of your SD card.
Feel free to add a directory, for example /MyDirectory/MyCanvas.png
Back to top of page ...




How to create a Scratchcard with App Inventor

It has been asked in the forum how to create a scratchcard with App Inventor. This is my solution.


Download aia file for App Inventor 2
Back to top of page ...




How to Swipe left/right and top/bottom to trigger something

It was asked in the forum: I'm trying to swipe to change an image. How can I do that?. This is a nice example for the flung event. Let me add additionally another requirement: swipe to the left or right to change an image and swipe to the top or bottom to change the background color. We can use the heading property to find out, in which direction there was the swipe, the heading ranges between -180 to +180.


Download aia file for App Inventor

Back to top of page ...




How to change background image without changing drawn lines

It was asked in the forum: I'm creating an app that will allow me to take a picture and then draw on it. The next step would be to then be able to view the drawn part without the background image. How would I do this?
The only possibility I can see is to set the taken image as screen background, then draw on the canvas. I set the Canvas background color to none in the Designer window to be able to see the background image. The Screen background color will be set to none after taking the first image in the Camera.AfterPicture event.

Download aia file for App Inventor

Back to top of page ...




Webviewer and App Inventor

From the Palette, expand 'User Interface' and add a 'WebViewer' component to the screen.



How to read a HTML page stored as media file inside of App Inventor

The example uses 2 html files and an image stored as media files inside of App Inventor. In case you like to take a look at the source of these files, upload the App Inventor aia file to App Inventor and download the html files from the assets list.

For the example, I uploaded a html page as asset into App Inventor, see below.

Note: You now can use the following path, which works for development and production!

http://localhost/hello.html


Note: For Koduar you can use this logic. Thank you bodymindpower!

Note: External anchors are working only for Android 2.x devices but not for Android 3.x and 4.x devices. Thank you Ehsan for finding it out.
Example: An external anchor is to go to the following url with a webviewer file://android_assets/page2.html#myAnchor. This works only for Android 2.x. You can go to this page file://android_assets/page2.html and inside the html document jump to the anchor, this works for all Android versions.



Download aia file for App Inventor 2
Back to top of page ...




App Inventor and animated gifs

You can access an animated gif file directly with the webviewer component.
Note: You now can use the following path, which works for development and production!

http://localhost/ani.gif


Download aia file for App Inventor 2
Back to top of page ...




How does the property Webviewer.WebViewString work?

As explained by Hal here: You can use WebViewString to communicate values back and forth between your App and the WebViewer. In your App, you get and set the WebViewer.WebViewString properties. In you webviewer, you open to a page that has Javascript that references the window.AppInventor object, using its getWebViewString() and setWebViewString(text) methods. Thank you Hal and Jeff for this great enhancement!

For the example, I uploaded a html page as asset into App Inventor, see below.
Note: You now can use the following path, which works for development and production!

http://localhost/webviewstring.html


Note: see also the following tutorial by ABG.



HTML file

<!doctype html>
<head>
  <meta name="author" content="puravidaapps.com">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test</title>
</head>

<body>
  <script>
    document.write("The value from the app is<br />" + window.AppInventor.getWebViewString());
    window.AppInventor.setWebViewString("hello from Javascript")
  </script>
</body>
</html>


Download aia file for App Inventor 2
Back to top of page ...




How to display some HTML text in a webviewer

For the example, I uploaded a html page as asset into App Inventor, see below.

Note: You now can use the following path, which works for development and production!

http://localhost/label.html


HTML file

<!DOCTYPE html>
<html>
<head>
  <meta name="author" content="puravidaapps.com">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Label</title>

  <script src="jquery-1.8.0.min.js"></script>
  <script>
  // urldecode function, which also handles the case of spaces being encoded as +
  // http://stackoverflow.com/a/4458580/1545993
  function urldecode(str) {
    return decodeURIComponent((str+'').replace(/\+/g, '%20'));
  }
  </script>
</head>

<body>
  <script>
    // get the text to display from the webviewstring, urldecoded
    var strLabel = urldecode(window.AppInventor.getWebViewString());


    // append the text to the body of the html document
    $("<div>" + strLabel + "</div>").appendTo("body");
  </script>
</body>
</html>


Note: To use this example, you have to upload the library jquery-1.8.0.min.js into the assets of your project. You can find the library in the assets of the example project downloadable below or on the official jQuery download page.


Download aia file for App Inventor 2
Back to top of page ...




How to sort a list using the webviewer(!)

After Stephen provided his solution for How to sort a list of names, I was thinking, why reinventing the wheel? Why not just using a simple JavaScript sort method? See the ridiculously simple solution below. This sort works with numeric and alphanumeric values. To perform a numeric sort, you must pass a function as an argument when calling the sort method, see the examples here how to do it. To reverse the sort order, just add

.reverse()
      



You also can sort list of lists using this method, see an example here.

Note: The data limit using this method is around 2 MB (max. length of an URI) For sorting more data, the data also could be passed to an embedded html file in the WebViewString property.

Successfully tested on Nexus 5 running Android 4.4.3 and Samsung Galaxy Tab 10.1N running Android 3.2. For the Galaxy Tab the home url needs to be set first to get this runnning.
Download aia file for App Inventor 2

See also this collection of sort methods by Joerg Kowalski. Thank you Joerg!
Back to top of page ...




How to get the max value within a list of numbers

It has been asked in the forum: I was trying to calculate max value within a list of numbers. Can you make it without using a loop? ... I started with the same solution as spider pig showed, and that made me wondering if anything faster is possible.

This is my embedded HTML/JavaScript solution, which is based on this stackoverflow answer. Thank you newspire!


<!doctype html>
<head>
  <meta name="author" content="puravidaapps.com">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title></title>
</head>

<body>
  <script>
    // get the list from the window.AppInventor object, remove the quotes and split at comma
    arr = window.AppInventor.getWebViewString().replace(/"/g,'').split(",");

    // find the max and print it to the title
    window.document.title = Math.max.apply(Math, arr);
  </script>

</body>
</html>



Download aia file for App Inventor 2
Back to top of page ...


Please also take a look at the App Inventor and embedded HTML/JavaScript tutorials and advanced examples.




How to pass user and password for basic HTTP Authentication in URL

According to this info on serverfault.com it is possible to pass user and password in a URL to be able to access a restricted area. The format to be used is

http://username:password@example.com


Unfortunately this does not work for all Android versions. I tested that on HTC Desire running Android 2.2 and Nexus 5 running Android 4.2.2 and it worked. It did not work on Samsung Galaxy Tab 10.1N running Android 3.2.



An example how to download a file from a restricted area you can find here.

Back to top of page ...




Activity Starter



How to launch Google Play from within your app


Back to top of page ...




How to add a contact to the contact list

Provided by Fabio in this thread. Thank you!
New Using the new Extras property we now can use multiple ExtraKey - ExtraValue pairs, see also the available constants.


Download aia file for App Inventor
Back to top of page ...




How to send an eMail

Following the Activity Starter documentation we easily can send an eMail with the Gmail client:

Download aia file for App Inventor 2
Back to top of page ...

You also might be interested in Different eMail solutions for App Inventor.




How to launch Waze to look for a specified location

Following the Waze documentation we easily can open Waze and look for a specified location:

Back to top of page ...




How to view a pdf document

You can use the Activity Starter to view a pdf document, which is already stored on your device. How to download files from the internet to your device. To open a pdf document from the Internet, I used a webviewer together with the Google Docs Viewer and the link to the pdf document.

It has been asked in the App Inventor forum: I have uploaded the PDF files into the media section in App Inventor but I just can't seem to find how to make them open from clicking the button.
Note: It is not possible to store a pdf document as asset in App Inventor and view it with a pdf viewer. This is, because App Inventor itself can't display pdf files and external pdf viewers called with the activity starter from App Inventor are not able to access assets inside the app.

Update: App Inventor is now able to view a pdf file from the assets using the new Pdf extension. Also you do not need an external pdf viewer anymore!

You also might be interested in the following example: How to pick a file from SD card with App Inventor



New Note: Drag a file component into the working area (without necessarily using it) to get the READ permission into the manifest and additionally ask for READ permission before trying to use the activity starter solution.

Download aia file for App Inventor
Back to top of page ...




How to pick an image using the Activity Starter

The Image Picker component is limited to 10 images you can pick from: When the user taps an image picker, the device's image gallery appears, and the user can choose an image. After an image is picked, it is saved on the SD card and the ImageFile property will be the name of the file where the image is stored. In order to not fill up storage, a maximum of 10 images will be stored. Picking more images will delete previous images, in order from oldest to newest.
Alternatively you can use the Activity Starter without such restrictions. Thank you Jari for this tip.

Download aia file for App Inventor
Back to top of page ...




How to use Activity Starter to view a Youtube video in full screen

In the Designer set Screen.Orientation to Landscape. Thank you Aaron for this example.
See also the discussion here.

Download aia file for App Inventor
Back to top of page ...




How to start a Skype call

This App Inventor solution is based on this stackoverflow question and answer. Thank you allemattio!
In the textbox you can enter a Skype name or a phone number.

Download aia file for App Inventor
Back to top of page ...




How to enable Bluetooth (User still needs to confirm)

Solution found in the Activity Starter app by mletsch80 (unfortunately not available anymore in Google Play)
New ActivityStarter.ActivityCanceled event added

Download aia file for App Inventor
Back to top of page ...




How to start OsmAnd and open the map with a place marker

As it has been said in the Activity Starter documentation: If you can find the "cmp=" string, then the ActivityPackage is the part before the slash, and the ActivityClass is is the entire "cmp=" part, without the slash character.



To find the correct DataURI parameter to use for OsmAnd, see the OsmAnd documentation.
Note: For OsmAnd+ please use net.osmand.plus instead of net.osmand as Activity Package. Thank you Harry!

Download aia file for App Inventor
Back to top of page ...




How to copy text to the Clipboard

Precondition for this solution to work: the Google Docs app is installed on the device! Because of an update of the Google Docs app we have to adjust our class name like this:
To find out the correct settings use the Sharing component and select "Copy to clipboard" in the Share dialog. Then in logcat you can see the correct values for package and class name. Thank you Manish!

New You probably also might be interested in my App Inventor Clipboard Extension, which can copy and paste to/from the clipboard without having to use another external app...

Download aia file for App Inventor
Back to top of page ...




How to start Whatsapp/send a message with Whatsapp

How to send a Whatsapp message to a specific mobile number?
There is this Android solution but this is unfortunately not possible with App Inventor, you only can open Whatsapp like this


or you can prepare the message in App Inventor and pick a contact from the Contact Picker in Whatsapp to send it like this

You also might be interested in the Sharing extension, which offers a method to share via Whatsapp.
See also this thread about how to send specific message to a specific number.

Download aia file for App Inventor (example 1)
Download aia file for App Inventor (example 2)
Back to top of page ...




How to execute statements in the Jackpal Terminal Emulator

Terminal Emulator for Android is a terminal emulator for communicating with the built-in Android shell. It emulates a reasonably large subset of Digital Equipment Corporation VT-100 terminal codes, so that programs like "vi", "Emacs" and "NetHack" will display properly. Download the Terminal Emulator for Android from Google Play.

Thank you Richard for being the sponsor of this snippet!
I just followed the documentation and translated this into the following blocks.

After that, you have to modify the manifest, you can use AppToMarket for that. You have to add the permission jackpal.androidterm.permission.RUN_SCRIPT to get this running.
The manifest looks like this in the end:

<?xml version="1.0" encoding="utf-8"?>
<manifest android:versionCode="1" android:versionName="1.0" package="appinventor.ai_taifunbaer.terminal"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="jackpal.androidterm.permission.RUN_SCRIPT" />
    <application android:label="terminal" android:icon="@drawable/ya" android:debuggable="false">
        <activity android:name=".Screen1" android:configChanges="keyboardHidden|orientation" android:windowSoftInputMode="stateHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


Download aia file for App Inventor
Download apk file
Back to top of page ...




How to uninstall another app programmatically

Following this stackoverflow snippet we can uninstall an app like this:

Note: This solution once worked for older Android versions, how to do it with newer Android versions see this thread. Thank you Anke and vknow360!



Other Basic Stuff



How to build a simple compass app with App Inventor

Compass card image from Wikipedia by Brosen. Thank you!

Download aia file for App Inventor 2
Bebemo made this example a little bit softer so that the compass needle doesn't bounce back and forth so crazy. You can find it here. Thank you Bebemo!

Back to top of page ...




An enhancement to the compass app to provide additionally the direction to a waypoint

It was asked in the forum: I had a question about using a compass direction that points to one specific Adress or coordinate instead of just the north.
We will have to do some calculations: you can calculate the bearing according to the formula provided here http://www.movable-type.co.uk/scripts/latlong.html. Then to get the direction to the waypoint, just calculate azimuth - bearing (in a range between 0 and 360 degrees), see screenshots. The example points to the famous whalestail in Uvita, Costa Rica.



Note: See also a modified example by SteveJG in this forum thread, which points to Mekka.
Make sure you have your GPS turned on in your Android's Settings menu. You would get an erroneous result if the LocationSensor.Latitude and Longitude both reported 0. If the values do not change, the app will not work because the code is based on local GPS coordinates.

Download aia file for App Inventor 2
Back to top of page ...




How to trigger something if device is facing down

It has been asked in the forum how to trigger a sound if the device is facing down. I'm using the Accelerometer Sensor for the example, because this sensor offers acceleration in the Z-dimension. Thank you freesfx.co.uk for the car alarm sound.


Download aia file for App Inventor 2
Back to top of page ...




How to create a nested listpicker

It has been asked in the forum: I need a main listpicker with different sublists of items below them depending which main list item is selected.
For the solution presented here, I'm using 2 listpicker, the second listpicker for the sublists is hidden and will be opened with the listpicker.open block.



How does this work: Using the first listpicker you select the main category, in the example "Fruit" or "Vegetables". Lets assume, you picked "Fruit", which means selection index = 1. Using the same selection index and the select list item block you select the corresponding sublist of listDetail, in the example these are Apple Banana Mango and Orange to display them in the second listpicker.

New Jay Dee asked in the forum": I am still having trouble figuring out how to put an email and number for each name. When I click on Apple I want to be able to see: Apple
555-555-5555 (and if I click it, it will dial the number)
apple@gmail.com (and if I click it, it will open up an email)

That's a nice example to learn how to work with list of lists. I adjusted my nested listpicker example, you can find it here.

Download aia file for App Inventor 2
Back to top of page ...




How to get a date in format YYYY-MM-DD

Starting from App Inventor Version 144 (June 30, 2015) we now can format dates and times easily using a pattern like yyyy-MM-dd. For all possible patterns, see here.
Back to top of page ...




How to get leading zeros in App Inventor


Back to top of page ...




How to get the Day of Year

Just use the Clock.Now block to get loads of information, then use a parse procedure to extract the day of year (see snippet below). Note: As Hal said in this thread, this is an undocumented feature. It's unlikely that this will change, but you have to use this on your own risk.


New A much easier method is using the new FormatDate block like this

For all possible patterns, see here.




How to parse a result


Download aia file for App Inventor
Back to top of page ...




How to use the Sound Recorder

It has been asked in the forum: I'm very new to this and would like to use the SoundRecorder but have no idea how it works and unable to find any example.
I now prepared an example for you:

Download aia file for App Inventor
Back to top of page ...




New formatting possibilities with the Notifier

According to the documentation of the notifier component we now can use some HTML for the formatting: The messages in the dialogs (but not the alert) can be formatted using the following HTML tags: <b>, <big>, <blockquote>, <br>, <cite>, <dfn>, <div>, <em>, <small>, <strong>, <sub>, <sup>, <tt>, <u>. You can also use the font tag to specify color, for example, <font color="blue">. Some of the available color names are aqua, black, blue, fuchsia, green, grey, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow.
Note: You might have to build your app to see the results! Thank you Hal for the example.




New formatting possibilities with the Label

Labels can now contain a limited subset of HTML as well as text. Check the HTMLFormat designer property to enable this feature..




How to play a random sound when the device is shaken

Thank you SoundFx for the sounds.

Download aia file for App Inventor
Back to top of page ...




How does the lookup in pairs block work?

Store tag/value pairs in a list to be able to easily search for a tag and get back the corresponding value from the list.


Download aia file for App Inventor 2
Back to top of page ...




How to pick a random item from a list without picking duplicates?

In this example I use the random integer block instead of the pick a random item block. The picked item will be removed from the list after displaying it.


Download aia file for App Inventor 2
Back to top of page ...




How to take a picture or pick an image and share it

For the Imagepicker, do not forget to add file:// to the provided path to the image...


Download aia file for App Inventor 2
Back to top of page ...




A workaround for the decimal separator problem

The Android, Where's My Car? tutorial does not work for devices, which use a comma as decimal separator: this is, because the location sensor provides numeric values with comma as decimal separator in this case. The Googe Maps app however expects values with dot as decimal separator to work correctly.
So how to fix this issue? The answer is simple: just use the replace all block to replace comma by dot. I prepared a custom procedure for that, see screenshot, you also could use the replace all block directly. Also if you develop an app in North America and you want to be sure that it also can be used in Europe without decimal point issues, just use the replace all block...


Back to top of page ...




How to get european or chinese characters from Web ResponseContent

It has been asked in the forum : why chinese word can't work from web reponsecontent?
Well, as you can see it works: I stored a text file with spanish, german and chinese characters in a text document. Important: To get this working, you have to store the text in UTF-8 format, see screenshot of notpad "Save As" dialog. Note: I'm using a german version of notepad here.






Download aia file for App Inventor 2
Back to top of page ...




How to use the YandexTranslate component

See the documentation and http://api.yandex.com/translate/ for more information, including the list of available languages and the meanings of the language codes and status codes.


Download aia file for App Inventor 2
Back to top of page ...




How to read a file stored as asset in App Inventor

The file component is very easy to use, see also the the documentation how to use it.


You also might be interested in How to append text to a file stored as asset in App Inventor.

Download aia file for App Inventor 2
Back to top of page ...




How to keep the screen on

You add a notifier and a clock, not used for other purposes in your app. Set the clock to a rather long interval, 10 seconds or so. Maybe even a minute would work fine, depending on the setting of your phone. Make the background color of the notifier transparent. When the clock.timer fires, display a warning that is an empty string. In this way you will not see it, because of the transparent background. It keeps your phone awake for as long as you want and as long as your battery stays alive (which may be considerably shorter). Note: description by Chica copied from here.




Download aia file for App Inventor 2
Back to top of page ...




How to create a directory

The file component unfortunately can't create a directory, but we can use the Canvas as workaround.


NewNote: It is no longer possible to create a folder (or save a file) in the external storage on devices with API > 28 using the Canvas component, see also this thread in the App Inventor community Thank you Anke!.

You probably also might be interested in my App Inventor File Extension, which offers some additional blocks related to the App Inventor built-in file component...

Download aia file for App Inventor 2
Back to top of page ...



Developing and maintaining snippets, tutorials and extensions for App Inventor takes a lot of time.
I hope it saved some of your time. If yes, then you might consider to donate a small amount!

Donation amount:

or donate some mBTC to Bitcoin Address:
1Jd8kXLHu2Vkuhi15TWHiQm4uE9AGPYxi8
Bitcoin

Thank you! Taifun
 

Creative Commons License
This work by Pura Vida Apps is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License
with attribution (name=Pura Vida Apps and link to the source site) required.


Home | Snippets | Tutorials | Extensions | Links | Search | Privacy Policy | Contact