Book Image

Android 3.0 Application Development Cookbook

By : Kyle Merrifield Mew
Book Image

Android 3.0 Application Development Cookbook

By: Kyle Merrifield Mew

Overview of this book

<p>Android is a mobile operating system that runs on a staggering number of smartphones and tablets. Android offers developers the ability to build extremely rich and innovative applications written using the Java programming language. Among the number of books that have been published on the topic, what&rsquo;s missing is a thoroughly practical, hands-on book that takes you straight to getting your job done without boring you with too much theory.<br /><br />Android 3.0 Application Development Cookbook will take you straight to the information you need to get your applications up and running. This book is written to provide you with the shortest possible route between an idea and a working application. <br /><br />Work through the book from start to finish to become an Android expert, or use it as a reference book by applying recipes directly to your project.<br /><br />This book covers every aspect of mobile app development, starting with major application components and screen layout and design, before moving on to how to manage sensors such as internal gyroscopes and near field communications. Towards the end, it delves into smartphone multimedia capabilities as well as graphics and animation, web access, and GPS. <br /><br />Whether you are writing your first app or your hundredth, this is a book that you will come back to time and time again, with its many tips and tricks on the rich features of Android 3.</p>
Table of Contents (18 chapters)
Android 3.0 Application Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Storing persistent activity data


Being able to store information about our activities on a temporary basis is very useful but more often than not we want our application to remember things across multiple sessions.

Obviously we can use an SQLite database, but this is a bit extreme if all we want to store the user's name or some preference or the other. Android provides a lightweight technique for doing this in the shape of the SharedPreferences interface.

Getting ready

It is possible to use SharedPreferences in any activity (as well as other application components). The example we use here makes use of a TextView, an EditText, and a Button to permanently store the user's name:

  1. Create a new project with these elements and provide them with IDs in the layout. Also edit the text value of the EditText and the Button but leave the TextView as it is.

  2. Connect these up in the Java code using findViewById(). In the code here we have named them mTextView, mEditText and mButton.

How to do it...

In this recipe the persistent data that we want to store is a string value used to represent the user's name. We will store this during the activity's onPause() method and restore the value in the onCreate() method (as they are called when we most likely need to restore and retrieve our preferences) but SharedPreferences can be applied anywhere:

  1. Declare a class-wide String field, mUserName and a String constant KEY with value null.

  2. Include the following lines in the onCreate() method after the findViewById() statements:

    SharedPreferences settings = getPreferences(MODE_PRIVATE);
    mUserName = settings.getString(KEY, "new user");
    mTextView.setText("Welcome " + mUserName);
  3. Override the onPause() method and complete it as shown here:

    @Override
      protected void onPause() {
      super.onPause();
      SharedPreferences settings = getPreferences(MODE_PRIVATE);
      SharedPreferences.Editor editor = settings.edit();
      editor.putString(KEY, mUserName);
      settings.edit().putString(KEY, mUserName).commit();
    }
  4. Add a button and a listener to the onCreate() method so that we can actually enter a value to be stored, as follows:

    mButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        mUserName = mEditText.getText().toString();
        mTextView.setText("Welcome " + mUserName);
      }
    });
  5. Run the application on a device or an emulator. Once a new value has been entered it will persist across sessions. In fact we would have to clear it using the device's Applications Manager in Settings, or uninstall and reinstall the application to completely reset it.

How it works...

We stored just one value here, the string KEY, but we could have stored any number of primitive name/value pairs. Each data type has equivalent getters and setters, for example SharedPreferences.getBoolean() or SharedPreferences.setInt().

When we retrieve the value, in the onCreate() method we provided a string literal "new user". This will be used in the absence of a stored value when the file has not yet been saved and is very useful for handling first-run events.

The saving of our preferences requires the services of the SharedPreferences.Editor. This is evoked with edit() and accepts remove() and clear() procedures as well as setters like the putString() one we used. Note that we must conclude any storing we do here with the commit() statement.

Note

It is worth bearing in mind that the use of SharedPreferences is slow, and when more than half a dozen or so values are needed it is worth considering more serious techniques of retaining an application's data such as a database or accessing the device's internal memory directly.

There's more...

There is a slightly more sophisticated variant of the getPreferences() accessor, getSharedPreferences(), which can be used for storing multiple preference sets.

Using more than one preference file

Using getSharedPreferences() is no different from its counterpart but it allows for more than one preference file. It takes the following form:

getSharedPreferences(String name, int mode)

Here name is the file and the mode can be one of MODE_PRIVATE, MODE_WORLD_READABLE or MODE_WORLD_WRITABLE and describe the file's access levels.

See also

To store more complex data, see the recipe Creating an SQLite database in Chapter 5, Data and Security.