Monday, 18 May 2015

MIT App Inventor - Reading and Writing a textfile

Textfiles

Getting information into and out of text files doesn't sound glamorous, but it's one of the most useful basic tools you can learn from any programming language. What I have here is a simple example that allows you to create and add to a text file called 'datastore.txt' and then read out information stored in that. Why might you want to do that? Well lets say you wanted to make a calendar program that notified you of particular events and/or times using notifications on your phone. A simple way of doing this would be to have all the information about alerts stored in a text file on your phone (you could event set up a button to download it from a website!), have your app read that information every day and figure out from it when to make alerts appear on your phone.
To get started you will need a 'File' element from the 'Storage' menu (but in the example above I've also included a textfield, label and a couple of buttons.)


In the code above we do 3 things:

  1. whenButton1.click - adds the text from the textbox to the file (append means 'add to the end of')
  2. whenButton2.click - reads all the information from the file
  3. gets the information read from the file and displays it on screen as the contents of the label field

Challenge:

Make a text file (either by making one and putting it on your android device or writing and app to make one) that contains a time (in seconds) followed by a comma followed by some text, like this:
     10000, "10 seconds have passed"
Then write a program to read this information, use the number to control the TimerInterval of a Timer element and the text to fill in the content of a notification box that appears after the TimerInterval has elapsed. (More info on the Notifier and Timer elements here). Good Luck!

No comments:

Post a Comment