• • • • • • • • •

Home Blog Java Eclipse Google Web Technology Algorithms Training

If you like this article it would be great if you could support this website.

Android Development Tutorial - Gingerbread
Lars Vogel
Version 4.6 Copyright © 2009 - 2010 Lars Vogel

22.12.2010 Revision History Revision 0.1 04.07.2009 Created Revision 0.2 - 4.6 07.07.2009 - 22.12.2010 bug fixing and enhancements Development with Android Froyo and Eclipse This tutorial describes how to create Android applications with Eclipse. It is based on Eclipse 3.6, Java 1.6 and Android 2.3 (Gingerbread).

Lars Vogel Lars Vogel

Table of Contents 1. Android Development 1.1. Android Operation System 1.2. Important Android components 1.3. AndroidManifest.xml 1.4. R.java, Resources and Assets 1.5. Activities and Layouts 1.6. Activities and Lifecyle 1.7. Context 2. Installation 2.1. Android SDK 2.2. Eclipse 2.3. Configuration 2.4. Device 3. Error handling 4. Your first Android project 4.1. Create Project 4.2. Two faces of things 4.3. Create attributes 4.4. Add UI Elements 4.5. Maintain UI properties 4.6. Code your application 4.7. Start Project 4.8. Using the home menue 5. Lists 5.1. Overview 5.2. Simple ListActivities 5.3. ListActivities with own layout 5.4. ListActivities with flexible layout 6. Menu, Preferences and Intents

6.1. Project 6.2. Add a menu 6.3. Using preferences 6.4. Run 7. ContentProvider 7.1. Overview 7.2. Create contacts on your emulator 7.3. Example 8. ScrollView 9. Services and Broadcast Receiver 10. Important views 10.1. LogCat View 10.2. File explorer 11. Shell 11.1. Android Debugging Bridge - Shell 11.2. Uninstall an application via adb 11.3. Emulator Console via telnet 12. Deploy your application on a real device 13. Thank you 14. Questions and Discussion 15. Links and Literature 15.1. Source Code 15.2. Android Resources 15.3. vogella Resources

1. Android Development
1.1. Android Operation System
Android is an operating system based on Linux with a Java programming interface. It provides tools, e.g. a compiler, debugger and a device emulator as well as its own Java Virtual machine (Dalvik Virtual Machine - DVM). Android is created by the Open Handset Alliance which is lead by Google. Android uses a special virtual machine, e.g. the Dalvik Virtual Machine. Dalvik uses special bytecode. Therefore you cannot run standard Java bytecode on Android. Android provides a tool "dx" which allows to convert Java Class files into "dex" (Dalvik Executable) files. Android applications are packed into an .apk (Android Package) file. To simplify development Google provides the Android Development Tools (ADT) for Eclipse . The ADT performs automatically the conversion from class to dex files and creates the apk during deployment. Android supports 2-D and 3-D graphics using the OpenGL libraries and supports data storage in a SQLite database.

Every Android applications runs in its own process and under its own userid which is generated automatically by the Android system during deployment. Therefore the application is isolated from other running applications and a misbehaving application cannot easily harm other Android applications.

1.2. Important Android components
An Android application consists out of the following parts:

• •

Activity - Represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application. The User interface of an Activities is build with widgets classes which inherent from "android.view.View". The layout of the views is managed by "android.view.ViewGroups". Services - perform background tasks without providing an UI. They can notify the user via the notification framework in Android. Content Provider - provides data to applications, via a content provider your application can share data with other applications. Android contains a SQLite DB which can serve as data provider Intents are asynchronous messages which allow the application to request functionality from other services or activities. An application can call directly a service or activity (explicit intent) or asked the Android system for registered services and applications for an intent (implicit intents). For example the application could ask via an intent for a contact application. Application register themself to an intent via an IntentFilter. Intents are a powerful concept as they allow to create loosely coupled applications. Broadcast Receiver - receives system messages and implicit intents, can be used to react to changed conditions in the system. An application can register as a broadcast receiver for certain events and can be started if such an event occurs.

Other Android parts are Android widgets or Live Folders and Live Wallpapers . Live Folders display any source of data on the homescreen without launching the corresponding application.

1.3. AndroidManifest.xml
An Android application is described the file "AndroidManifest.xml". This files must declare all activities, services, broadcast receivers and content provider of the application. It must also contain the required permissions for the application. For example if the application requires network access it must be specified here. "AndroidManifest.xml" can be thought as the deployment descriptor for an Android application.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="de.vogella.android.temperature"

android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Convert" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="9" /> </manifest>

The "package" attribute defines the base package for the following Java elements. "activity" defines an activity in this example pointing to the class "de.vogella.android.temperature.Convert". For this class an intent filter is registered which defines that this activity is started ion the application starts (action android:name="android.intent.action.MAIN"). The category definition (category android:name="android.intent.category.LAUNCHER" ) defimes that this application is added to the application directory on the Android device. The @ values refer to resource files which contain the actual values. This makes it easy to provide different resources, e.g. strings, colors, icons, for different devices and makes it easy to translate applications.

1.4. R.java, Resources and Assets
The directory "gen" in an Android project contains generated values. "R.java" is a generated class which contains references to resources of the "res" folder in the project. System resources are maintained in the "res" directory and can be values, menus, layouts, icons or pictures or animations. These resources can for example be text or icons. If you create a new resources the corresponding reference is automatically created in R.java. The references are static int values, the Android system provides methods to access the corresponding resource. For example to access a String with the reference id "R.string.yourString" use the method getString(R.string.yourString)); Please do not try to modify "R.java" manually. While "res" contains structured values which are known to the Android platform the directory "assets" can be used to store any kind of data. In Java you can access this data via the AssetsManager and the method getAssets().

1.5. Activities and Layouts
The user interface for Activities is defined via layouts. Layouts are at runtime instances of "android.view.ViewGroups". The layout defines the UI elements, their properties and their arragement. UI elements are based on the class "android.view.View". ViewGroup is

com/android/eclipse/ . e.1.6. 1.called if the Activity is re-started. 2. Contexts provides the method getSystemService which allows to receive a manager object for the different hardware parts. For details please see Eclipse Tutorial . The download contains a zip file which you can extract to any place in your file system. The XML way is usually preferred as this separates the programming logic from the layout definition and allow to define easily different layout resources from different devices.a subclass of View A and a layout can contain UI components (Views) or other layouts (ViewGroups). You should not nestle ViewGroups to deeply as his impact performance. Used to save data so that the activity can restore its states if re-started onPause() .always called if the Activity ends. The Android system defines a life cycle for an activities via pre-defined methods.2. You can also mix both approaches. As Activities and Services extend this class you can directly access the context via "this". Installation The following assume that you have already Eclipse installed. can be used to release ressource or save data onResume() .g.content. e. 2. Configuration .7. 2. Android SDK Download the Android SDK from the Android homepage under Android SDK download . Activities and Lifecyle The operating system controls the life cycle of your application.google. because of an incoming call. 2.called if the activity is stopped.3. Eclipse Use the Eclipse update manager to install all available plugins for the Android Development Tools (ADT) from the URL https://dl-ssl.g. Context The class android. The most important methods are: • • • onSaveInstanceState() . I placed it under "c:\android-sdk-windows" . A layout can be defined via code at runtime or XML in a resource file in the folder "/res/layout". At any time the Android system may stop or destroy your application. can be used to initiaze fields 1.Context provides the connections to the Android system.

Select Android and maintain the installation path of the Android SDK. Tip If you maintain the location the Android plugin will remind you frequently (and for every workspace). Select now Window -> Android SDK and AVD Manager from the menu. . Select available packages and select the latest version of the SDK.In Eclipse open the Preferences dialog via Windows -> Preferences. Join me in starring at Bug 3210 to get this improved.

4. Device .Press "Install selected" and confirm the license for all package. After the installation restart Eclipse. 2.

Press the device manager button. press "New" and maintain the following.You need to define a device which can be used for emulation. .

This will create the device. . To test if you setup is correct.Press "Create AVD". eelect your device and press "Start".

After (a long time) your device should be started. .

Project . The project could not be built until build path errors are resolved. 3... If you having problems with your own code you can use the LogCat viewer as described in LogCat Viewer . Unable to open class file R.3. To solve this error select from the menu Project -> Clean. is missing required source folder: 'gen' 2.java. Several users report that get the following errors: 1. Error handling Things are not always working as they should be. .

4. Search for "vogella" for find this example.vogella. Create Project Tip This app is also available on the Android Marketplace. Your first Android project 4.android. Select File -> New -> Other -> Android -> Android Project and create the Android project "de.1.temperature". . Maintain the following.

Tip .

This should create the following directory structure. via a rich editor and directly via XML. In Java you can access this data via the AssetsManager and the method getAssets(). The following description tries to use the rich UI . While "res" contains structured values which are known to the Android platform the directory "assets" can be used to store any kind of data. e. strings and UI's. 4. Please stare at Android New Project Wizard should have the option to add to Working set to get this functionality. Two faces of things The Android SDK allows to maintain certain artifacts.I think this wizard should have the option to add the project to an existing working set.g.2. Press "Finish". in two ways.

You can switch between the two things the the tab on the lower part of the screen. .3. Create attributes Android allows to create attributes for resources.g. For example: 4.but for validation lists also the XML. for strings and / or colors. e. These attributes can be used in your UI definition via XML or in your Java source code.

String Attributes Name buttonHandler celsius fahrenheit calc Value myClickHandler to Celsius to Fahrenheit Calculate . Select "Color" and maintain "myColor" as the name and "#3399CC" as the value.xml" and press "Add". String attributes allow to translate the application at a later point. Table 1.Select the file "res/values/string. Add also the following "String" attributes.

Delete the "Hello World. Make sure that your code is the same as listed below. This editor allows to maintain the UI via drag and drop or directly via the XML source code. . From the "Views" bar.Switch to the XML representation and validate that you maintained the values correctly. <?xml version="1. Convert!</string> <string name="app_name">Temperature Converter</string> <color name="myColor">#3399CC</color> <string name="buttonHandler">myClickHandler</string> <string name="celsius">to Celsius</string> <string name="fahrenheit">to Fahrenheit</string> <string name="calc">Calculate</string> </resources> 4. Add UI Elements Select "res/layout/main. Add from the layout a "RadioGroup" and then two RadioButtons.xml" and open the Android editor via double-click.4. You can switch between both representations via the tabs at the bottom of the editor. drag in an "EditText". add one "Button". The result should look like the following and the corresponding XML is listed below. For changing the postion and grouping elements you can use the outline view.0" encoding="utf-8"?> <resources> <string name="hello">Hello World. Hello!" via a right mouse click.

Switch to "main. <?xml version="1.android.xml" and verify that your XML looks like the following.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText> <RadioGroup android:id="@+id/RadioGroup01" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:text="@+id/RadioButton01" android:id="@+id/RadioButton01" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton> <RadioButton android:text="@+id/RadioButton02" android:id="@+id/RadioButton02" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton> </RadioGroup> <Button android:text="@+id/Button01" android:id="@+id/Button01" .0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.

android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout> 4.5. . Maintain UI properties If you select a UI element you can change its properties via the properties view. Select EditText and change the property "Layout Width" to "fill_parent".


Select the complete widget and use the Properties view to set the property "background" to the color attribute "@color/myColor". Delete the text property in the EditText (this means no text will be initially shown) and set the "Input type" property to "numberSigned" and "number decimal". Set the property "Checked" to true for the first RadioButton.Assign the "celsius" string attribute to your "text" property of the first radio button and "fahrenheit" to the second. Assign "calc" to the text property of your button and assign "buttonHandler" to the "onClick" property. .

<?xml version="1.Switch to the "main.android.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.com/apk/res/android" .xml" tab and verify that the XML is correctly maintained.

} // This method is called at button click because we assigned the name to the .widget. android.EditText01). Note that the "myClickHandler" will be called based on the "On Click" property of your button.RadioButton. android.vogella.temperature.Bundle.android.view. setContentView(R.widget.onCreate(savedInstanceState).6.os.java" to the following. @Override public void onCreate(Bundle savedInstanceState) { super. import import import import import import android.widget.android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/myColor"> <EditText android:id="@+id/EditText01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:inputType="numberSigned|numberDecimal"></EditText> <RadioGroup android:id="@+id/RadioGroup01" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:id="@+id/RadioButton01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/celsius" android:checked="true"></RadioButton> <RadioButton android:id="@+id/RadioButton02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/fahrenheit"></RadioButton> </RadioGroup> <Button android:id="@+id/Button01" android:layout_height="wrap_content" android:onClick="@string/buttonHandler" android:layout_width="wrap_content" android:text="@string/calc"></Button> </LinearLayout> 4.EditText. Code your application Change your code in "Convert.id. text = (EditText) findViewById(R.View. public class Convert extends Activity { private EditText text. package de.main). android.app. android.Toast.layout. android.Activity.

setChecked(false). } else { fahrenheitButton.id. if (text.length() == 0) { Toast.RadioButton02).id. return.isChecked()) { fahrenheitButton.parseFloat(text. } break.show().setChecked(false). } else { text. RadioButton fahrenheitButton = (RadioButton) findViewById(R.valueOf(convertFahrenheit ToCelcius(inputValue))).LENGTH_LONG).valueOf(convertCelciusToF ahrenheit(inputValue))). celsiusButton.setChecked(true).setText(String . } } // Converts to celcius private float convertFahrenheitToCelcius(float fahrenheit) { return ((fahrenheit .makeText( this. } } 4.toString()).7.isChecked()) { text.Button01: RadioButton celsiusButton = (RadioButton) findViewById(R. } float inputValue = Float.id. } // Switch to the other button if (fahrenheitButton.32) * 5 / 9). Start Project .setChecked(true).// "On Click property" of the button public void myClickHandler(View view) { switch (view.RadioButton01).getId()) { case R. celsiusButton.getText(). if (celsiusButton.getText().setText(String . "Please enter a valid number". } // Converts to fahrenheit private float convertCelciusToFahrenheit(float celsius) { return ((celsius * 9) / 5) + 32. Toast.

To start the Android Application.8. select your conversion and press the button. Type in a number. 4. You should get the following result. The result should be displayed and the other option should get selected. . select your project. Run-As-> Android Application Be patient. the emulator starts up very slow. right click on it. Using the home menue If you press the Home button you can also select your application.


callbacks for list events..g for selecting a list element and helper methods to access the current list position and the selected element(s). e. Overview List can be used to display a scrollable list of items. It extends the standard Activity with a standard ListView Elements. Lists 5.2. . You can either use lists in your layout or if the purpose of your Activity is to show primary a list you can extend ListActivities which provides nice hocks for typical actions for lists. Simple ListActivities A ListActivity extends Activity and simplifies the approach to show several objects in a list.1.5. 5.

Create the following activity.show().ListActivity.setListAdapter(new ArrayAdapter<String>(this.To test this create a new Android project "de.getItem(position). } @Override protected void onListItemClick(ListView l.widget. package de.View.toString(). that will actually make the Strings above // appear in the ListView this. Toast. // Create an ArrayAdapter.onListItemClick(l.onCreate(icicle).os. "Ubuntu". android. */ public void onCreate(Bundle icicle) { super. android. id).Toast. android.view.widget. "You selected: " + keyword. Toast.listactivity.ArrayAdapter. position.widget. v. You do not need to change the default layout "main.vogella.makeText(this. View v.android. "Solaris". "iPhone"}.app.layout.simple_list_item_checked. android.listactivity" with the activity "MyList". // Get the item that was clicked Object o = this. long id) { super. String keyword = o.getListAdapter(). import import import import import import android.android. "Windows7". int position. android. "Eclipse".LENGTH_LONG) . // Create an array of Strings. "Suse". } } . "Android".R. public class MyList extends ListActivity { /** Called when the activity is first created.vogella.xml". names)). that will be put to our ListActivity String[] names = new String[] { "Linux".Bundle.ListView. android.

android.xml" in the res/layout folder of your project "de.listactivity". We will add a graphic to each list entry.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> .vogella. Create the following layout file "rowlayout. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.5. ListActivities with own layout The example above is boring. You can also define your own layout for the rows and assign this layout to your row adapter.android.3. as only text is shown.

app. android. // Create an array of Strings.ListActivity. */ public void onCreate(Bundle icicle) { super.ListView. android. // Get the item that was clicked Object o = this. "Suse".Bundle.widget. package de.widget. "Solaris". "Android". "Ubuntu".label. that will be put to our ListActivity String[] names = new String[] { "Linux".listactivity2.getListAdapter(). "iPhone" }. android. } @Override protected void onListItemClick(ListView l. View v. "You selected: " + keyword.Toast.app.os. android. the only difference is that we are using our own layout in the ArrayAdapter and telling the adapter which UI element should contains the text.widget. names)). R.vogella. Toast. import import import import import import import android.rowlayout. int position.android. // Use your own layout and point the adapter to the UI elements which contains the label this.id. android.view. "Windows7". Toast.onListItemClick(l. android.<ImageView android:id="@+id/icon" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="22px" android:layout_marginTop="4px" android:layout_marginRight="4px" android:layout_marginLeft="4px"> </ImageView> <TextView android:text="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/label" android:textSize="30px"></TextView> </LinearLayout> Change your activity "MyList" to the following. id).toString().ArrayAdapter.onCreate(icicle).getItem(position). v.Activity.LENGTH_LONG) .layout. long id) { super. "Eclipse". public class MyLayoutList extends ListActivity { /** Called when the activity is first created.setListAdapter(new ArrayAdapter<String>(this.View. This is almost the same coding as in the previous example.makeText(this. String keyword = o. position. R.

The above example uses one layout for all rows. Create the following class "MyArrayAdapter. If you want to influence the display of the different rows you can also define your own adapter and implement your own getView() method. This method is responsible for creating the listview.java". ListActivities with flexible layout The following uses an image "alt_window_16". You must maintain your own icon. } } 5. package de.show().android. .vogella. In this method we will read the pre-defined layout via LayoutInflator and return one individual view per row.listactivity.4. I placed the res/drawable folder..

label.Toast. android.alt_window_16).Activity.widget.ArrayAdapter. View convertView.View.ImageView. imageView. // Change the icon for Windows and iPhone if (names[position].View. android. } return rowView.android.os. public MyArrayAdapter(Activity context.println(names[position]).label).layout.ListView.app. String[] names) { super(context.inflate(R. import import import import import android. private final String[] names. */ . System. R. public class MyList extends ListActivity { /** Called when the activity is first created. names).findViewById(R.names = names. true).setText(names[position]).vogella. this.import import import import import import import android.widget. null. } } package de.view. android.setImageResource(R.context = context. View rowView = inflater.widget. } @Override public View getView(int position. android.ViewGroup. android.out.view.widget.findViewById(R.rowlayout. android.view.Bundle. android. android. android.layout.ListActivity. android.icon). TextView label = (TextView) rowView.app.getLayoutInflater().view. public class MyArrayAdapter extends ArrayAdapter<String> { private final Activity context. ViewGroup parent) { LayoutInflater inflater = context.rowlayout.widget.LayoutInflater.TextView.id.id.listactivity. this.startsWith("Windows7") || names[position].startsWith("iPhone") ) { ImageView imageView = (ImageView) rowView.drawable.

public void onCreate(Bundle icicle) { super. id). Toast. position. long id) { super.getListAdapter(). this. int position. } } . View v.show(). // Create an array of Strings.onCreate(icicle). "Eclipse". "iPhone"}. names)).makeText(this.onListItemClick(l.LENGTH_LONG) . "Android". "Suse".toString(). v. "Windows7". Toast. // Get the item that was clicked Object o = this. } @Override protected void onListItemClick(ListView l. "You selected: " + keyword. that will be put to our ListActivity String[] names = new String[] { "Linux".setListAdapter(new MyArrayAdapter(this. String keyword = o.getItem(position). "Ubuntu". "Solaris".

com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Preferences"></Button> </LinearLayout> 6. how to define preferences and how to navigate between activities via an intent . Create a project "de.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas. . Menu.android. Change the UI in the file "/res/layout/main.android.6.2.1. Add a menu Menus can be defined via XML files. right click on it and select New -> Other -> Android -> "Android XML File". Select your project. Preferences and Intents 6.preferences" with the activity "HelloPreferences".xml" to the following: <?xml version="1. Project This chapter will demonstrate how to create and evaluate a menu.vogella.

Maintain the following value. . We will have only one entry.Press Add and select "Item". This defines the entries in your menu.

*/ @Override public void onCreate(Bundle savedInstanceState) { super.layout.Activity.preferences.vogella.main). android. Please note that at the moment nothing happens if you select this menu.app.MenuInflater. The behavior will be later implemented in the method "onOptionsItemSelected".view. setContentView(R. menu). return true.Menu. public class HelloPreferences extends Activity { /** Called when the activity is first created. import import import import android.os. inflater.view. . package de.inflate(R. } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater().Bundle.Change your class "HelloPreferences" to the following.menu.menu.onCreate(savedInstanceState).android. android. In case you want to disable or hide menu items you can use the method "onPrepareOptionsMenu" which is called every time the menu is called. The OnCreateOptionsMenu method is used to create the menu. android.

Your menu should be displayed. 6. . Create another Android XML File "preferences. Using preferences Preference values can also be stored as a XML resource.xml" this time of type preferences.} } Run your application and press "Menu" on the emulator.3.

Press Add. add a category and add two preferences "EditTextPreferences" to this category : "User" and "Password". .

import android.preference.Bundle. package de.android.xml".vogella.Create the class "Preferences" which will load the "preference.preferences. import android. public class Preferences extends PreferenceActivity { .PreferenceActivity.os.

preferences). Add the activity "Preferences". ./** Called when the activity is first created.xml. } } Select "AndroidManifest. addPreferencesFromResource(R.xml" and the tab "Application". */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState).

os.PreferenceManager. .content.Activity.Bundle.To use the preferences add a button to your main. android.content.vogella.preferences.Intent.app.xml with the id "@+id/Button01" and change the coding of HelloPreferences to the following. android. android. import import import import import android.SharedPreferences.preference. package de.android. android.

view.widget.Button.getDefaultSharedPreferences(this).Menu.class).makeText(HelloPreferences.this. android.menu.onCreate(savedInstanceState). android. android.getString("username". Preferences.getItemId()) { // We have only one menu option case R. Toast.MenuItem. String password = preferences. android.this. startActivity(i).inflate(R. button. }).OnClickListener.layout. "You maintained user: " + username + " and password: " + password.id. } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater().Button01). // Initialize preferences preferences = PreferenceManager. Toast.preferences: // Launch Preference activity Intent i = new Intent(HelloPreferences. // A toast is a view containing a quick little message for the user. public class HelloPreferences extends Activity { SharedPreferences preferences.id. "n/a").View.MenuInflater.menu.View.show().widget. } // This method is called once the menu is selected @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item. "n/a"). /** Called when the activity is first created.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String username = preferences.view.view.import import import import import import import android. return true.Toast. android.view. */ @Override public void onCreate(Bundle savedInstanceState) { super.view. Button button = (Button) findViewById(R. inflater.main). } . menu). setContentView(R.getString("password". android.LENGTH_LONG).

this. . } } Toast.4.".show().Toast. You should be able to enter your user settings then press the back hardware button to return to your main activity and press the button. "Here you can maintain your user credentials. Press the "menu" hardware button and then select your menu item "Preferences". } return true. Run Run your application. The saved values should be displayed in a small message windows (Toast). break.makeText(HelloPreferences. 6.LENGTH_LONG).

2.7.1. . ContentProvider 7. Create contacts on your emulator Select the home menu and then the menu entry "Contacts" to create contacts. The following example will use an existing context provider from "Contacts". Overview ContentProvider are used to provide data from an application to another. 7. ContentProvider do not store the data but provide the interface for other applications to access the data.

.Press Menu and select "New Contact".

As a result you should have a few new contacts. .

com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/contactview" /> </LinearLayout> . Delete the default text. Also change the layout_height to "fill_parent".android. Example Create a new Android project "de.android. The resulting main. Rename the id of the the existing TextView from the example wizard to "contactview".contentprovider" with the activity "ContactsView".xml should look like the following.7. <?xml version="1.3.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.vogella.

DISPLAY_NAME + " COLLATE LOCALIZED ASC".android.Cursor.Contacts.main). Change the coding of the activity. contactView. android.DISPLAY_NAME }. */ @Override public void onCreate(Bundle savedInstanceState) { super. import import import import import import android.append("Name: "). return managedQuery(uri. Cursor cursor = getContacts(). TextView contactView = (TextView) findViewById(R.app.net. String[] selectionArgs = null.append("\n").Contacts.permission. setContentView(R.Contacts._ID.Contacts.widget.database. .CONTENT_URI. android. android. String selection = ContactsContract. package de.Activity.vogella.IN_VISIBLE_GROUP + " = '" + ("1") + "'". while (cursor.getString(cursor . } } private Cursor getContacts() { // Run query Uri uri = ContactsContract.READ_CONTACTS".TextView.xml add the User Permission that the application can use "android. contactView.In AndroidManifest. selection.provider. ContactsContract. selectionArgs.ContactsContract.Contacts. android. String[] projection = new String[] { ContactsContract.Bundle. Data.getColumnIndex(ContactsContract.contentprovider.os. String sortOrder = ContactsContract.id.Uri.layout.moveToNext()) { String displayName = cursor. projection.append(displayName). contactView.DISPLAY_NAME)). public class ContactsView extends Activity { /** Called when the activity is first created. android.onCreate(savedInstanceState).contactview).

0"></Button> <Button android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" android:layout_weight="1.0"></TextView> <LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Submit" android:layout_weight="1.scrollview. 8. Create the following layout and class.vogella. .} } sortOrder).0"></Button> </LinearLayout> </LinearLayout> </ScrollView> package de.android.android.android. If the child is to big the ScrollView will display a scroll bar to scroll the context. ScrollView ScrollViews can be used to contain one child that might be to big to fit on one screen.scrollview" with the activity "ScrollView". Of course the child can be a layout which can then contain other elements. Create an android project "de.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true"> <LinearLayout android:id="@+id/LinearLayout01" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a header" android:textAppearance="?android:attr/textAppearanceLarge" android:paddingLeft="8dip" android:paddingRight="8dip" android:paddingTop="8dip"></TextView> <TextView android:text="@+id/TextView02" android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1. <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.vogella.

setContentView(R.main).TextView. String s="". TextView view = (TextView) findViewById(R.widget.import import import import android. public class ScrollView extends Activity { /** Called when the activity is first created.id. } } The attribute "android:fillViewport="true"" ensures that the the scrollview is set to the full screen even if the elements are smaller then one screen and the "layout_weight" tell the android system that these elements should be extended. */ @Override public void onCreate(Bundle savedInstanceState) { super.Bundle.onCreate(savedInstanceState). .de ". android. i++) { s += "vogella. } view. android.View.TextView02). android.setText(s).app.view.Activity.os. i < 100. for (int i=0.layout.

usually exposed via a Manager class.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/time" android:hint="Number of seconds" . Create a new project "de. Services and Broadcast Receiver The Android platform provides a lot of pre-defined services. <?xml version="1.alarm" with the activity "AlarmActivity". Create the following layout.android. In this chapter we will use the AlertManager and VibratorManager.android.vogella.9. The alarm manager will in our example our own broadcast receiver.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.

intent. "Don't panik but your time is up!!!!.makeText(context.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas. android. This class will get the Vibrator service. // Vibrate the mobile phone Vibrator vibrator = (Vibrator) context.alarm" android:versionCode="1" android:versionName="1.MAIN" /> <category android:name="android.VIBRATOR_SERVICE).widget.os.content.category. public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context.content. import import import import import android.intent. <?xml version="1.show(). android. vibrator.vogella.com/apk/res/android" package="de.Context.android:inputType="numberDecimal"></EditText><Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ok" android:onClick="startAlert" android:text="Start Counter"></Button> </LinearLayout> Create the following broadcast receiver class. android.AlarmActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.".Intent.LENGTH_LONG).getSystemService(Context.alarm.LAUNCHER" /> </intent-filter> </activity> . package de.vibrate(2000).content. Toast.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=". } } Maintain this class as broadcast receiver in "AndroidManifest.vogella.android.action.android.android. Intent intent) { Toast.BroadcastReceiver. android.Toast.xml" and allow the vibrate authorization.Vibrator.

LENGTH_LONG). android.os.app.Activity. package de. android.Bundle. public class AlarmActivity extends Activity { /** Called when the activity is first created.permission.view. This activity will create an Intent for the Broadcast receiver and get the AlarmManager service.MyBroadcastReceiver" android:enabled="true"> </receiver> </application> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.widget.Intent. 234324243. pendingIntent). setContentView(R. android. alarmManager. "Alarm set in " + i + " seconds".android. AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE).getText(). intent.EditText.Toast. } public void startAlert(View view) { EditText text = (EditText) findViewById(R. android.time). Intent intent = new Intent(this.content.View.toString()).vogella.main). import import import import import import import import android. int i = Integer.VIBRATE"></usespermission> </manifest> Now define your main Activitiy.widget. PendingIntent pendingIntent = PendingIntent. Toast.<receiver android:name=".show(). MyBroadcastReceiver.app.PendingIntent.getBroadcast( this. android.AlarmManager.layout. */ @Override public void onCreate(Bundle savedInstanceState) { super.parseInt(text.RTC_WAKEUP.app. android.makeText(this.class).set(AlarmManager. System. } } . android.alarm.onCreate(savedInstanceState). Toast. 0).id.currentTimeMillis() + (i * 1000).getApplicationContext(). statements) via the LogCat view.out. Important views 10. File explorer The file explorer allows to see the files on the android simulator. LogCat View You can see the log (including System. .

Android Debugging Bridge . Shell 11. The application data is stored in the directory "/data/data/package_of_your_app". # Lists all devices adb devices #Result List of devices attached . switch to your "android-sdk" installation directory into the folder "tools". Open a shell. mkdir. e. If you have several devices running you can issue commands to one individuel device.11.1. etc.g. rm.Shell You can access your Android emulator also via the console. ls. Start the shell via the following command "adb shell". adb shell This will connect you to your device and give you Linux command line access to the underlying file system.

then enable USB debugging. change the network "stability". e. set your current geocodes. Uninstall an application via adb You can uninstall an android application via the shell. use the command "quit" or "exit". Select in the settings Applications > Development. 11. To select your phone. incoming call. Use "telnet localhost 5554" to conntect to your simulated device. Please note that the Android version you are developing for must be the installed version on your phone. . Switch the the data/app directory (cd /data/app) and simply delete your android application. You also need to install the driver for your mobile phone. Emulator Console via telnet Alternatively to adb you can also use telnet to connect to the device.g.emulator-5554 attached emulator-5555 attached # Issue a command to a specific device adb -s emulator-5554 shell 11. For details please see Developing on a Device . select "Manual" selection and select your device. For example to change the power settings of your phone. Deploy your application on a real device Turn on "USB Debugging" on your device in the settings. To exit the console session.2. to receive an sms and to get an incoming call make the following. select the "Run Configurations". etc.3. # connects to device telnet localhost 5554 # set the power level power status full power status charging # make a call to the device gsm call 012041293123 # send a sms to the device sms send 12345 Will be home soon # set the geo location For more information on the emulator console please see Emulator Console manual 12. This allows you to simulate certain things.

Source Code Source Code of Examples 15. 15. Links and Literature 15.2.1. Questions and Discussion Before posting questions.vogella. Thank you If you like this tutorial please support this website. Android Resources . If you have questions or find an error in this article please use the www. I have created a short list how to create good questions which might also help you. 14.13. please see the vogella FAQ .de Google Group .

vogella Resources Eclipse RCP Training Join my Eclipse RCP Training to become an RCP Expert in 5 days (Training in German) Android Tutorial Introduction to Android Programming GWT Tutorial Program in Java and compile to JavaScript and HTML Eclipse RCP Tutorial Create native applications in Java JUnit Tutorial Test your application Git Tutorial Put everything you have under distributed version control system .Android 2 (German Book) Android Location API and Google Maps Android Intents Android and Networking Android Homepage Android Developer Homepage Android Issues / Bugs Android Google Groups Android Market SQLight database homepage Content Provider Tutorial by Google Notepad Tutorial from Google Android Core Snippets / Tutorial page Marakana Android Tutorials 15.3.

Sign up to vote on this title
UsefulNot useful