Published: 04 Jul 2011
By: Dino Esposito

In this article, Dino Esposito focuses on the options that the Android SDK offers for local storage.

Contents [hide]

The Android for .NET Developers Series

  • Part 1 Starting with this article, I'll discuss what you need to know to approach Android programming without any aid from your .NET expertise.
  • Part 2 In this article, we'll go through an Android application that accepts input from the user and handles user's clicking.
  • Part 3 In this article, you will learn how to build the user interface.
  • Part 4 In this article, I'll be delving deep into menus and dialog boxes in Android for .NET, and discuss a few very common (and frequently used) types of menus and dialogs.
  • Part 5 In this article, Dino Esposito focuses on the options that the Android SDK offers for local storage.
  • Part 6 In this article, Dino Esposito shows how to build settings dialog boxes using a built-in feature of Android for .NET.
  • Part 7 In this article, I'll dissect the code of a realistic application - a waterpolo score manager - to show how to save and resume the status of a game using both the internal storage and SD card.
  • Part 8 In this article, I'll focus on the execution of common tasks from within an Android application. I'll build the skeleton of an application that takes a photo and emails to the specified address. For both tasks I'll use native Android components.
  • Part 9 In this article, I'll discuss how to arrange an Android view where the dominant element is the list. I'll start with a plain list of strings and then improve up to populating a listview with downloaded content arranged using a custom layout.
  • Part 10 In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.
  • Introduction

    Overall I believe that the most significant plus that native mobile applications have over mobile sites is the ability to work offline and cache data. I value this aspect even more than a better and richer user experience. (The ability of caching data can be coded in mobile pages through HTML5 capabilities for the mobile browsers that support it, but that's another story.) For a mobile native application caching data locally is a key asset. In this article, I'll just focus on the options that the Android SDK offers for local storage.

    Android and the Others

    The three major mobile operating systems (Android, iOS, Windows Phone) provide nearly the same set of storage capabilities. Check your enthusiasm: this doesn't mean that the same code, or just the same algorithms, can be reused across all the three platforms. More simply, it means that local storage develops around the same core options on the three platforms but each coded through a unique API.

    The local storage API of a mobile operating system offers a set of classes to save simple settings that can fit into a name/value string-based dictionary. This is the option you use for individual (and mostly primitive) values such as user preferences. A second option consists in an API to read and create text or binary files. The API is stream-based and allows you to store (and retrieve) data laid out in any format that fits your needs. In Windows Phone, this stream-based API is implemented through the isolated storage.

    Finally, when none of the above works well for your application, you may resort to local databases. Android and iOS come with a SQLite installation; Windows Phone works well with SQL Compact and SQLite as well. In Windows Phone, though, these are separate downloads. On Android, however, you also have the option of CouchDB - the mobile version of the popular document-based, NoSQL database.

    In this article, I'm going to cover the simplest of the three approaches - using a dictionary for simple name/value pairs. Before I come to the grips with the details of Android local storage, let me touch on the topic of custom dialog boxes. Custom dialog boxes are typically the user interface commodity through which the user enters settings to be saved locally. Let's see how to create a custom popup dialog box for data entry and how to persist any data captured in this way.

    Custom Dialog Boxes

    A custom dialog boxes is a view; as such, its content is fully described through an XML file created under the res/layout folder of the Android project. It should be noted that the name of a layout file must be lowercase and can't contain other than lowercase letters and digits. Needless to say, the file must have a .xml extension. Here's a sample layout file for a dialog box with two text boxes and a button.

    How do you bring this window up? There are two possible options. One entails that you use the showDialog method on the activity class that needs to use the dialog box. I prefer to go with a class that wraps up everything about the dialog box. Here's the code for a dialog-specific class:

    The class has three key aspects. In the constructor, you define the content of the dialog and set its title. Title-less dialogs are possible, but it requires that you instruct the Dialog class about that. You create the following XML style file in the res/values folder. The file name doesn't matter.

    Next, you explicitly set the style in the constructor of the dialog, as shown below.

    The constructor of the dialog class is also responsible for usual tasks such as attaching event handlers and saving references to widgets.

    Moving Data In and Out of Dialog Boxes

    The primary goal of a dialog box is collecting data for the application. Furthermore, the dialog box should also be initialized in some way so that it displays default data. Android allows doing both things through a custom interface like below:

    You associate each custom dialog box class with a similar interface and call methods from within the execution flow of the dialog. In OnCreate you call Initialize and receive input data from the caller. This data is used to initialize input fields in the dialog. In any click handlers expected to dismiss the dialog and process input, you call the Completed method. The Bundle object is a dictionary used to carry data around. The actual content depends on the nature and content of the dialog box. For example, the dialog box of Figure 1 contains two entries for the name of the playing teams - home and visitors.

    Figure 1: Display of a custom dialog box.

    Display of a custom dialog box.

    To invoke a dialog box, you just create a new instance of the custom class and tell it to show up. The constructor of the dialog box class accepts also an object that implements the communication interface for data transfer.

    Where would you place the code that updates the main user interface after the dialog is dismissed? This code can't follow the invocation of the method show. The flow is not synchronous so the code won't stop once show is invoked. You need to integrate any UI update code in the implementation of Completed in the event listener, as below:

    Now that we've seen how to pass and receive data from a custom dialog box, we're ready to delve into data serialization and persistence.

    Saving Data as Preferences

    For lightweight usage, the SharedPreferences object is more than appropriate and quite simple to use. For data that don't fit the dictionary model, you might want to try streams or relational SQLite tables. To save simple standalone values such as settings or preferences, you need an instance of the SharedPreferences object plus an ad hoc editor object if you are writing to it.

    Shared preferences are saved to an XML file with the given name. The visibility of the file depends on the second argument you specify. MODE_PRIVATE indicates that only the current application has access to the file. Other options are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE which would make the content visible to every application for just reading and/or writing.

    To save data, you also need an editor. Here's how to proceed:

    To write data to the system dictionary you use an API nearly identical to that of the Bundle class. The putString method takes a key and a value and updates the internal dictionary. When you commit the editor, data is written to an underlying XML file.

    Reading Data from Preferences

    A nice feature of the preferences API is that when it comes to reading you don't have to be worried about exceptions. There's no need to check whether the XML file really exists. You just try to read and provide default values should the read fail for whatever reasons.

    The SharedPreferences object supports a bunch of types natively. In addition to strings, you can read/write primitive data types such as int, long, float and Boolean.

    Summary

    For very simple, but quite common mobile scenarios, the native Android dictionary is useful and effective. In addition, it is also easy to use. This article only scratched the surface of the local storage topic, however. In my next article I'll discuss another cool feature you find in Android: system provided, XML-driven forms built around preferences. This means that you don't strictly need to write and integrate your own custom dialog boxes as long as the dictionary model works for your data. Stay tuned.

    The Android for .NET Developers Series

  • Part 1 Starting with this article, I'll discuss what you need to know to approach Android programming without any aid from your .NET expertise.
  • Part 2 In this article, we'll go through an Android application that accepts input from the user and handles user's clicking.
  • Part 3 In this article, you will learn how to build the user interface.
  • Part 4 In this article, I'll be delving deep into menus and dialog boxes in Android for .NET, and discuss a few very common (and frequently used) types of menus and dialogs.
  • Part 5 In this article, Dino Esposito focuses on the options that the Android SDK offers for local storage.
  • Part 6 In this article, Dino Esposito shows how to build settings dialog boxes using a built-in feature of Android for .NET.
  • Part 7 In this article, I'll dissect the code of a realistic application - a waterpolo score manager - to show how to save and resume the status of a game using both the internal storage and SD card.
  • Part 8 In this article, I'll focus on the execution of common tasks from within an Android application. I'll build the skeleton of an application that takes a photo and emails to the specified address. For both tasks I'll use native Android components.
  • Part 9 In this article, I'll discuss how to arrange an Android view where the dominant element is the list. I'll start with a plain list of strings and then improve up to populating a listview with downloaded content arranged using a custom layout.
  • Part 10 In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Dino Esposito

    Dino Esposito is one of the world's authorities on Web technology and software architecture. Dino published an array of books, most of which are considered state-of-the-art in their respective areas. His most recent books are “Microsoft ® .NET: Architecting Applications for the Enterprise” and “...

    This author has published 54 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Android for .NET Developers - Location and Maps
    In Windows Phone and iOS getting the current position of the device in terms of latitude and longitu...
    Android for .NET Developers - Using Web Views
    In this article, I'll show a native app that contains a web-based view. The great news is that HTML ...
    Android for .NET Developers - Building a Twitter Client
    In this article, I'll discuss the features and capabilities required by an Android application to ta...
    Developing a Hello World Java Application and Deploying it in Windows Azure - Part II
    In this article we will see the steps involved in deploying the WAR created in the first part of thi...
    Ref and Out (The Inside Story)
    Knowing the power of ref and out, a developer will certainly make full use of this feature of parame...

    You might also be interested in the following related blog posts


    Designer Support for One-Way navigations in Entity Framework 4 read more
    How To: Silverlight grid hierarchy load on demand using MVVM and RIA services read more
    Why VBA Still Makes Sense read more
    Ruminations on Multi-Tenant Data Architectures read more
    WPF Release History : Q2 2009 (version 2009.2.701) read more
    WPF Localization Guidance Paper Posted on CodePlex read more
    Software Consulting Customer's Bill of Rights read more
    EntityObject Class Constructors read more
    Silverlight 2 beta 2 Mega-FAQ read more
    Thinking about the EntityDataSource read more
    Top
     
     
     

    Please login to rate or to leave a comment.