Java Code Snippets for App Inventor Extension Developers


The following is a collection of Java code snippets specific to the App Inventor platform, for those that are developing extensions for the App Inventor platform this resource may be utilised as inspiration for your custom extensions.

Whether you are a beginner learning how to create extensions or an advanced Java Software Engineer, this resource will hopefully be helpful in learning the App Inventor specific Java code.

Accessing App Assets

This method allows you to access the assets you have bundled in your app, this only works if you know the exact filename of the file you want to access.
import com.google.appinventor.components.runtime.Form;

...

InputStream inputstream = form.getAssets().open("your_file.json");


Creating a YailList

This code demonstrates how you can return a list which is compatible with all the functions in the list category from the App Inventor website.
import com.google.appinventor.components.runtime.util.YailList;
import java.util.ArrayList;
import java.util.List;

...

List listItems = new ArrayList();
listItems.add(data);
return YailList.makeList(listItems);


Creating a Runtime Error Alert

Built into the App Inventor libraries is the YailRuntimeError, you can use this to throw an error and a message will be displayed on screen.
import com.google.appinventor.components.runtime.errors.YailRuntimeError;

...

try {
something() 
} catch (Exception e) {
throw new YailRuntimeError("Argument to MakeInstant should have form MM/DD/YYYY hh:mm:ss, or MM/DD/YYYY or hh:mm",
 "Sorry to be so picky.");
}

Check Android version

Sometimes features can change or become unavailable this is where the Android API level comes into play, you can detect the version of Android the user has installed on thier device, if it's supported you can execute the action, if it's not supported you may want to display a message or there could be a different way to complete the desired action.

The following code demonstrates how to check if the device is running Android KitKat or newer.


import android.os.Build;

...

if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT){
 //Execute code here - Version of Android is KitKat or newer
}
else{
 //Execute other code - Version of Android is older than KitKat
}

For more information on the different Android version codes see Android Version Codes Reference.


This page will be updated with new code snippets as I come across them, if you have any snippets you would like to contribute to this page, feel free to comment in the comments section below.



Icons made by Madebyoliver from www.flaticon.com is licensed by CC 3.0 BY

Was this helpful?

Yes No

Comments

Thunkable Components