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 an activity's state


A smart phone is a dynamic environment for software to exist in and an application can be interrupted for any number of reasons. Even turning the handset on its side will cause an activity to reload in orientation sensitive programs.

Android provides SQLite for storing and retrieving data but this would a little heavy handed for storing an instance value or two and fortunately the activity class has built-in methods that we can override and use to store primitive name or value pairs.

Getting ready

Our recipes get a little more involved from here on and so we will not be able to include all the code in the given examples. We will assume that the reader is familiar with the subjects covered in the past few recipes and will be able to create applications with the necessary elements without recourse to the exact text. If not, have a quick look through the preceding recipes. We will not introduce any new subjects without fully explaining them.

  1. Create a new application project and call it StateSaver.

  2. Include these elements within the main.xml layout file:

    • An EditText

    • A Button

    • A TextView

  3. Provide them with the following android:ids:

    • @+id/edit_text

    • @+id/button

    • @+id/text_view

  4. Change the text in the boxes to match the following screenshot:

How to do it...

In this recipe we will create a simple application that 'remembers' a line of text that we enter when the activity is reloaded. To do this we override the activity's onSaveInstanceState() and onRestoreInstanceState() methods:

  1. Declare the three UI elements that we just created as class-wide fields in the activity Java file, as follows:

    public class StateSaver extends Activity {
      private EditText mEditText;
      private Button mButton;
      private TextView mTextView;
  2. We also need a String constant:

      private static final String KEY = null;
  3. Inside the onCreate() method and after the setContentView() statement associate these views with their Resource IDs:

    mEditText = (EditText) findViewById(R.id.edit_text);
    mButton = (Button) findViewById(R.id.button);
    mTextView = (TextView) findViewById(R.id.text_view);
  4. Create a click listener for our button (also inside onCreate()):

    mButton.setOnClickListener(new OnClickListener() {
    
      @Override
      public void onClick(View v) {
        mTextView.setText(mEditText.getText().toString);
      }
    });
  5. Now is a good time to import any libraries. Pressing Shift + Ctrl + O will cause Eclipse to offer you a choice between android.view.View.OnClickListener and android.content.DialogInterface.OnClickListener. Make sure that you select android.view.View.

  6. Beneath the onCreate()method, add the onSaveInstanceState() method:

    @Override
    public void onSaveInstanceState(Bundle state) {
      state.putString(KEY, mTextView.getText().toString());
      super.onSaveInstanceState(state);
    }
  7. Beneath this last method, include the onRestoreInstanceState() method:

    @Override
    public void onRestoreInstanceState(Bundle state) {
      super.onRestoreInstanceState(state);
      mTextView.setText(state.getString(KEY));
    }
  8. Run the project on a device or emulator. Enter some text into the EditText view and click on the button. Then restart the activity by exiting and restarting or by rotating the handset. When the activity begins afresh, the TextView restores to its remembered state.

How it works...

The way these state saving methods work is really quite simple. When our application is dropped from memory, a Bundle of name/value pairs can be stored with the onSaveInstanceState() method. This Bundle is then handed back when the activity restarts to both the onRestoreInstanceState() and the onCreate() methods. This is an important point as the Bundle is made available to both procedures and gives us a choice over where and how to handle activity restarts. This is because onRestoreInstanceState() is not called until after onStart() meaning we can apply any initialization that we may need before restoring our values.

There's more...

The two methods introduced here are not the only way to ensure that a screen component's state is stored.

Using ID to include a view in the Bundle

Android will automatically include any view that has been supplied with an ID in the saved instance state Bundle when the activity is interrupted, regardless of whether we have included the two methods discussed here.

See also

Internal memory can also be used to store other private data and details on how to do this can be found in the recipe Using internal storage for private data in Chapter 5, Data and Security.

The recipe Storing public data on external storage in Chapter 5, Data and Security demonstrates how to use SD cards to store data available from outside an application.