App Inventor and HTML/JavaScript


How to read a text file with App Inventor

Note: with the new File component, which has been introduced in release nb133 on May, 18th 2014, this workaround is now obsolete. Thank you MIT!

Scott already found a solution to read a text file and display it using a trick to echo a file's contents from App Inventor to a php server and back. This solution here uses HTML with some JavaScript.

The example reads the text file import.txt which is stored as asset in App Inventor and displays its content in a label. The text was created using the text generator at www.lipsum.com.

Thank you Freek8! Your JavaScript example helped me to set up this solution.

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/read.html


Before packaging the app, use the production path.

file:///android_asset/read.html



Phantomfoot's modification of this example which imports a XML file you can find here.

You also might be interested in the following example: How to import a multiline csv file on first run of the app.

App Inventor Blocks

How does this work: The webviewer loads a HTML file containing the Javascript necessary to read the text file from the assets into the webviewer document title.

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

Screenshot


HTML/JavaScript

<!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>Read File</title>
</head>

<body>
  <script>
    // the filename is hardcoded to be able to read a textfile stored as asset in App Inventor
    var strFilename = "import.txt";

    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET",strFilename,false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseText;

    // print the result to the page title
    window.document.title= xmlDoc;
  </script>
</body>
</html>

Note

The limit to import a text file is around 2 MB (max. length of an URI).

Download


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
 

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 | Snippets | Tutorials | Extensions | Links | Search | Privacy Policy | Contact