Wednesday, December 7, 2011

How to Create HelloAndroid or Your First Android Application

First thing you have to set up the Environment to run the Android application. If you don't done so far. you can follow this link to setup your Android SDK.
http://agileswaran.blogspot.com/2011/12/simple-and-easy-way-to-install-android.html

  •  Open eclipse
  •  After that go to File<New<Other




  • It's open another window then Select Android Folder<Android Project

  • Then Specify your project Name, Build Target and Application Info


  • After give all details click finish to create your Android project.
  • Open your src folder<java class
In first Example I explain about layout set by . XML class this is located under res<layout folder in your project.
So you can easily add buttons, textview, image, etc via XML layout.

import android.app.Activity;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}
}

Second Example,  I explain about layout set by programming.
Display the "Hello,Android" via programming. 

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid 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, Android");
    setContentView(tv);
 }
}
Finally simply hit F11 to build and run the your project.


How to show another activity in android when button click


Using Intent in an Android application to show another activity

In my Android application, I have two activity classes FirstActivity and Second Activity. I have a button on the first one and I want to show the second when it is clicked.


public class FirstActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);  
Button firstButton = (Button)findViewById(R.id.first); 

firstButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
    startActivity(intent);
  }
});
}
}
The second class that should show when the button is clicked:

 public class SecondActivity extends Activity {

 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Button secondButton = (Button) findViewById(R.id.second);

secondButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    finish();
  }
});
}
}
Important: add this line to your AndroidManifest.xml:
 <activity android:name=".SecondAcitivty" />