Archive

Posts Tagged ‘activity’

How to create a new Android activity

August 25th, 2009 2 comments

(Android phone – how-to/example)

The Android development paradigm introduces for the developer the “Activity”: <> During development you will find it easy to wrap-up parts of the functionality of your code into independent activities, with their own life cycle. More about activity life cycle on the Android developers website.

Easy (just start activity)
Assume you have the MainActivity, and a SecondaryActivity you want to start, this may be done in the easiest way:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName(this, SecondaryActivity.class.getName());
startActivity(intent);

Medium (pass some params as well)
Now imagine you want to pass some data to the new intent. You will achieve this using the Bundle class, to encapsulate your data. Example:

Intent intent = new Intent();
Bundle bun = new Bundle();

bun.putString(”param_string”, “the actual string”); // add two parameters: a string and a boolean
bun.putBoolean(”param_bool”, true);

intent.setClass(this, SecondaryActivity.class);
intent.putExtras(bun);
startActivity(intent);

In the SecondaryActivity, you will need to access these params. This is how:

Bundle bun = getIntent().getExtras();
String param1 = bun.getString(”param_string”);
boolean param2 = bun.getBoolean(”param_bool”);

Advanced (return some data)
So we passed some parameters to the SecondaryActivity, but let’s assume we want some results as well. From MainActivity one will pack parameters and all others like in the examples above, and than one will call SecondaryActivity as follows:

startActivityForResult(intent, R.id.secondaryactivity_finished);

where secondaryactivity_finished is just some id, that the MainActivity will be looking for in it’s onActivityResult, as follows:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
     switch(requestCode)
     {
         case R.id.secondaryactivity_finished:
         if (resultCode == RESULT_OK)
         {
         Bundle res = data.getExtras();
         String result = res.getString(”param_result”);
         }
         break;
     } // end switch
}

In onActivityResult, one simply follows the activities that returned and their error/success codes, and as in the example above may get data passed by the SecondaryActivity. In our case SecondaryActivity returned a string under the name “param_result”.

On the other side, in SecondaryActivity, one will need to pack “param_result” as follows.

private void ReturnToParent()
{
   Bundle conData = new Bundle();
   conData.putString(”param_return”, “text returned to MainActivity”);
   Intent intent = new Intent();
   intent.putExtras(conData);
   setResult(RESULT_OK, intent);
   finish();
}

Some useful default activities:
Part of the beauty of Android is that you can encapsulate other functionality/activities in your own code, just by writing a few lines of code. Below is a list of useful activities one may consider to use:

1. Writing an email

Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(”mailto:office@example.com”));
intent.putExtra(”subject”, “my subject”);
intent.putExtra(”body”, “my message”);
startActivity(intent);

2. Browse to a web-page

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(”http://www.google.com”));
startActivity(intent);

3. Write a SMS

Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(”sms://”));
intent.putExtra(”address”, “”);
intent.putExtra(”sms_body”, “my message”);
startActivity(intent);

4. Search something on Google

Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, “search this text”);
startActivity(intent);

5. Get the Wiktionary of some word

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(”http://en.wiktionary.org/wiki/” + “word”));
startActivity(intent);

6. Get the Wikipedia page of some words

String uri = “http://en.wikipedia.org/wiki/” + “my text”;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

There are several others activities one can try, just a quick google-search will reveal useful examples and links:
- calendar, phone, map, getdirections, product/book search – here

Preference / Settings

June 26th, 2009 No comments

(Android phone – how-to/example)

An android.preference.PreferenceActivity “shows a hierarchy of Preference objects as lists, possibly spanning multiple screens. These preferences will automatically save to SharedPreferences as the user interacts with them. Furthermore, the preferences shown will follow the visual style of system preferences. It is easy to create a hierarchy of preferences (that can be shown on multiple screens) via XML. For these reasons, it is recommended to use this activity (as a superclass) to deal with preferences in applications.” For example:

public final class PreferencesActivity extends android.preference.PreferenceActivity
implements OnSharedPreferenceChangeListener
{

In order to display the preferences the PreferenceActivity may call addPreferencesFromResource(int preferencesResId) method where preferencesResId is the id of preference.xml.
A preference.xml may look like this:

< PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
< PreferenceCategory android:title="First category">
< ListPreference
android:key="preferences_set_1"
android:title="First SET 1"/>
< EditTextPreference
android:key="preferences_set_2"
android:title="First SET 2"/>
< CheckBoxPreference
android:key="preferences_set_3"
android:defaultValue="true"
android:title="First SET 3"/>
< /PreferenceCategory>

< PreferenceCategory android:title="Second category">
< CheckBoxPreference
android:key="preferences_set_4"
android:defaultValue="false"
android:title="Second Set 4"/>
< Preference
android:key="preferences_set_5"
android:title="Second Set 5"/>
< /PreferenceCategory>

< /PreferenceScreen>

Note: The full documentation for PreferenceCategory, EditTextPreference, CheckBoxPreference, Preference may be found on http://developer.android.com/reference/android/preference/PreferenceActivity.html

Every preference must have a key defined in XML and in code. Example:

public static final String KEY_SET_1 = “preferences_set_1″;

To link the XML to the java code you need to do the folowing steps:
1. Create a PreferenceScreen object.“android.preference.PreferenceScreen represents a top-level Preference that is the root of a Preference hierarchy. A PreferenceActivity points to an instance of this class to show the preferences.”
Example: PreferenceScreen preferences;

2. Initialize PreferenceScreen object using getPreferenceScreen method. “android.preference.PreferenceActivity.getPreferenceScreen() method gets the root of the preference hierarchy that this activity is showing.”
Example: preferences = getPreferenceScreen();

3. Create a preference object that is also in XML and use findPreference(CharSequence key) method where key is the key of the preference. “android.preference.PreferenceGroup.findPreference(CharSequence key) finds a Preference based on its key.”
Example: CheckBoxPreference m_cbpSET1 = (CheckBoxPreference) preferences.findPreference(KEY_SET_1);

If you want to add an action when the preference is changed you must use the setOnPreferenceChangeListener method. This method “sets the callback to be invoked when this Preference is changed by the user (but before the internal state has been updated).”
Example:

m_cbpSET1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
/* your code here */
return true;
}
});

Code example: you may find useful to see the whole implementation of this in the Mezzofanti application – google code. The code is released under Apache License, ver 2.0, so you can freely use it free of charge in your own code. Consult the class PreferenceActivity.java.