Google Android Development for Windows
Programming with Google Android and Eclipse
This article describes how to create Android applications with Eclipse.
The article is based on Eclipse 3.5 and Android 2.1.
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).
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 a special Bytecode so that you have to use the Android compiler to create this special 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.
An Android application consists out of the following parts:
- Activity – A screen in the Android application
- Intent / Broadcast Receiver – allow the application to request and / or provide services from other application. For example the application call ask via an intent for a contact application. Application register themself via an IntentFilter
- Services – Background activities without UI
- Content Provider – provides data to applications, Android contains a SQLLite DB which can serve as data provider
An Android application is described the file “AndroidManifest.xml”. This files contains all classes of the application and the required permissions for the application, e.g. if the application requires network access. “AndroidManifest.xml” can be thought as the deployment descriptor for an Android application.
The following assume that you have already Eclipse install. For installing and using Eclipse please see Eclipse Tutorial
To use Android you need to install the Eclipse Android Plugin and the base Android SDK. Afterwards you can install different Android versions via the Eclipse Android plugin . You will also need to configure a device which will be used to emulate your real device.
Use the update manager of Eclipse to install all available plugins for the Android Development Tools (ADT) from the URL https://dl-ssl.google.com/android/eclipse/ . See Using the Eclipse update manager for details on how to use the update manager and how to install new plugins.
Tip
Ehe Eclipse Android SDK does not seem to have an option to install the Android (Java) source code to make it available in Eclipse. Please join me in starring at bug Make Android Source available in Eclipse – Bug report .
Download the Android SDK from the Android homepage under Android Homepage .
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” .
In Eclipse open the Preferences dialog via Windows -> Preferences. Select Android and maintain the installation path of the Android SDK.

Tip
If you maintain the location the Android plugin will remind you frequently (and for every workspace). 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.

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”.
To test if you setup is correct, eelect your device and press “Start”.

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

Tip
You can use the perspective “DDMS” to monitor your device.
. Select File -> New -> Other -> Android -> Android Project and create the Android project “de.vogella.android.first” Maintain the following.

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

“R.java” is a generated class which contains the text and the UI elements. Please do not try to modify this class manually.
Select “layout/main.xml” and open the editor via double-click. The result should look like the following.

From the “Views” bar, drag in an “EditText” and three “Buttons”. The result should look like the following.

Tip
Check the file “R.java”. It will contain your new elements.
Select “values/string.xml” and press “Add”.

Select “Color” and maintain “white” as the name and “#FFFFFF” as the value.

Go back to “main.xml”, select the complete widget and use the Properties view to set the background to this attribute.

Change your code in “Hello.java” to the following.
package de.vogella.android.first;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Hello extends Activity {
private EditText text;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // bind the layout to the activity
text = (EditText) findViewById(R.id.EditText01);
text.setText("No button pressed");
}
// Will be connected with the buttons via XML
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.Button01:
text.setText("Button 1 was clicked");
break;
case R.id.Button02:
text.setText("Button 2 was clicked");
break;
case R.id.Button03:
text.setText("Button 3 was clicked");
break;
}
}
}
Tip
The next chapter will connect the handler methods with the buttons via XML.
Open again “main.xml” and select your first button. Via the property view assign the method “myClickHandlerButton” to the “on Click” property of the first button.

Assign “myClickHandlerButton” also to the other buttons.
Switch to the “main.xml” tab.

The resulting “main.xml” file 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"
android:background="@color/white">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
<Button android:text="@+id/Button01" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClickHandler"></Button>
<Button android:text="@+id/Button02" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClickHandler"></Button>
<Button android:text="@+id/Button03" android:id="@+id/Button03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClickHandler"></Button>
</LinearLayout>
To start the Android Application, select your project, right click on it, Run-As-> Android Application
Tip
Be patient, the emulator is sometimes very slow.
You should get the following result.

The last chapter explained how you can run your application in the emulator. To see how you can deploy your application to a real device 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.


Android allows to access the network via the the java.net.URL class.
Tip
You can also read XML, e.g. RSS feeds. Unfortunately Android does not have a Stax parser included in it SDK. Vote for Android should have a Stax parser to get support. Currently you have to use the android specific class XmlPullParser.
To set the proxy you can use the class Settings. For example you could add the following line to your onCreate method in your activity.
Settings.System.putString(getContentResolver(), Settings.System.HTTP_PROXY, "myproxy:8080");
Tip
It seems that DNS resolving doesn’t work behind a proxy. See Bug 2764
You also have to give your application the right to change the settings “android.permission.WRITE_SETTINGS” in “AndroidManifest.xml”.

Create the project “de.vogella.android.network.html”. Add the following elements to your activity:
- EditText with the ID “address”
- TextView with the ID “pagetext”
- Button with the ID “ReadWebPage”
Create the following code to read a webpage and show the HTML code in the TextView.
This example also demonstrate the usage of Android preferences to store user data. The URL which the user has typed is stored in the preferences in the method onPause(). This method is called whenever the Activity is send into the background.
package de.vogella.android.network.html;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class ReadWebpage extends Activity {
private static final String PREFERENCES = "PREFERENCES";
private static final String URL = "url";
private String lastUrl;
private EditText urlText;
private TextView textView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
urlText = (EditText) findViewById(R.id.address);
textView = (TextView) findViewById(R.id.pagetext);
loadPreferences();
urlText.setText(lastUrl);
}
/**
* Demonstrates loading of preferences The last value in the URL string will
* be loaded
*/
private void loadPreferences() {
SharedPreferences preferences = getSharedPreferences(PREFERENCES,
Activity.MODE_PRIVATE);
// Set this to the Google Homepage
lastUrl = preferences.getString(URL, "http://209.85.229.147");
}
@Override
protected void onPause() {
super.onPause();
SharedPreferences preferences = getSharedPreferences(PREFERENCES,
Activity.MODE_PRIVATE);
Editor preferenceEditor = preferences.edit();
preferenceEditor.putString(URL, urlText.getText().toString());
// You have to commit otherwise the changes will not be remembered
preferenceEditor.commit();
}
// Will be connected with the buttons via XML
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.ReadWebPage:
try {
textView.setText("");
// Perform action on click
URL url = new URL(urlText.getText().toString());
// Get the response
BufferedReader rd = new BufferedReader(
new InputStreamReader(url.openStream()));
String line = "";
while ((line = rd.readLine()) != null) {
textView.append(line);
}
}
catch (Exception e) {
System.out.println("Nay, did not work");
textView.setText(e.getMessage());
}
break;
}
}
}
Assign the handler “buttonHandler” to the button in the property “on Click”. via your XML.
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”.
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 Application.xml add the Permission that the application can use “android.permission.READ_CONTACTS”.
Change now your coding of your activity.
package de.vogella.android.contentprovider;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
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 = getContentResolver().query(Contacts.CONTENT_URI, null, null, null, null);
while(cursor.moveToNext()){
String displayName = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
contactView.append("Name: ");
contactView.append(displayName);
contactView.append("\n");
}
}
}
Tip
Currently the contentProvider does not return any data. Looks like the content provider has been changed but the content provider documentation still refers to the People class. If you find a solution please email me.
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”.
For example you can set your geolocation in the emulator via “geo fix -121.45356 46.51119 4392″
For more information on the emulator console please see Emulator Console manual
The location API allow you to determine your current location. The following requires that you have installed the Googles API (see installation) and a valid Google map API key. Go to Obtaining a Maps API Key to get one.
Create a new device which supports the Google API’s. During device creation select the target Google API’s in the version of your SDK.

Create a new project “de.vogella.android.locationapi”. Make sure to select the Google API

Add the following permissions to your application in Android.xml.
- INTERNET
- ACCESS_FINE_LOCATION
- ACCESS_COARSE_LOCATION
Tip
The maintenance of “Uses permissions” should be enhanced. Please stare at Bug: Permissions should support field assists to get this improved.
You need to add the Google maps library to your application. Open Android.xml, tab Application and add a “Uses library”.

Define your view layout like the following.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.maps.MapView
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey="Your Maps API Key"
/>
</RelativeLayout>
Tip
Replace “Your Maps API Key” with your Google API key.
Create the following activity. This activity use an LocationListner to update the map with the current location.
package de.vogella.android.locationapi; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.RelativeLayout; import







This article was very helful for me..so i decided to share it with you..all the credits goes to vogella..hats off to him..
Like or Dislike:
2
0