Sunday 19 October 2014

Android "Hello World" Application development tutorial

Goal

In this post I will show how can we make an Android application. The aim would be very simple - Create an App (.apk file). Install it on my Moto E running Kitkat , run the app. The App will have a button which on click will show "Hello World" text for some time [Also called toast].


Hoping you have already downloaded and installed Android ADT bundle. My Moto E android device is running Kitkat (Android 4.4/ API 19). So that's what I am going to target. You may choose your own target OS versions. Before proceeding with Android project read my previous posts on some Android Basics


Creating Project






  • Open your Eclipse. Go to File -> New -> Android Application Project.
  • Fill in project details. I am naming it "HelloWorld". Also as stated earlier I am going to target Kitkat as target OS. Minimum can be set to Froyo.

  • Leave the options in the next screen to default.Click Next.

  •  If you want your own icon for the App go ahead provide one. For this project I am going to keep everything default.So click on next.

  • Select to create a black Activity. We will edit this activity so suit our requirements. Select Next.

  • Give the name you wish to your Activity. I am giving it "HelloWorldMainActivity". You will automatically get a corresponding name for the activity layout.

  •  Click on Finish to finish creating your project.


  • After creating your project, the project structure would be as below -


    To the Code.....


    First lets modify the layout to suit our requirements.

    Modify activity_hello_world_main.xml file in your layout folder to below. Replace whatever content it has by the following content -

    activity_hello_world_main.xml


    <?xml version="1.0" encoding="UTF-8"?>
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
        android:layout_width="fill_parent"
    
        android:layout_height="fill_parent"
    
        android:layout_gravity="center"
    
        android:orientation="vertical"
    
        android:padding="35dip" >
    
    
    
        <TextView
    
            android:layout_width="fill_parent"
    
            android:layout_height="wrap_content"
    
            android:layout_marginBottom="20dip"
    
            android:gravity="center"
    
            android:text="@string/author"
    
            android:textSize="24.5sp" />
    
    
    
        <Button
    
            android:id="@+id/helloworld_button"
    
            android:layout_width="fill_parent"
    
            android:layout_height="wrap_content"
    
            android:text="@string/click_here" />
    
    
    
    </LinearLayout>
    



    Explanation :

    Basically we are defining a linear layout. There are various layouts in Android - linear layout being one of them. In this we are creating a normal text view to render some text and a button below that. Now lets create our Activity and provide this layout to it. You would already have file HelloWorldMainActivity.java. Replace/Add content in the file to be same as below -

    HelloWorldMainActivity.java


    package com.example.helloworld;
    
    
    
    import android.support.v7.app.ActionBarActivity;
    
    import android.os.Bundle;
    
    import android.view.Menu;
    
    import android.view.MenuItem;
    
    import android.view.View;
    
    import android.view.View.OnClickListener;
    
    import android.widget.Toast;
    
    
    
    /**
    
     * 
    
     * @author athakur
    
     *
    
     */
    
    public class HelloWorldMainActivity extends ActionBarActivity implements OnClickListener {
    
    
    
        @Override
    
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_hello_world_main);
    
            
    
            View continueButton  = findViewById(R.id.helloworld_button);
    
            continueButton.setOnClickListener(this);
    
        }
    
    
    
        @Override
    
        public boolean onCreateOptionsMenu(Menu menu) {
    
            // Inflate the menu; this adds items to the action bar if it is present.
    
            getMenuInflater().inflate(R.menu.hello_world_main, menu);
    
            return true;
    
        }
    
    
    
        @Override
    
        public boolean onOptionsItemSelected(MenuItem item) {
    
            // Handle action bar item clicks here. The action bar will
    
            // automatically handle clicks on the Home/Up button, so long
    
            // as you specify a parent activity in AndroidManifest.xml.
    
            int id = item.getItemId();
    
            if (id == R.id.action_settings) {
    
                return true;
    
            }
    
            return super.onOptionsItemSelected(item);
    
        }
    
    
    
        @Override
    
        public void onClick(View v) {
    
            switch(v.getId()) {
    
            case R.id.helloworld_button : 
    
                Toast.makeText(getApplicationContext(), R.string.hello_world, Toast.LENGTH_LONG).show();
    
                break;
    
    
    
            }
    
            
    
        }
    
    }
    



    Explanation :

    Most of the method should already be generated by Eclipse for you. Some changes that I have done is make the Activity class implement android.view.View.OnClickListener and have overridden the onClick() method.

    To set view for a Activity we use setContentView(R.layout.activity_hello_world_main); method. As mentioned in one of  my earlier posts

    "Resources can be your icons/images that your Application uses, the localized Strings, layouts etc. Android resource compiler compresses and packs the resources and then generates a class named R that contains references or identifiers that you can use your code to reference the resources. "

    So you can reference your resources Strings, layouts, icons using R class. 

    Also if you notice in onCreate() method I am getting a reference of the button we had created in our layout xml and assigning a onClickListener to it. What it means is when user presses this button it should invoke a callback method onClick() of the OnClickListener instance the button is registered with. In our case it is the Activity itself as it is implementing OnClickListener and we have registered button for OnClickListener using this keyword.

    If you notice the xml you have something like android:text="@string/click_here"  and also in your
    Activity wile creating Toast we have R.string.hello_world. So we need to define all these resources. So we have to modify the strings.xml file in res/values folder. Replace/add content to match the following -

    strings.xml

     
    <?xml version="1.0" encoding="utf-8"?>
    
    <resources>
    
    
    
        <string name="app_name">HelloWorld</string>
    
        <string name="hello_world">Hello world!</string>
    
        <string name="action_settings">Settings</string>
    
       
    
        <string name="author">OpenSourceForGeeks</string>
    
        <string name="click_here">Click Here</string>
    
    
    
    </resources>
    


    Explanation :

    Content is quite self explanatory. We define String resources in this file. It has a name and a value. We can reference the String resource using R.string.StringName. Eg. R.string.hello_world.


    Toasts in Android

    Toasts are basically flash messages that are displayed on the screen/Activity for some duration of time. Toasts can be created as 

    //Toast shown for  short period of time
    
    Toast.makeText(getApplicationContext(), "Toast Message", Toast.LENGTH_SHORT).show();
    
    
    
    //Toast shown for long period of time
    
    Toast.makeText(getApplicationContext(), "Toast Message", Toast.LENGTH_LONG).show();
    

    We can also create a custom Toast by providing a custom Layout to it. Eg.

    Toast myToast = new Toast(getApplicationContext());
    
    myToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    
    myToast.setDuration(Toast.LENGTH_LONG);
    
    myToast.setView(myLayout);
    
    myToast.show();
    


     That's it for the code part of it. Let's see the demonstration.


    Demonstration

    Right click the project in Eclipse -> Select Run as -> Android Application. You should see following screen. Choose your device. If you don't have one you can create virtual device. I have my own device so I am going to use that. If you have problems recognizing your devices go through the following posts I have written before.


    Device selection screen is as follows -




    After you select Ok then the app should get installed in your device and open the app on it's own.



    Go ahead click on the button and you should see "Hello World!" toast message on the screen.


    That's it for creating an Android hello World Application!

    Related Links

    1 comment:

    1. Amazing Android Application development tutorial sharing this post, excellent cording with info-graphics. So sharing more helpful post for Android apps development tutorials...


      Best Android Apps Development

      ReplyDelete

    t> UA-39527780-1 back to top