You are on page 1of 29

Android Development Tutorial - Gingerbread

Home

Blog

Java

Eclipse

Google

Web

Technology

Algorithms

Android Development Tutorial - Gingerbread


Lars Vogel
Version 4.4 Copyright 2009 - 2010 Lars Vogel 06.12.2010 Revision History
Revision 0.1 Created Revision 0.2 - 4.4 bug fixing and enhancements 07.07.2009 - 06.12.2010 Lars Vogel 04.07.2009 Lars Vogel

You can help me maintaining this article:

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). Table of Contents 1. Android Development 1.1. 1.2. 1.3. 1.4. 1.5. Android Operation System Important Android terms Activities and Layouts Activities and Lifecyle Context

2. Installation 2.1. 2.2. 2.3. 2.4. Android SDK Eclipse Configuration Device

3. Error handling 4. Your first Android project 4.1. 4.2. 4.3. 4.4. 4.5. 4.6. 4.7. 4.8. 5. Lists 5.1. 5.2. 5.3. 5.4. Overview Simple ListActivities ListActivities with own layout ListActivities with flexible layout Create Project Two faces of things Create attributes Add UI Elements Maintain UI properties Code your application Start Project Using the home menue

6. Menu, Preferences and Intents 6.1. 6.2. 6.3. 6.4. Project Add a menu Using preferences 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

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

15. Links and Literature 15.1. Source Code 15.2. Android Resources 15.3. vogella Resources

Xperia X10 Upgrade Upgrade ke New Android 2.1 dan dapatkan aplikasi baru yang menarik www.SonyEricsson.co Windows 7 Programming Programming tips from MS insiders. Ribbon. Task bar. Annimation. Go! www.drdobbs.co Download Eclipse Fast Free optimized mirrors for maximum download speed - Eclipse & plugins! www.poweredby

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 Java virtual machine (Dalvik) which is based on the Apache Harmony Java implementation. 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 then packed into an .apk (Android Package) file. Android supports 2-D and 3-D graphics using the OpenGL libraries and supports data storage in a SQLLite database. For development Google provides the Android Development Tools (ADT) for Eclipse to develop Android applications. Every Android applications runs in its own process and it isolated from other running applications. Therefore on misbehaving application cannot harm other Android applications.

1.2. Important Android terms


An Android application consists out of the following parts: Activity - A screen in the Android application Services - Background activities without UI Content Provider - provides data to applications, Android contains a SQLLite DB which can serve as data provider Broadcast Receiver - receives system messages, can be used to react to changed conditions in the system Intends allow the application to request and / or provide services . For example the application call ask via an intent for a contact application. Application register themself via an IntentFilter. Intends are a powerful concept as they allow to create loosely coupled applications. An Android application is described the file "AndroidManifest.xml". This files contains all activities application and 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.

1.3. Activities and Layouts


The user interface for Activities is defined via layouts. The layout defines the UI elements, their properties and their arragement. A layout can be defined via XML and via code at runtime. The XML way is usually preferred for a fixed layout while defining the layout via code is more flexible. You can also mix both approaches.

1.4. Activities and Lifecyle


The operating system controls the life cycle of your application. At any time the Android system may stop or destroy your application, e.g. because of an incoming call. The Android system defines a life cycle for an activities via pre-defined methods. The most important methods are: onSaveInstanceState() - called if the activity is stopped. Used to save data so that the activity can restore its states if restarted onPause() - always called if the Activity ends, can be used to release ressource or save data onResume() - called if the Activity is re-started, can be used to initiaze fields

1.5. Context
The class android.content.Context provides the connections to the Android system. Contexts provides the method getSystemService which allows to receive a manager object for the different hardware parts. As Activities and Services extend this class you can directly access the context via "this".

2. Installation
The following assume that you have already Eclipse installed. For details please see Eclipse Tutorial .

2.1. Android SDK


Download the Android SDK from the Android homepage under Android SDK download . The download contains a zip file which you can extract to any place in your file system, e.g. I placed it under "c:\android-sdk-windows" .

2.2. Eclipse
Use the Eclipse update manager to install all available plugins for the Android Development Tools (ADT) from the URL https://dl-ssl.google.com/android/eclipse/ .

2.3. Configuration

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

In Eclipse open the Preferences dialog via Windows -> Preferences. Select Android and maintain the installation path of the Android SDK.

If you maintain the location the Android plugin will remind you frequently (and for every workspace). Join me in starring at Bug 3210 to get this improved. Select now Window -> Android SDK and AVD Manager from the menu.

Select available packages and select the latest version of the SDK.

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

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

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

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

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

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

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

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

Powerful Quadratic Solver

Build & Solve Large Scale QP and QIP Models Quickly and Easily www.lindo.com

Darteco Strategy and Technology Knowledge for the Mobile World www.darteco.com Flowcharts from C/C++ CallFlow, DataFlow, Code Metrics Trees, Static Check, Documentation www.sgvsarc.com

4. Your first Android project


4.1. Create Project

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

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

I think this wizard should have the option to add the project to an existing working set. Please stare at Android New Project Wizard should have the option to add to Working set to get this functionality. Press "Finish". This should create the following directory structure.

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

"R.java" is a generated class which contains the text and the UI elements. Please do not try to modify this class manually.

4.2. Two faces of things


The Android SDK allows to maintain certain artifacts, e.g. strings and UI's, in two ways, via a rich editor and directly via XML. The following description tries to use the rich UI but for validation lists also the XML. You can switch between the two things the the tab on the lower part of the screen. For example:

4.3. Create attributes


Android allows to create attributes for resources, e.g. for strings and / or colors. These attributes can be used in your UI definition via XML or in your Java source code.

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

Select the file "res/values/string.xml" and press "Add". Select "Color" and maintain "myColor" as the name and "#3399CC" as the value.

Add also the following "String" attributes. String attributes allow to translate the application at a later point. Table 1. String Attributes Name celsius fahrenheit calc Value to Celsius to Fahrenheit Calculate

buttonHandler myClickHandler

Switch to the XML representation and validate that you maintained the values correctly.

< ? xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, 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.4. Add UI Elements


Select "res/layout/main.xml" and open the Android editor via double-click. This editor allows to maintain the UI via drag and drop or directly via the XML source code. You can switch between both representations via the tabs at the bottom of the editor. For changing the postion and grouping elements you can use the outline view. Delete the "Hello World, Hello!" via a right mouse click. From the "Views" bar, drag in an "EditText". Add from the layout a "RadioGroup" and then two RadioButtons, add one "Button". The result should look like the following and the corresponding XML is listed below. Make sure that your code is the same as listed below.

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

Switch to "main.xml" and verify that your XML looks like the following.

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

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

Assign the "celsius" string attribute to your "text" property of the first radio button and "fahrenheit" to the second. Set the property "Checked" to true for the first RadioButton. Assign "calc" to the text property of your button and assign "buttonHandler" to the "onClick" property. 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".

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

Switch to the "main.xml" tab and verify that the XML is correctly maintained.

< ? xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 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.6. Code your application


Change your code in "Convert.java" to the following. Note that the "myClickHandler" will be called based on the "On Click" property of your button.

package de.vogella.android.temperature; import import import import import import android.app.Activity; android.os.Bundle; android.view.View; android.widget.EditText; android.widget.RadioButton; android.widget.Toast;

public class Convert extends Activity { private EditText text; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (EditText) findViewById(R.id.EditText01); } // This method is called at button click because we assigned the name to the // "On Click property" of the button

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread


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

4.7. Start Project


To start the Android Application, select your project, right click on it, Run-As-> Android Application Be patient, the emulator starts up very slow. You should get the following result.

Type in a number, select your conversion and press the button. The result should be displayed and the other option should get selected.

4.8. Using the home menue


If you press the Home button you can also select your application.

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

5. Lists
5.1. 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.

5.2. Simple ListActivities


A ListActivity extends Activity and simplifies the approach to show several objects in a list. It extends the standard Activity with a standard ListView Elements, callbacks for list events, e..g for selecting a list element and helper methods to access the current list position and the selected element(s). To test this create a new Android project "de.vogella.android.listactivity" with the activity "MyList". You do not need to change the default layout "main.xml". Create the following activity.
package de.vogella.android.listactivity; import android.app.ListActivity;

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread


import import import import import android.os.Bundle; android.view.View; android.widget.ArrayAdapter; android.widget.ListView; android.widget.Toast;

public class MyList extends ListActivity { /** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); // Create an array of Strings, that will be put to our ListActivity String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse", "Ubuntu", "Solaris", "Android", "iPhone"}; // Create an ArrayAdapter, that will actually make the Strings above // appear in the ListView this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, names)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked Object o = this.getListAdapter().getItem(position); String keyword = o.toString(); Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG) .show(); } }

5.3. ListActivities with own layout


The example above is boring, as only text is shown. You can also define your own layout for the rows and assign this layout to your row adapter. We will add a graphic to each list entry. Create the following layout file "rowlayout.xml" in the res/layout folder of your project "de.vogella.android.listactivity".

< ? xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <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. This is almost the same coding as in the previous example, 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.

package de.vogella.android.listactivity2; import import import import import import android.app.Activity; android.app.ListActivity; android.os.Bundle; android.view.View; android.widget.ArrayAdapter; android.widget.ListView;

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread


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

5.4. ListActivities with flexible layout


The above example uses one layout for all rows. 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. In this method we will read the pre-defined layout via LayoutInflator and return one individual view per row. Create the following class "MyArrayAdapter.java".

package de.vogella.android.listactivity; import import import import import import import android.app.Activity; android.view.LayoutInflater; android.view.View; android.view.ViewGroup; android.widget.ArrayAdapter; android.widget.ImageView; android.widget.TextView;

public class MyArrayAdapter extends ArrayAdapter<String> { private final Activity context; private final String[] names; public MyArrayAdapter(Activity context, String[] names) { super(context, R.layout.rowlayout, names); this.context = context; this.names = names; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView = inflater.inflate(R.layout.rowlayout, null, true); TextView label = (TextView) rowView.findViewById(R.id.label); label.setText(names[position]); System.out.println(names[position]); // Change the icon for Windows and iPhone if (names[position].startsWith("Windows7") || names[position].startsWith("iPhone") ) { ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); imageView.setImageResource(R.drawable.alt_window_16); } return rowView; }

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

package de.vogella.android.listactivity; import import import import import android.app.ListActivity; android.os.Bundle; android.view.View; android.widget.ListView; android.widget.Toast;

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

Ads by Google

Google Android

Android Gui

Android Code

Android App Download

6. Menu, Preferences and Intents


6.1. Project
This chapter will demonstrate how to create and evaluate a menu, how to define preferences and how to navigate between activities via an intent . Create a project "de.vogella.android.preferences" with the activity "HelloPreferences". Change the UI in the file "/res/layout/main.xml" to the following:

< ? xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.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.2. Add a menu


Menus can be defined via XML files. Select your project, right click on it and select New -> Other -> Android -> "Android XML File".

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

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

Change your class "HelloPreferences" to the following. The OnCreateOptionsMenu method is used to create the menu. Please note that at the moment nothing happens if you select this menu. The behavior will be later implemented in the method "onOptionsItemSelected".

package de.vogella.android.preferences; import import import import android.app.Activity; android.os.Bundle; android.view.Menu; android.view.MenuInflater;

public class HelloPreferences extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) {

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread


MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } }

Run your application and press "Menu" on the emulator. Your menu should be displayed.

6.3. Using preferences


Preference values can also be stored as a XML resource. Create another Android XML File "preferences.xml" this time of type preferences.

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

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

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

Create the class "Preferences" which will load the "preference.xml".

package de.vogella.android.preferences; import android.os.Bundle; import android.preference.PreferenceActivity; public class Preferences extends PreferenceActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); }

Select "AndroidManifest.xml" and the tab "Application". Add the activity "Preferences".

To use the preferences add a button to your main.xml with the id "@+id/Button01" and change the coding of HelloPreferences to the following.

package de.vogella.android.preferences; import import import import import import import android.app.Activity; android.content.Intent; android.content.SharedPreferences; android.os.Bundle; android.preference.PreferenceManager; android.view.Menu; android.view.MenuInflater;

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread


import import import import import android.view.MenuItem; android.view.View; android.view.View.OnClickListener; android.widget.Button; android.widget.Toast;

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

6.4. Run
Run your application. Press the "menu" hardware button and then select your menu item "Preferences". 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. The saved values should be displayed in a small message windows (Toast).

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

Ads by Google

Java Android

Android Tutorial

Android Phone

Android Applications

7. ContentProvider
7.1. Overview
ContentProvider are used to provide data from an application to another. ContentProvider do not store the data but provide the interface for other applications to access the data. The following example will use an existing context provider from "Contacts".

7.2. Create contacts on your emulator


Select the home menu and then the menu entry "Contacts" to create contacts.

Press Menu and select "New Contact".

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

As a result you should have a few new contacts.

7.3. Example
Create a new Android project "de.vogella.android.contentprovider" with the activity "ContactsView". Rename the id of the the existing TextView from the example wizard to "contactview". Delete the default text. Also change the layout_height to "fill_parent". The resulting main.xml should look like the following.

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

In AndroidManifest.xml add the User Permission that the application can use "android.permission.READ_CONTACTS". Change the coding of the activity.

package de.vogella.android.contentprovider;

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread


import import import import import import android.app.Activity; android.database.Cursor; android.net.Uri; android.os.Bundle; android.provider.ContactsContract; android.widget.TextView;

public class ContactsView extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView contactView = (TextView) findViewById(R.id.contactview); Cursor cursor = getContacts(); while (cursor.moveToNext()) { String displayName = cursor.getString(cursor .getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); contactView.append("Name: "); contactView.append(displayName); contactView.append("\n"); } } private Cursor getContacts() { // Run query Uri uri = ContactsContract.Contacts.CONTENT_URI; String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + ("1") + "'"; String[] selectionArgs = null; String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; return managedQuery(uri, projection, selection, selectionArgs, sortOrder); } }

8. ScrollView
ScrollViews can be used to contain one child that might be to big to fit on one screen. If the child is to big the ScrollView will display a scroll bar to scroll the context. Of course the child can be a layout which can then contain other elements. Create an android project "de.vogella.android.scrollview" with the activity "ScrollView". Create the following layout and class.

< ? xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.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.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.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"></Button> </LinearLayout> </LinearLayout> </ScrollView>

package de.vogella.android.scrollview; import import import import android.app.Activity; android.os.Bundle; android.view.View; android.widget.TextView;

public class ScrollView extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView view = (TextView) findViewById(R.id.TextView02); String s=""; for (int i=0; i < 100; i++) { s += "vogella.de "; } view.setText(s); } }

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.

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

9. Services and Broadcast Receiver


The Android platform provides a lot of pre-defined services, usually exposed via a Manager class. In this chapter we will use the AlertManager and VibratorManager. The alarm manager will in our example our own broadcast receiver. Create a new project "de.vogella.android.alarm" with the activity "AlarmActivity". Create the following layout.

< ? xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.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" 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. This class will get the Vibrator service.

package de.vogella.android.alarm; import import import import import android.content.BroadcastReceiver; android.content.Context; android.content.Intent; android.os.Vibrator; android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Don't panik but your time is up!!!!.", Toast.LENGTH_LONG).show(); // Vibrate the mobile phone Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(2000); } }

Maintain this class as broadcast receiver in "AndroidManifest.mf" and allow the vibrate authorization.

< ? xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="de.vogella.android.alarm" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AlarmActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".MyBroadcastReceiver" android:enabled="true"> </receiver> </application> <uses-sdk android:minSdkVersion="8" />

<uses - permission android:name="android.permission.VIBRATE"></uses-permission> </manifest>

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

Now define your main Activitiy. This activity will create an Intent for the Broadcast receiver and get the AlarmManager service.

package de.vogella.android.alarm; import import import import import import import import android.app.Activity; android.app.AlarmManager; android.app.PendingIntent; android.content.Intent; android.os.Bundle; android.view.View; android.widget.EditText; android.widget.Toast;

public class AlarmActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startAlert(View view) { EditText text = (EditText) findViewById(R.id.time); int i = Integer.parseInt(text.getText().toString()); Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent); Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show(); } }

10. Important views


10.1. LogCat View
You can see the log (including System.out.print() statements) via the LogCat view.

10.2. File explorer


The file explorer allows to see the files on the android simulator.

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

11. Shell
11.1. Android Debugging Bridge - Shell
You can access your Android emulator also via the console. Open a shell, switch to your "android-sdk" installation directory into the folder "tools". 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, e.g. ls, rm, mkdir, etc. The application data is stored in the directory "/data/data/package_of_your_app". If you have several devices running you can issue commands to one individuel device.

# Lists all devices adb devices #Result List of devices attached emulator-5554 attached emulator-5555 attached # Issue a command to a specific device adb - s emulator-5554 shell

11.2. Uninstall an application via adb


You can uninstall an android application via the shell. Switch the the data/app directory (cd /data/app) and simply delete your android application.

11.3. Emulator Console via telnet


Alternatively to adb you can also use telnet to connect to the device. This allows you to simulate certain things, e.g. incoming call, change the network "stability", set your current geocodes, etc. Use "telnet localhost 5554" to conntect to your simulated device. To exit the console session, use the command "quit" or "exit". For example to change the power settings of your phone, to receive an sms and to get an incoming call make the following.

# 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. Deploy your application on a real device


Turn on "USB Debugging" on your device in the settings. Select in the settings Applications > Development, then enable USB debugging. You also need to install the driver for your mobile phone. For details please see Developing on a Device . Please note that the Android version you are developing for must be the installed version on your phone. To select your phone, select the "Run Configurations", select "Manual" selection and select your device.

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

Android Development Tutorial - Gingerbread

13. Thank you


If you like this tutorial please support this website.

14. Questions and Discussion


Before posting questions, please see the vogella FAQ . If you have questions or find an error in this article please use the www.vogella.de Google Group . I have created a short list how to create good questions which might also help you.

15. Links and Literature


Ads by Google Android Software Android 2.1 Android Mobile Android TV

15.1. Source Code


Source Code of Examples

15.2. Android Resources


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 SQL light 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

http://www.vogella.de/articles/Android/article.html[12/8/2010 1:59:51 PM]

You might also like