Lab 1.3: Storage & WEB API

Overview

Most Android apps need to save data, even if only to save information about the app state during onPause() so the user’s progress is not lost. Most realistic apps need to save user settings and preferences. In this lab, we will learn how to store data in two ways, either simple key value pairs that can be used for simple app preferences , or  to store  arbitrary data in files.  Also, we will learn how to communicate to a web server through HTTP protocol and get results back using standard formats.

Saving Key-Value Sets

If you need  small collection of key-values pairs that you’d like to save, a good choice would be using the SharedPreferences APIs. As the name suggests, the main purpose is to save and retrieve app preferences quickly. SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by android framework and can be either private or shared.

We will write a simple app (with a button and EditText) that initially queries the value of a key named “name” or returns a default value if it doesn’t exist (i.e., not stored previously). Whenever we click the button, it reads an EditText string data and stores it with a key named “name”.

  • Start a new project with default settings (name it Lab-1.3 for example).
  • Create a simple layout containing an EditText and a button.
  • In your main Activity class, onCreate() method add:
  • Create a handler method inside the main activity class:
  •  In your layout_main.xml , link the method ‘savePref’ to to the button and Run the app. Try to close and open the application to check whether the values are actually stored. Make sure your app is not in the background.

Note: If you create a shared preferences file with MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE, then any other apps that know the file identifier can access your data.

Files

Android uses a file system that’s similar to disk-based file systems on other platforms. We will learn how to work with the Android file system to read and write files with the File APIs.

All Android devices have two file storage areas: “internal” and “external” storage. These names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage), plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into “internal” and “external” partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not. The following lists summarize the facts about each storage space.

Internal storage:

  • It’s always available.
  • Files saved here are accessible by only your app by default.
  • When the user uninstalls your app, the system removes all your app’s files from internal storage.

Internal storage is best when you want to be sure that neither the user nor other apps can access your files.

External storage:

  • It’s not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.
  • It’s world-readable, so files saved here may be read outside of your control.
  • When the user uninstalls your app, the system removes your app’s files from here only if you save them in the directory from getExternalFilesDir().

External storage is the best place for files that don’t require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.

In this lab, we will learn how to read/write internal files. Here are some File operations.

  • Now, create one more EditText view and two buttons. We will use one button to store the data entered from the EditText in a file called myfile, and the other button to load back the stored content to the EditText.
  • In main activity class, create two functions, load() and store(). Try to understand the following code and do not just copy it (check android reference if your are not familiar with any class (say Log):

  • Link the two new buttons to the above function and run your application.
To learn further about how to store files on external storage, check android site. If you decide to store in external storage,  you should be aware that the file content is visible to other applications to read, hence, application sensitive data should not be stored in external storage.
Note that you can also store data in android SQLite server. Read this simple tutorial, if interested.

 

Connecting to the Web

We will learn how perform an HTTP GET request to download some XML content from a given URL. Remember that in HTTP GET requests, you can simply send parameters prefixed by  ‘?’ (e.g., URL= “http://example.com/read.php?”param1=value1”). In Web API, this can be used to tune a search value, for instance. If a server is configured properly (or RESTfuly), a simple URL call (e.g., “http://example.com/read/value1”) will correspond to an exact data we need to search for rather than giving search options. It is just an architectural methodology as you have read in the pre-lab. In the pre-lab, you have read that GET is used to read and POST to write some data. For brevity, we shall focus in this section on GET requests. You may find some POST tutorial online.

Since HTTP requests may take some time, we need to do it asynchronously in a different thread. A simple way to do multi-threading in android is extending  a class by AsyncTask which provides one of the simplest ways to fire off a new task from the UI thread.

  • In the layout, add a TextView (to show downloaded web file) and a button (to perform HTTP GET request).
  • Add a couple of permission in AndroidManifist.xml, otherwise android OS will not allow the app accessing network resources which will result a run time exception.

  • create a method named getResponse() to handle button on click event. In the method, first check whether there is internet connection is up or down.

  • Create a nested class in MainActivity that extends AsyncTask.

  •  This class will run as a separate thread than UI. It has two main methods, one for doing the asynchronous task in the background, and one task after finishing the asynchronous task which runs in the activity UI thread. In the function getResponse(), we create an object of DownloadWebpageText class and call execute() method to fork a new thread. AsyncTask automatically calls doInBackground() method, and upon completion, onPostExecute() is called, where the result is displayed.
  • Now we will implement downloadUrl() method which deals with HTTP requests. The code is self-explanatory  

  • Run your application. You should see some XML appear after sometime. Make sure you internet is running on your device.

The content type for most of Web APIs are either XML or JSON (simple syntax used for javascript objects) . You need to use some parser or write your own to get the respective information. Check with google APIs (You need to sign in with google acount), you can quary web, search for books, translate text using simple HTTP requests.

Try to replace the URL in the above code with (“https://www.googleapis.com/books/v1/volumes?q=hurry+potter“). Here you can search information about a hurry potter book and you will get the result in JSON format.

You may explore later more services in Google API such as Google Cloud Messaging for Android which allows to send (using POST requests) light weight device to device and server to device messages.

Lab Exercise 1.3

Search in the web for any Web API that returns data in either XML or JSON format. Create a simple application that reads from the source you chose, previews in appropriate textViews (not xml or json dump) and then stores the data in internal storage. If the app launches again, it reads from the storage and previews again. If the user clicks a refresh button, the data should be renewed from the web, and the new data shall be stored again. Make sure the XML or JSON data is read completely and then parsed using appropriate libraries (or by manually). Notice that the above downloadURL method only reads 500 characters; modify the code to read the entire file, otherwise you might get parsing errors.

 

  • The exercise should be done individually.
  • Copy the final exercise files into “lab-1.3” directory.
  • Add, commit, and push your changes to the remote server
  • The deadline is before the next lab.