Tuesday, July 31, 2012

Learn Android Operating System – Part 2

Hello World – First program in Android
After you have created a AVD (more details in: Learn OS Android – Part 1), you can create the first program in Android. For this you should follow these steps:
  •      In Eclipse select File -> New -> Android Project
  •      Complete these fields as follows:
  •      Project name: HelloWorld
  •      Build Target platform that will run the application (for Android 2.3.3 below)
  •      Application name: HelloWorld
  •      Package name: org.helloworld
  •      Create Activity: HelloWorld


After you click Finish Eclipse will create a new Android project with specific structure. If you look in the file: HelloWorld -> src -> org -> HelloWorld -> HelloWorldActivity it should look like:
package org.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorldActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
Edit this file like this:
package org.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloWorldActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        tv.setText(“Hello, World”);
        setContentView(tv);
    }
}
In this case we created a TextView and I used setText method to set the text “Hello, World”.
Running Android
To run the application will be in Eclipse to select Run -> Run and then Android Application. We have to wait to start emulator (may take a few minutes) and then after the application is installed you will need the following screen:

No comments:

Post a Comment