Please note that the contents of this offline web site may be out of date. To access the most recent documentation visit the online version .
Note that links that point to online resources are green in color and will open in a new window.
We would love it if you could give us feedback about this material by filling this form (You have to be online to fill it)
Android APIs
public abstract class

PreferenceActivity

extends ListActivity
implements PreferenceFragment.OnPreferenceStartFragmentCallback
java.lang.Object
   ↳ android.content.Context
     ↳ android.content.ContextWrapper
       ↳ android.view.ContextThemeWrapper
         ↳ android.app.Activity
           ↳ android.app.ListActivity
             ↳ android.preference.PreferenceActivity

Class Overview

This is the base class for an activity to show a hierarchy of preferences to the user. Prior to HONEYCOMB this class only allowed the display of a single set of preference; this functionality should now be found in the new PreferenceFragment class. If you are using PreferenceActivity in its old mode, the documentation there applies to the deprecated APIs here.

This activity shows one or more headers of preferences, each of which is associated with a PreferenceFragment to display the preferences of that header. The actual layout and display of these associations can however vary; currently there are two major approaches it may take:

  • On a small screen it may display only the headers as a single list when first launched. Selecting one of the header items will re-launch the activity with it only showing the PreferenceFragment of that header.
  • On a large screen in may display both the headers and current PreferenceFragment together as panes. Selecting a header item switches to showing the correct PreferenceFragment for that item.

Subclasses of PreferenceActivity should implement )">onBuildHeaders(List ) to populate the header list with the desired items. Doing this implicitly switches the class into its new "headers + fragments" mode rather than the old style of just showing a single preferences list.

Developer Guides

For information about using PreferenceActivity , read the Settings guide.

Sample Code

The following sample code shows a simple preference activity that has two different sets of preferences. The implementation, consisting of the activity itself as well as its two preference fragments is:

       public class PreferenceWithHeaders extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Add a button to the header list.
        if (hasHeaders()) {
            Button button = new Button(this);
            button.setText("Some action");
            setListFooter(button);
        }
    }

    /**
     * Populate the activity with the top-level headers.
     */
    @Override
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    /**
     * This fragment shows the preferences for the first header.
     */
    public static class Prefs1Fragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Make sure default values are applied.  In a real app, you would
            // want this in a shared function that is used to retrieve the
            // SharedPreferences wherever they are needed.
            PreferenceManager.setDefaultValues(getActivity(),
                    R.xml.advanced_preferences, false);

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_preferences);
        }
    }

    /**
     * This fragment contains a second-level set of preference that you
     * can get to by tapping an item in the first preferences fragment.
     */
    public static class Prefs1FragmentInner extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Can retrieve arguments from preference XML.
            Log.i("args", "Arguments: " + getArguments());

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_preferences_inner);
        }
    }

    /**
     * This fragment shows the preferences for the second header.
     */
    public static class Prefs2Fragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Can retrieve arguments from headers XML.
            Log.i("args", "Arguments: " + getArguments());

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.preference_dependencies);
        }
    }
}
      

The preference_headers resource describes the headers to be displayed and the fragments associated with them. It is:

        <preference-headers
        xmlns:android="http://schemas.android.com/apk/res/android">

    <header android:fragment="com.example.android.apis.preference.PreferenceWithHeaders$Prefs1Fragment"
            android:icon="@drawable/ic_settings_applications"
            android:title="Prefs 1"
            android:summary="An example of some preferences." />

    <header android:fragment="com.example.android.apis.preference.PreferenceWithHeaders$Prefs2Fragment"
            android:icon="@drawable/ic_settings_display"
            android:title="Prefs 2"
            android:summary="Some other preferences you can see.">
        <!-- Arbitrary key/value pairs can be included with a header as
             arguments to its fragment. -->
        <extra android:name="someKey" android:value="someHeaderValue" />
    </header>

    <header android:icon="@drawable/ic_settings_display"
            android:title="Intent"
            android:summary="Launches an Intent.">
        <intent android:action="android.intent.action.VIEW"
                android:data="http://www.android.com" />
    </header>

</preference-headers>
       

The first header is shown by Prefs1Fragment, which populates itself from the following XML resource:

       <PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
            android:title="@string/inline_preferences">

        <CheckBoxPreference
                android:key="checkbox_preference"
                android:title="@string/title_checkbox_preference"
                android:summary="@string/summary_checkbox_preference" />

    </PreferenceCategory>

    <PreferenceCategory
            android:title="@string/dialog_based_preferences">

        <EditTextPreference
                android:key="edittext_preference"
                android:title="@string/title_edittext_preference"
                android:summary="@string/summary_edittext_preference"
                android:dialogTitle="@string/dialog_title_edittext_preference" />

        <ListPreference
                android:key="list_preference"
                android:title="@string/title_list_preference"
                android:summary="@string/summary_list_preference"
                android:entries="@array/entries_list_preference"
                android:entryValues="@array/entryvalues_list_preference"
                android:dialogTitle="@string/dialog_title_list_preference" />

    </PreferenceCategory>

    <PreferenceCategory
            android:title="@string/launch_preferences">

        <!-- This PreferenceScreen tag sends the user to a new fragment of
             preferences.  If running in a large screen, they can be embedded
             inside of the overall preferences UI. -->
        <PreferenceScreen
                android:fragment="com.example.android.apis.preference.PreferenceWithHeaders$Prefs1FragmentInner"
                android:title="@string/title_fragment_preference"
                android:summary="@string/summary_fragment_preference">
            <!-- Arbitrary key/value pairs can be included for fragment arguments -->
            <extra android:name="someKey" android:value="somePrefValue" />
        </PreferenceScreen>

        <!-- This PreferenceScreen tag sends the user to a completely different
             activity, switching out of the current preferences UI. -->
        <PreferenceScreen
                android:title="@string/title_intent_preference"
                android:summary="@string/summary_intent_preference">

            <intent android:action="android.intent.action.VIEW"
                    android:data="http://www.android.com" />

        </PreferenceScreen>

    </PreferenceCategory>

    <PreferenceCategory
            android:title="@string/preference_attributes">

        <CheckBoxPreference
                android:key="parent_checkbox_preference"
                android:title="@string/title_parent_preference"
                android:summary="@string/summary_parent_preference" />

        <!-- The visual style of a child is defined by this styled theme attribute. -->
        <CheckBoxPreference
                android:key="child_checkbox_preference"
                android:dependency="parent_checkbox_preference"
                android:layout="?android:attr/preferenceLayoutChild"
                android:title="@string/title_child_preference"
                android:summary="@string/summary_child_preference" />

    </PreferenceCategory>

</PreferenceScreen>
      

Note that this XML resource contains a preference screen holding another fragment, the Prefs1FragmentInner implemented here. This allows the user to traverse down a hierarchy of preferences; pressing back will pop each fragment off the stack to return to the previous preferences.

See PreferenceFragment for information on implementing the fragments themselves.

Summary

Nested Classes
class PreferenceActivity.Header Description of a single Header item that the user can select. 
Constants
String EXTRA_NO_HEADERS When starting this activity, the invoking Intent can contain this extra boolean that the header list should not be displayed.
String EXTRA_SHOW_FRAGMENT When starting this activity, the invoking Intent can contain this extra string to specify which fragment should be initially displayed.
String EXTRA_SHOW_FRAGMENT_ARGUMENTS When starting this activity and using EXTRA_SHOW_FRAGMENT , this extra can also be specified to supply a Bundle of arguments to pass to that fragment when it is instantiated during the initial creation of PreferenceActivity.
String EXTRA_SHOW_FRAGMENT_SHORT_TITLE When starting this activity and using EXTRA_SHOW_FRAGMENT , this extra can also be specify to supply the short title to be shown for that fragment.
String EXTRA_SHOW_FRAGMENT_TITLE When starting this activity and using EXTRA_SHOW_FRAGMENT , this extra can also be specify to supply the title to be shown for that fragment.
long HEADER_ID_UNDEFINED Default value for Header.id indicating that no identifier value is set.
[Expand]
Inherited Constants
From class android.app.Activity
From class android.content.Context
From interface android.content.ComponentCallbacks2
[Expand]
Inherited Fields
From class android.app.Activity
Public Constructors
PreferenceActivity ()
Public Methods
void addPreferencesFromIntent ( Intent intent)
This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.
void addPreferencesFromResource (int preferencesResId)
This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.
Preference findPreference ( CharSequence key)
This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.
void finishPreferencePanel ( Fragment caller, int resultCode, Intent resultData)
Called by a preference panel fragment to finish itself.
PreferenceManager getPreferenceManager ()
This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.
PreferenceScreen getPreferenceScreen ()
This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.
boolean hasHeaders ()
Returns true if this activity is currently showing the header list.
void invalidateHeaders ()
Call when you need to change the headers being displayed.
boolean isMultiPane ()
Returns true if this activity is showing multiple panes -- the headers and a preference fragment.
void )">loadHeadersFromResource (int resid, List < PreferenceActivity.Header > target)
Parse the given XML file as a header description, adding each parsed Header into the target list.
void )">onBuildHeaders ( List < PreferenceActivity.Header > target)
Called when the activity needs its list of headers build.
Intent onBuildStartFragmentIntent ( String fragmentName, Bundle args, int titleRes, int shortTitleRes)
Called by startWithFragment(String, Bundle, Fragment, int, int, int) when in single-pane mode, to build an Intent to launch a new activity showing the selected fragment.
void onContentChanged ()
Updates the screen state (current list and other views) when the content changes.
PreferenceActivity.Header onGetInitialHeader ()
Called to determine the initial header to be shown.
PreferenceActivity.Header onGetNewHeader ()
Called after the header list has been updated ( )">onBuildHeaders(List ) has been called and returned due to invalidateHeaders() ) to specify the header that should now be selected.
void onHeaderClick ( PreferenceActivity.Header header, int position)
Called when the user selects an item in the header list.
boolean onIsHidingHeaders ()
Called to determine whether the header list should be hidden.
boolean onIsMultiPane ()
Called to determine if the activity should run in multi-pane mode.
boolean onPreferenceStartFragment ( PreferenceFragment caller, Preference pref)
Called when the user has clicked on a Preference that has a fragment class name associated with it.
boolean onPreferenceTreeClick ( PreferenceScreen preferenceScreen, Preference preference)
This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.
void setListFooter ( View view)
Set a footer that should be shown at the bottom of the header list.
void setParentTitle ( CharSequence title, CharSequence shortTitle, View.OnClickListener listener)
Should be called after onCreate to ensure that the breadcrumbs, if any, were created.
void setPreferenceScreen ( PreferenceScreen preferenceScreen)
This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.
void showBreadCrumbs ( CharSequence title, CharSequence shortTitle)
Change the base title of the bread crumbs for the current preferences.
void startPreferenceFragment ( Fragment fragment, boolean push)
Start a new fragment.
void startPreferencePanel ( String fragmentClass, Bundle args, int titleRes, CharSequence titleText, Fragment resultTo, int resultRequestCode)
Start a new fragment containing a preference panel.
void startWithFragment ( String fragmentName, Bundle args, Fragment resultTo, int resultRequestCode)
void startWithFragment ( String fragmentName, Bundle args, Fragment resultTo, int resultRequestCode, int titleRes, int shortTitleRes)
Start a new instance of this activity, showing only the given preference fragment.
void switchToHeader ( PreferenceActivity.Header header)
When in two-pane mode, switch to the fragment pane to show the given preference fragment.
void switchToHeader ( String fragmentName, Bundle args)
When in two-pane mode, switch the fragment pane to show the given preference fragment.
Protected Methods
boolean isValidFragment ( String fragmentName)
Subclasses should override this method and verify that the given fragment is a valid type to be attached to this activity.
void onActivityResult (int requestCode, int resultCode, Intent data)
Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it.
void onCreate ( Bundle savedInstanceState)
Called when the activity is starting.
void onDestroy ()
Perform any final cleanup before an activity is destroyed.
void onListItemClick ( ListView l, View v, int position, long id)
This method will be called when an item in the list is selected.
void onNewIntent ( Intent intent)
This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent) .
void onRestoreInstanceState ( Bundle state)
Ensures the list view has been created before Activity restores all of the view states.
void onSaveInstanceState ( Bundle outState)
Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).
void onStop ()
Called when you are no longer visible to the user.
[Expand]
Inherited Methods
From class android.app.ListActivity
From class android.app.Activity
From class android.view.ContextThemeWrapper
From class android.content.ContextWrapper
From class android.content.Context
From class java.lang.Object
From interface android.content.ComponentCallbacks
From interface android.content.ComponentCallbacks2
From interface android.preference.PreferenceFragment.OnPreferenceStartFragmentCallback
From interface android.view.KeyEvent.Callback
From interface android.view.LayoutInflater.Factory
From interface android.view.LayoutInflater.Factory2
From interface android.view.View.OnCreateContextMenuListener
From interface android.view.Window.Callback

Constants

public static final String EXTRA_NO_HEADERS

When starting this activity, the invoking Intent can contain this extra boolean that the header list should not be displayed. This is most often used in conjunction with EXTRA_SHOW_FRAGMENT to launch the activity to display a specific fragment that the user has navigated to.

Constant Value: ":android:no_headers"

public static final String EXTRA_SHOW_FRAGMENT

When starting this activity, the invoking Intent can contain this extra string to specify which fragment should be initially displayed.

Starting from Key Lime Pie, when this argument is passed in, the PreferenceActivity will call isValidFragment() to confirm that the fragment class name is valid for this activity.

Constant Value: ":android:show_fragment"

public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS

When starting this activity and using EXTRA_SHOW_FRAGMENT , this extra can also be specified to supply a Bundle of arguments to pass to that fragment when it is instantiated during the initial creation of PreferenceActivity.

Constant Value: ":android:show_fragment_args"

public static final String EXTRA_SHOW_FRAGMENT_SHORT_TITLE

When starting this activity and using EXTRA_SHOW_FRAGMENT , this extra can also be specify to supply the short title to be shown for that fragment.

Constant Value: ":android:show_fragment_short_title"

public static final String EXTRA_SHOW_FRAGMENT_TITLE

When starting this activity and using EXTRA_SHOW_FRAGMENT , this extra can also be specify to supply the title to be shown for that fragment.

Constant Value: ":android:show_fragment_title"

public static final long HEADER_ID_UNDEFINED

Default value for Header.id indicating that no identifier value is set. All other values (including those below -1) are valid.

Constant Value: -1 (0xffffffffffffffff)

Public Constructors

public PreferenceActivity ()

Added in API level 1

Public Methods

public void addPreferencesFromIntent ( Intent intent)

Added in API level 1

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Adds preferences from activities that match the given Intent .

Parameters
intent The Intent to query activities.

public void addPreferencesFromResource (int preferencesResId)

Added in API level 1

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Inflates the given XML resource and adds the preference hierarchy to the current preference hierarchy.

Parameters
preferencesResId The XML resource ID to inflate.

public Preference findPreference ( CharSequence key)

Added in API level 1

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Finds a Preference based on its key.

Parameters
key The key of the preference to retrieve.
Returns

public void finishPreferencePanel ( Fragment caller, int resultCode, Intent resultData)

Called by a preference panel fragment to finish itself.

Parameters
caller The fragment that is asking to be finished.
resultCode Optional result code to send back to the original launching fragment.
resultData Optional result data to send back to the original launching fragment.

public PreferenceManager getPreferenceManager ()

Added in API level 1

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Returns the PreferenceManager used by this activity.

Returns

public PreferenceScreen getPreferenceScreen ()

Added in API level 1

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Gets the root of the preference hierarchy that this activity is showing.

Returns

public boolean hasHeaders ()

Returns true if this activity is currently showing the header list.

public void invalidateHeaders ()

Call when you need to change the headers being displayed. Will result in onBuildHeaders() later being called to retrieve the new list.

public boolean isMultiPane ()

Returns true if this activity is showing multiple panes -- the headers and a preference fragment.

)">

public void loadHeadersFromResource (int resid, List < PreferenceActivity.Header > target)

Parse the given XML file as a header description, adding each parsed Header into the target list.

Parameters
resid The XML resource to load and parse.
target The list in which the parsed headers should be placed.
)">

public void onBuildHeaders ( List < PreferenceActivity.Header > target)

Called when the activity needs its list of headers build. By implementing this and adding at least one item to the list, you will cause the activity to run in its modern fragment mode. Note that this function may not always be called; for example, if the activity has been asked to display a particular fragment without the header list, there is no need to build the headers.

Typical implementations will use )">loadHeadersFromResource(int, List ) to fill in the list from a resource.

Parameters
target The list in which to place the headers.

public Intent onBuildStartFragmentIntent ( String fragmentName, Bundle args, int titleRes, int shortTitleRes)

Called by startWithFragment(String, Bundle, Fragment, int, int, int) when in single-pane mode, to build an Intent to launch a new activity showing the selected fragment. The default implementation constructs an Intent that re-launches the current activity with the appropriate arguments to display the fragment.

Parameters
fragmentName The name of the fragment to display.
args Optional arguments to supply to the fragment.
titleRes Optional resource ID of title to show for this item.
shortTitleRes Optional resource ID of short title to show for this item.
Returns
  • Returns an Intent that can be launched to display the given fragment.

public void onContentChanged ()

Added in API level 1

Updates the screen state (current list and other views) when the content changes.

public PreferenceActivity.Header onGetInitialHeader ()

Called to determine the initial header to be shown. The default implementation simply returns the fragment of the first header. Note that the returned Header object does not actually need to exist in your header list -- whatever its fragment is will simply be used to show for the initial UI.

public PreferenceActivity.Header onGetNewHeader ()

Called after the header list has been updated ( )">onBuildHeaders(List ) has been called and returned due to invalidateHeaders() ) to specify the header that should now be selected. The default implementation returns null to keep whatever header is currently selected.

public void onHeaderClick ( PreferenceActivity.Header header, int position)

Called when the user selects an item in the header list. The default implementation will call either startWithFragment(String, Bundle, Fragment, int, int, int) or switchToHeader(Header) as appropriate.

Parameters
header The header that was selected.
position The header's position in the list.

public boolean onIsHidingHeaders ()

Called to determine whether the header list should be hidden. The default implementation returns the value given in EXTRA_NO_HEADERS or false if it is not supplied. This is set to false, for example, when the activity is being re-launched to show a particular preference activity.

public boolean onIsMultiPane ()

Called to determine if the activity should run in multi-pane mode. The default implementation returns true if the screen is large enough.

public boolean onPreferenceStartFragment ( PreferenceFragment caller, Preference pref)

Called when the user has clicked on a Preference that has a fragment class name associated with it. The implementation to should instantiate and switch to an instance of the given fragment.

public boolean onPreferenceTreeClick ( PreferenceScreen preferenceScreen, Preference preference)

Added in API level 1

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

public void setListFooter ( View view)

Set a footer that should be shown at the bottom of the header list.

public void setParentTitle ( CharSequence title, CharSequence shortTitle, View.OnClickListener listener)

Should be called after onCreate to ensure that the breadcrumbs, if any, were created. This prepends a title to the fragment breadcrumbs and attaches a listener to any clicks on the parent entry.

Parameters
title the title for the breadcrumb
shortTitle the short title for the breadcrumb

public void setPreferenceScreen ( PreferenceScreen preferenceScreen)

Added in API level 1

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Sets the root of the preference hierarchy that this activity is showing.

Parameters
preferenceScreen The root PreferenceScreen of the preference hierarchy.

public void showBreadCrumbs ( CharSequence title, CharSequence shortTitle)

Change the base title of the bread crumbs for the current preferences. This will normally be called for you. See FragmentBreadCrumbs for more information.

public void startPreferenceFragment ( Fragment fragment, boolean push)

Start a new fragment.

Parameters
fragment The fragment to start
push If true, the current fragment will be pushed onto the back stack. If false, the current fragment will be replaced.

public void startPreferencePanel ( String fragmentClass, Bundle args, int titleRes, CharSequence titleText, Fragment resultTo, int resultRequestCode)

Start a new fragment containing a preference panel. If the preferences are being displayed in multi-pane mode, the given fragment class will be instantiated and placed in the appropriate pane. If running in single-pane mode, a new activity will be launched in which to show the fragment.

Parameters
fragmentClass Full name of the class implementing the fragment.
args Any desired arguments to supply to the fragment.
titleRes Optional resource identifier of the title of this fragment.
titleText Optional text of the title of this fragment.
resultTo Optional fragment that result data should be sent to. If non-null, resultTo.onActivityResult() will be called when this preference panel is done. The launched panel must use finishPreferencePanel(Fragment, int, Intent) when done.
resultRequestCode If resultTo is non-null, this is the caller's request code to be received with the resut.

public void startWithFragment ( String fragmentName, Bundle args, Fragment resultTo, int resultRequestCode)

public void startWithFragment ( String fragmentName, Bundle args, Fragment resultTo, int resultRequestCode, int titleRes, int shortTitleRes)

Start a new instance of this activity, showing only the given preference fragment. When launched in this mode, the header list will be hidden and the given preference fragment will be instantiated and fill the entire activity.

Parameters
fragmentName The name of the fragment to display.
args Optional arguments to supply to the fragment.
resultTo Option fragment that should receive the result of the activity launch.
resultRequestCode If resultTo is non-null, this is the request code in which to report the result.
titleRes Resource ID of string to display for the title of this set of preferences.
shortTitleRes Resource ID of string to display for the short title of this set of preferences.

public void switchToHeader ( PreferenceActivity.Header header)

When in two-pane mode, switch to the fragment pane to show the given preference fragment.

Parameters
header The new header to display.

public void switchToHeader ( String fragmentName, Bundle args)

When in two-pane mode, switch the fragment pane to show the given preference fragment.

Parameters
fragmentName The name of the fragment to display.
args Optional arguments to supply to the fragment.

Protected Methods

protected boolean isValidFragment ( String fragmentName)

Subclasses should override this method and verify that the given fragment is a valid type to be attached to this activity. The default implementation returns true for apps built for android:targetSdkVersion older than KITKAT . For later versions, it will throw an exception.

Parameters
fragmentName the class name of the Fragment about to be attached to this activity.
Returns
  • true if the fragment class name is valid for this Activity and false otherwise.

protected void onActivityResult (int requestCode, int resultCode, Intent data)

Added in API level 1

Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

You will receive this call immediately before onResume() when your activity is re-starting.

Parameters
requestCode The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
resultCode The integer result code returned by the child activity through its setResult().
data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").

protected void onCreate ( Bundle savedInstanceState)

Added in API level 1

Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri, String[], String, String[], String) to retrieve cursors for data being displayed, etc.

You can call finish() from within this function, in which case onDestroy() will be immediately called without any of the rest of the activity lifecycle ( onStart() , onResume() , onPause() , etc) executing.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

Parameters
savedInstanceState If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle) . Note: Otherwise it is null.

protected void onDestroy ()

Added in API level 1

Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle) , not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

protected void onListItemClick ( ListView l, View v, int position, long id)

Added in API level 1

This method will be called when an item in the list is selected. Subclasses should override. Subclasses can call getListView().getItemAtPosition(position) if they need to access the data associated with the selected item.

Parameters
l The ListView where the click happened
v The view that was clicked within the ListView
position The position of the view in the list
id The row id of the item that was clicked

protected void onNewIntent ( Intent intent)

Added in API level 1

This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent) . In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.

An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.

Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.

Parameters
intent The new intent that was started for the activity.

protected void onRestoreInstanceState ( Bundle state)

Added in API level 1

Ensures the list view has been created before Activity restores all of the view states.

Parameters
state the data most recently supplied in onSaveInstanceState(Bundle) .

protected void onSaveInstanceState ( Bundle outState)

Added in API level 1

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle) .

Do not confuse this method with activity lifecycle callbacks such as onPause() , which is always called when an activity is being placed in the background or on its way to destruction, or onStop() which is called before destruction. One example of when onPause() and onStop() is called and not this method is when a user navigates back from activity B to activity A: there is no need to call onSaveInstanceState(Bundle) on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause() is called and not onSaveInstanceState(Bundle) is when activity B is launched in front of activity A: the system may avoid calling onSaveInstanceState(Bundle) on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.

The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(Bundle) ). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

If called, this method will occur before onStop() . There are no guarantees about whether it will occur before or after onPause() .

Parameters
outState Bundle in which to place your saved state.

protected void onStop ()

Added in API level 1

Called when you are no longer visible to the user. You will next receive either onRestart() , onDestroy() , or nothing, depending on later user activity.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.