• • • • • • • • •

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

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

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

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

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

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

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

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

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

Tip .

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

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

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

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

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" .Switch to "main.android.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas. <?xml version="1.

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


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". Select the complete widget and use the Properties view to set the property "background" to the color attribute "@color/myColor". 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.

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

Note that the "myClickHandler" will be called based on the "On Click" property of your button.layout.main). android. public class Convert extends Activity { private EditText text. package de.Toast.Activity.id.os. android.6.RadioButton. android.EditText.onCreate(savedInstanceState).widget.widget. text = (EditText) findViewById(R. android. setContentView(R. import import import import import import android.vogella. } // This method is called at button click because we assigned the name to the . Code your application Change your code in "Convert.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.android.widget.java" to the following. @Override public void onCreate(Bundle savedInstanceState) { super.View.temperature.EditText01). android.view.Bundle.app.

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

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


1. . It extends the standard Activity with a standard ListView Elements. callbacks for list events.. 5.5. Overview List can be used to display a scrollable list of items. 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.2. Lists 5. e.g for selecting a list element and helper methods to access the current list position and the selected element(s).

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

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

This is almost the same coding as in the previous example.label. int position. "Eclipse".View.Bundle. android.Toast.Activity. "iPhone" }. R. "Ubuntu". "Android".ListView. long id) { super. id).view. // Use your own layout and point the adapter to the UI elements which contains the label this.id. names)). import import import import import import import android. android. "Windows7". android.LENGTH_LONG) .layout. String keyword = o.makeText(this.toString(). Toast.widget. */ public void onCreate(Bundle icicle) { super.getItem(position). v. // Get the item that was clicked Object o = this. position. // Create an array of Strings.<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.getListAdapter(). android. package de.ArrayAdapter.android.rowlayout. Toast. R. 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.ListActivity. "Suse".os. View v.widget.setListAdapter(new ArrayAdapter<String>(this.app.listactivity2.vogella. "You selected: " + keyword.widget. that will be put to our ListActivity String[] names = new String[] { "Linux".onListItemClick(l. "Solaris". public class MyLayoutList extends ListActivity { /** Called when the activity is first created.app. } @Override protected void onListItemClick(ListView l.onCreate(icicle). android.

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

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

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

1. Create a project "de. right click on it and select New -> Other -> Android -> "Android XML File".2.android. Change the UI in the file "/res/layout/main.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas. Project This chapter will demonstrate how to create and evaluate a menu.vogella.6.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.xml" to the following: <?xml version="1. Add a menu Menus can be defined via XML files.preferences" with the activity "HelloPreferences". how to define preferences and how to navigate between activities via an intent .android. Select your project. Preferences and Intents 6. . Menu.

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

setContentView(R.os. return true.menu.menu.inflate(R. import import import import android. package de.Change your class "HelloPreferences" to the following.app. } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater().Bundle. android.layout.vogella. 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. public class HelloPreferences extends Activity { /** Called when the activity is first created.Activity. menu).onCreate(savedInstanceState). . android. The behavior will be later implemented in the method "onOptionsItemSelected".preferences.android. */ @Override public void onCreate(Bundle savedInstanceState) { super.main). inflater.MenuInflater. The OnCreateOptionsMenu method is used to create the menu.Menu. android.view.view. Please note that at the moment nothing happens if you select this menu.

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

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

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

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

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

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

".4. "Here you can maintain your user credentials. The saved values should be displayed in a small message windows (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. break. . } } Toast.makeText(HelloPreferences.LENGTH_LONG). Run Run your application. } return true.this.Toast. Press the "menu" hardware button and then select your menu item "Preferences". 6.show().

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

.Press Menu and select "New Contact".

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

7. Delete the default text. Also change the layout_height to "fill_parent".android.vogella.android. The resulting main. Example Create a new Android project "de.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.contentprovider" with the activity "ContactsView".3. <?xml version="1. Rename the id of the the existing TextView from the example wizard to "contactview".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> .xml should look like the following.

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

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. Create the following layout and class.scrollview. Of course the child can be a layout which can then contain other elements.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas. . If the child is to big the ScrollView will display a scroll bar to scroll the context. <?xml version="1.vogella.} } sortOrder).android.android.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" with the activity "ScrollView". 8.android.0"></Button> <Button android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" android:layout_weight="1.vogella. ScrollView ScrollViews can be used to contain one child that might be to big to fit on one screen. Create an android project "de.0"></Button> </LinearLayout> </LinearLayout> </ScrollView> package de.

i < 100.import import import import android. i++) { s += "vogella.TextView02).widget.TextView. android. } } 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. public class ScrollView extends Activity { /** Called when the activity is first created.app.view.layout. android.main).de ". setContentView(R. for (int i=0.setText(s). android. */ @Override public void onCreate(Bundle savedInstanceState) { super. TextView view = (TextView) findViewById(R.Bundle.onCreate(savedInstanceState). } view. String s="".View.os. .Activity.id.

usually exposed via a Manager class. <?xml version="1. The alarm manager will in our example our own broadcast receiver.android. In this chapter we will use the AlertManager and VibratorManager.9.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas. Create a new project "de.android.alarm" with the activity "AlarmActivity".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 the following layout.vogella. Services and Broadcast Receiver The Android platform provides a lot of pre-defined services.

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

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

print() statements) via the LogCat view.10.out. Important views 10. 10. LogCat View You can see the log (including System. File explorer The file explorer allows to see the files on the android simulator.2. .1.

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

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

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

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. 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 .