Writing to and reading from text files in App Inventor programs

Update: When the program is run in AI2 Companion, it behaves differently than when run as a standalone “build” .apk app.

The updated tutorial explains where – and why – the files you create may appear to be hidden on the phone – how to find them and how to transfer the files to your PC.

An earlier blog post described how to store data using TinyDB so that an app’s data can persist between uses of the program, or even to share data between screens in a program.

Another way to save data is to write the data to a file on your Android device. App Inventor has introduced a File control that lets us write text data to a file and then read it back, later. As we will see, the File control is not the easiest thing to use but with some work, the control can be used to store data from our program into a file. (Once data is in a file, you could, hypothetically, email the file to yourself to read it on a computer, or transfer it from an Android to device to another computer using a USB cable and mounting the device as a simulated hard drive. But that is beyond the scope of this blog post!)

Let’s start our exploration of the File control in the Designer. Beneath the Palette heading, find the Storage item. Within Storage, find the File control. Drag and drop the File control on to your app. The control is placed below the user interface as it is an invisible control.

FileIOControl

 

After dragging the File control, you’ll see something like this at the bottom of the user interface Designer:

File1ControlThe real work begins over in the Blocks editor. For this example, we have just a few user interface components:

  • btnAddItem – when pressed, it writes some items out to a text file
  • btnTestFetch – when pressed, it starts the process of reading the data from the text file back into the program
  • txtBoxResult1 and txtBoxResult2 – a couple of text boxes that can be used to display the values read from the file.

In the Blocks editor, we will set up some blocks to write text to the file. We will start with a simple example:

FileIOSimpleEx

btnAddItem.Click is an event handler and you should already be familiar with the concept of event handlers. The new features are those in purple, which reference the File1 control. Assuming you are implementing this in your own app, you should find the File1 control, probably at the bottom of the list of Blocks, at the left side of the Blocks editor.

The first purple item above, AppendToFile, writes a piece of text to the file indicated at the filename component. Writing to the file is the easy part!

When our app’s TestFetch button is pressed, the code initiates a read operation by reference ReadFrom and giving it the name of the file to read the data from. But at this point, the data has not yet been read!

When the data has actually been read, an event occurs and we need to add an event handler for GotText to process the data that has been read in to the app.

In the example above, the original text is read back from the file and placed in an on screen text box to illustrate success.

Writing and reading a single line of text is easy. But writing and reading a series of data elements is a bit more complex. There are several possible ways to handle this but I have chosen to use the mechanism.

But before we get started, let’s add a piece of code to help us during development: let’s always start with a clean data file by deleting the old file (if any) first. We can do this by adding the following code to the screen’s Initialize event:

FileIOSimpleDelete

Find your screen’s name in the Blocks list and then click the mouse over the screen name. You should see the Initialize event handler appear in a pop up list – drag that initialize block over to the Blocks editing window.

Let us now take a look at writing a list – or list of lists to the text file. You’d best be familiar with lists (see volume 1 of my App Inventor 2: Tutorial) before starting on this.

FileIO-Lists

 

For this example, we want to store a typical name/address combination. This means storing several items for each individual record – in our example, we have two individuals but this could be easily expanded to support more.

The first block creates two lists (at far right) – one list per person to combine the name and address.

These two lists are converted to the “CSV” (comma separate values) format and the two CSV values lists are combined into a table. Think of this as being something like this:

  1. Alice Smith, 1234 Main St, Portlandia, USA
  2. Bob Smithy, 1234 Rural St, Portlandia, USA

Think of this as being like a spreadsheet with rows and columns, if you prefer. All those blue list processing blocks are converting our text input at right, into two CSV rows, combining those into a list, and then converting to a table. That’s a lot of work but its just a way of storing our more complex data into the file.

At the bottom block, the data read from the file is converted from text back in to table list format. And after this is done, individual list elements can be referenced. Since this table has two rows, index position 1 and index position 2 refer to first and second name records. Since each row is itself a list, we could also select the individual items from each name/address record if we wanted (but that is not shown in this example).

App Inventor’s new File control is helpful but remains cumbersome to use, as shown by the effort to read and write complex records.  It works only with text (which is how most of App Inventor works) and it reads the entire file all at once, rather than reading a line at at time. This limits the total size of the file that we can likely handle (maximum size is not known).

Where is testfile2.txt stored on your phone?

On my Nexus 5, there is a visible folder named AppInventor, and within that folder, there is a folder labeled data. This is where testfile2.txt is located.

This location also corresponds to /storage/emulated/0/AppInventor/data, a folder on the phone. You’ll need a file explorer app – or connect your phone to a PC using a USB cable and mount the phone as an external hard drive – to see the file structure on the phone.

To Learn More About App Inventor Databases and Files

My 322 page e-book provides extensive guidance on App Inventor databases and files, including TinyDB, TinyWeb, Fusion Tables and text files.

Learn about all my App Inventor guide books, including sample chapters – here!

  • App Inventor 2 Databases and Files (Volume 3 e-book)
    Step-by-step TinyDB, TinyWebDB, Fusion Tables and Files
    Buy from: Amazon, Google Books, Kobo Books

“The creation of live programming in App Inventor.”

App Inventor has a neat featured called “live programming”. With this feature, after transferring your app from the App Inventor “cloud” designer and blocks editor, you can make changes in the Designer or Blocks editor while your program is connected and running. Try it! Create an app, transfer to your phone and start running the app – then go back to the App Inventor browser window and make some changes to your program. Moments later, your changes will show up on the phone!

Here is a bit of history about how this feature came to be, and how it was implemented: Colorless Green Ideas Sleep Furiously: The creation of live programming in App Inventor.

That summary is pretty techie and might be beyond someone very new to programming.

Using TinyDB in App Inventor

(This post was completely rewritten and updated on October 30, 2015)

What is TinyDB?

TinyDB is a simple “database” that stores data on your phone or tablet. Unlike program variables that go away when your app is finished running or your phone is re-set, values stored in TinyDB remain on your phone for use the next time your app is run.

About Memory on your Phone or Tablet

Your smart phone or tablet typically has two primary types of memory: RAM and FLASH memory.

RAM stands for “random access memory” – but today we mostly think of RAM as memory that can be accessed very fast (as compared to Flash or hard drive memory storage). RAM retains values as long as power is applied to the RAM circuity. Once we turn off the power, the values stored in RAM are lost. (In some applications, extra batteries are used to continuously provide power to RAM even when the “normal” power is turned off.)

Flash memory retains values when the power is turned off. But access to Flash RAM is not as fast as access to conventional RAM memory.

Why is it called “Flash”?  There was an early version of memory technology where the memory was erased by literally flashing it with ultraviolet light. However the inventor of Flash RAM chose the name “Flash” for different reasons. Modern Flash RAM is read, written and erased electronically.

App Inventor variables are stored in RAM memory – and the content of RAM is erased or reset whenever the power is turned off. TinyDB, on the other hand, stores values in FLASH RAM, where the values remain even when the power is turned off.

Using TinyDB

TinyDB provides a simple way to store and retrieve data efficiently and to store the data in long-term storage.  TinyDB is based on the concept of a “tag” to identify the stored data, and the data value. Think of a “tag” as like using your name as your identification to look up your address:

Tag value: Martin

Value: 123 Main St, Anytown, USA

or

Tag value: Alexa

Value: 321 Other St, Someplace, USA

TinyDB uses the “tag” (such as Alexa) to quickly locate the corresponding value. Even if you have 100 names and addresses stored in TinyDB, TinyDB can  look up the “tag” quickly and use the tag to find the corresponding value. We do not need to know how TinyDB does its look up so fast – it just does it [see Footnote 1].

In most database programs, the “tag” is known as a “key” or “key value”. App Inventor uses the name “tag” in place of “key”. As I am used to the name “key”, I tend to use “key” were I should have used “tag” in App Inventor! You will see this is the sample program, below!

To learn how to put TinyDB in operation, we construct a very simple app, described below.

Continue reading Using TinyDB in App Inventor

AI Companion and your phone’s battery

On my phone, if I leave AI Companion running, the battery life of my phone goes down more rapidly.

Consequently, when I am done working on an app on my phone, I go in to Settings | Apps on the Android phone, find MIT App Inventor in the applications list, select it, and then select Force Stop.

I have no idea if other people experience this problem but the fix is simple – just kill the AI Companion app if its no longer needed.

This issues appears to be because the AI Companion links to the App Inventor cloud-based editor – as you edit and make changes, those changes are copied from the editor back to your device, almost in real time. However, if you walk away from the computer and the phone, neither realizes you left for a cup of coffee or to walk the dog – and they may continue to chat with each other, draining the battery.

Regardless, when developing apps for your phone or tablet, your best bet is to turn off battery saving features and leave your phone on (so you don’t have to continually enter your pass code or otherwise restart the phone after it goes to sleep). AND – very important – leave it plugged into a charger. Taking these steps can make your app development go more smoothly.

You can run App Inventor and install apps to your phone at Starbucks

As you already know, you can use App Inventor and the AI Companion on your phone to install apps from your computer (Browser) to your smart phone, as long as both are on the same network.

This works at Starbucks too 🙂 Just run appinventor.mit.edu to access your app in the cloud, run the MIT AI Companion app on your phone, and then select Connect | AI Companion in the browser window.

The app installs on to your phone.

App Inventor’s File access component

In the Designer, under Storage, drag the File component to the user interface Design screen.  This adds a “non-visible component” at the bottom of the Designer canvas area.

In the Blocks view, scan down the list of blocks until you find File1 (you can  rename it to something else). You’ll find a set of functions for writing to files and reading from files.

This component can write text to files and read text from files. If you are familiar with other programming systems and concepts, this type of file and its use are called “sequential files”.  Since Comma Separated Values (CSV) files are a formatted version of text files, you can also convert lists into CSV rows and write those to the file, creating text files filled with data that can be read into spreadsheet programs.

Using App Inventor’s Official Documentation pages

Using App Inventor’s Official Documentation

App Inventor programming uses graphical components to layout program functionality. But the official App Inventor documentation uses a traditional programming textual description. When you reference the documentation you see a (mostly) textual description of “Properties”, “Methods” and “Events”.

In the App Inventor Designer, you should see a question mark inside a circle  next to each component (just to the right) in the Palette. Clicking on the question mark brings up a pop up dialog box with a brief description of the component. At the bottom is usually a “More information” hyper link. When you click on that link, documentation pages open in a new browser tab. And this is where you will see information described in “Properties”, “Methods” and “Events” sections.

Events

Inside App Inventor (and within Android) lie the concept of an “event driven” programming model and object oriented programming. The former is easy to understand: a “When xxx.Click Do” block describes what to do when an “event” occurs such as a user presses a button on the screen. That button push is an event.  Our program blocks respond to events – and specify what our program does when the event occurs.

Properties

You have seen properties on the Designer page – at the right hand side, you can change the color of buttons or change the text of a label. Each of these values is a “property” of the component.

The concept of a property is easy to understand by seeing how properties apply to every day objects.  A car might have the property “blue in color”.  A house might have a property “yellow in color”.  A dog might have a property like “breed is german shepherd” or “small dog” or “large dog”.

Real world objects can have multiple properties. For example, a car could be “blue in color”, “4 wheel drive”, “4 door” and “140 horsepower engine”. Each of these attributes is a property that helps to describe the car.

In App Inventor, each component may have a set of properties. For example, a button might be square or oval, or blue or gray in color. Each of these attributes is a property – for example, the color property might be set to “blue”.

Methods

“Methods” describe the actions or services the component can provide for a program. A method labeled “Start()” is an action that the component can perform.

Another way to describe “properties” and “methods” is to describe them in terms of human language – a property is like a noun “small”, “large”, “blue” (as in color) and a method is like a verb describing an action.

In this way, each component is an “object” that has properties and can provide services and perform an action (the methods).

In terms of real world objects, a car might have methods such as “start engine”, “stop engine”, “increase throttle”, “decrease throttle” and “set throttle” (to a specify speed).

Back to the Documentation

When you look at the App Inventor documentation online, you will see a list of properties, events and methods.

For example, the media player plays audio or sound. It has a property “Volume” set between 0 and 100 to adjust the player volume. And it has methods such as “Start()” to begin playing the sound and “Stop()” to end playing the sound.

Now that you know what “properties”, “events” and “methods” actually mean, you should find reading the documentation to be a bit easier!

App Inventor is the quick and easy way to write Android Apps

WP to LinkedIn Auto Publish Powered By : XYZScripts.com