App Inventor Code Snippets


This page lists useful code snippets for App Inventor 2.

The snippets for App Inventor Classic you can now find here.



What's New New?


App Inventor Code Snippets Overview

The snippets for App Inventor Classic you can now find here.

Canvas

Web Viewer and App Inventor

Activity Starter

Other Stuff

Do you need help with your App Inventor project?

I can help you: for one hour I charge 25 USD.
Please contact me at info [at] puravidaapps [dot] com for details!
For questions about App Inventor, please use the App Inventor forum. 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.

There is one special thing to consider for HTML documents uploaded as assets into App Inventor: During development, you have to use the development path to the embedded HTML document.

file:///mnt/sdcard/AppInventor/assets/<NAME OF YOUR HTML FILE>.html


Before building the app, use the production path.

file:///android_asset/<NAME OF YOUR HTML FILE>.html


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
Download apk file

Back to top of page ...




App Inventor and animated gifs

You can access an animated gif file directly with the webviewer component.

There is one special thing to consider for HTML documents uploaded as assets into App Inventor: During development, you have to use the development path to the embedded HTML document.

file:///mnt/sdcard/AppInventor/assets/ani.gif


Before building the app, use the production path.

file:///android_asset/ani.gif


Download aia file for App Inventor 2
Download apk file

Back to top of page ...




How does the new 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. Alternatively of course you can use a directory on the SD card, e.g. file:///sdcard/Temp/stuff.html

There is one special thing to consider for HTML documents uploaded as assets into App Inventor: During development, you have to use the development path to the embedded HTML document.

file:///mnt/sdcard/AppInventor/assets/webviewstring.html


Before building the app, use the production path.

file:///android_asset/webviewstring.html



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 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()
      




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
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! The default data type is "mobile", unfortunately we can't change that with MIT App Inventor, because we only have one ExtraKey - ExtraValue pair we can send with the Activity Starter.

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 the example How to send an email with attachment.




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.

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


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.

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 here: App Inventor Activity Starter App. Thank you mletsch!

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

Solution found here: App Inventor Activity Starter App. Thank you mletsch!

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




How to start Whatsapp


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




Other Basic Stuff



App Inventor and the Screen Size

The screen size of some older phone models is 320 x 480 pixels in portrait mode. The current version of App Inventor (Android API 3) uses that size. Thank you Jos! To demonstrate that, I used Scott's example and a Samsung Galaxy Tab 10.1N. The first screenshot is the app after packaging through App Inventor (screen size =545 x 295), the second screenshot after additionally going through AppToMarket and setting the screen to "Any" (screen size = 1280 x 727).

See also some recommendations from Gareth here. Also the Universal Screen Size tutorial by Saj might help.

Back to top of page ...




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
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.

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


For the leadingZeros procedure, see below.
Download aia file for App Inventor
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.




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.




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 ...


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 | Apps | Snippets | Tutorials | News | Forums | Links | Search | Contact