Version 3.8
Copyright © 2009 - 2010 Lars Vogel
16.08.2010
| Revision History | ||
|---|---|---|
| Revision 0.1 | 04.07.2009 | Lars Vogel |
| Created | ||
| Revision 0.2 - 2.5 | 08.07.2009 - 10.05.2010 | Lars Vogel |
| bug fixes and enhancements | ||
| Revision 2.6 | 23.05.2010 | Lars Vogel |
| Update to Android 2.2 | ||
| Revision 2.7 - 3.78 | 30.05.2010 - 16.08.2010 | Lars Vogel |
| bug fixing and enhancements | ||
Table of Contents
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 but you have to use the Android compiler to create Android specific byte-code.
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.
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.
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".
The following assume that you have already Eclipse installed. For details please see Eclipse Tutorial .
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" .
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/ .
In Eclipse open the Preferences dialog via Windows -> Preferences. Select Android and maintain the installation path of the Android SDK.

Select now Window -> Android SDK and AVD Manager from the menu.

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

Press "Install selected" and confirm the license for all package.
After the installation restart Eclipse.
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".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.

Things are not always working as they should be. Several users report that get the following errors:
Project ... is missing required source folder: 'gen'
The project could not be built until build path errors are resolved.
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 .
Select File -> New -> Other -> Android -> Android Project and create the Android project "de.vogella.android.temperature". Maintain the following.

Press "Finish". This should create the following directory structure.

"R.java" is a generated class which contains the text and the UI elements. Please do not try to modify this class manually.
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:

Modifying "string.xml" gives currently a NPE, for details see the Bug report . As a workaround you can select Window -> Preferences -> XML -> XML Files -> Editor. Uncheck "Use inferred grammar in absence of DTD/Schema".
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.
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 | Value |
|---|---|
| buttonHandler | myClickHandler |
| celsius | to Celsius |
| fahrenheit | to Fahrenheit |

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">Celsius to Fahrenheit 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>
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.

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

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

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>
Change your code in "Convert.java" to the following. Note that the "myClickHandler" will be called basedon the "On Click" property of your button.
package de.vogella.android.tempconvertor;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import 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
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;
}
}
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.
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;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import 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();
}
}

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

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 android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import 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) {
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.

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

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



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 android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import 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;
}
}
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).


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".
Select the home menu and then the menu entry "Contacts" to create contacts.

Press Menu and select "New Contact".

As a result you should have a few new contacts.

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;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import 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);
}
}
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 android.app.Activity;
import android.os.Bundle;
import android.view.View;
import 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.

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 command "adb shell".
The emulator console lets you dynamically access your simulated device. Use "telnet localhost 5554" to conntect to your simulated device. To exit the console session, use the command "quit" or "exit".
# connects to device telnet location 5554 # set the power leve 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
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.


Thank you for practicing with this tutorial.
I maintain this tutorial in my private time. If you like the information please help me by using flattr or donating or by
|
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. .