Friday, 5 July 2013

LIFECYCLE of an ACTIVITY (Part 1)

Hello Friends,
            Welcome you all in the Android Tutorial.



Today we are going to learn about the very important component of android application “ACTIVTY” and it’s LIFECYCLE.

Like any other programming language like C, C++ or Java where the execution of the code starts from the main() function.
In android same thing can be achieved by the ACTIVITY. In android application main activity is behave like main() function.

What is an Activity?

An Activity provides a user interface, from where the user can interact with our android application.
Each activity is a single screen. An android application can have multiple activities.
            Main activity is same like any other activity but main activity is the one who interacts with the user first time when they start the application.
An activity can start another activity also in order to perform different actions.

Lifecycle of an Activity:-
           
         The following diagram shows the Lifecycle of an Activity:-



The key parts of the lifecycle are the “system calls”.
With the help of these system calls, activity changes his state from one to another.
There are only three main states of the Lifecycle, which can be static.
They are:-
1)    Resumed
2)    Paused
3)    Stopped

Resumed:-
In this state an activity is visible to the user. User can interact with the activity at this time. We can also refer this state as a “Running” state.

Paused:-
Suppose activity A is in Resumed/Running state. At this time another activity B came up in the Running state. Activity B has not covered the entire screen or we can say activity B is semi-transparent.

            This time activity A moved into the Paused state.
In Paused State, activity A does not interact with the user and cannot execute any code.

Stopped:-
            In this state activity is completely hidden or not visible to the user.
            We can say activity is running in the background.
In this state activity instance and its state information like member variables are retained.
In this state also activity cannot execute any code.

When user first time launches the application, the system create the new instance of the Activity by calling onCreate() method.
Once onCreate() finishes execution, the system calls the onStart() and onResume()  method and the Activity moved into the Resumed/Running State.

onCreate() is the very first lifecycle callback and onDestroy() is the very last.

It is not necessary to implement all the lifecycle methods. It’s all depend on the requirement of the application what we develop.




In the next part of ACTIVITY LIFECYCLE, we will be writing some code and trying to understand how to start an Activity and how to move from one state to another.





Thanks for reading, please give your suggestion.

Please share it !!!

Wednesday, 3 July 2013

How to communicate between separate Activities

Hello Friends,
            Welcome you all in the Android tutorial.

Today we are going to learn “How to communicate between separate Activities”?

We have already developed the GUI application for an android device.
That application has First_Name , Last_Name text-field and one send Button.

We are going to use the same GUI application in today’s session. If you have not created the application please refer the following link:-

How to develop a Graphical User Interface ( GUI ) 


In today’s topic we will create another activity which displays the First_Name and Last_Name on the screen, send by the MainActivity of the GUI application.

Let’s start:-

Step 1: Define a function that handles the onClick event of the Button
           
            In MainActvity.java  add the following line :-

   /* sendData handles the onClick event*/
       public void sendData(View view) {

       }

            Must have condition for the function that handles the onClick event are :-
           ·        It must be public
           ·        It must have a void return type
           ·        It must have a View as the only parameter.

           
Step 2: Add the onClick attribute to the Button

            android:onClick=”sendData”

           sendData is the function which responds to the onClick event. Add onClick attribute on <BUTTON> element in activity_main.xml file.

Step 3: Binding of two Activities
           
            Binding of separate components can be achieved by the Intent object.
           “Intent” provides the run-time binding between separate components (for example between two activities).
           
           Syntax:-
                        Intent intent = new Intent (this, DisplayActivity.class);

            Intent constructor here takes two parameter.
             ·     A Context as the first parameter. We are passing this because Activity class is a subclass of Context.
            ·    The Class of the application component to which the system should deliver the Intent.
            We should deliver the Intent to the another activity named as DisplayActivity. 
            We are going to create this activity later.

Step 4: Create a message what you want to pass it to another activity

            We have designed two Text-Fields in our GUI app.
            We will fetch those data and send it to another activity.
            Check the following code:-
            
            Intent intent = new Intent(this, DisplayActivity.class);
     EditText editText = (EditText) findViewById(R.id.first_name);
     String message = editText.getText().toString();
     
     editText = (EditText) findViewById(R.id.last_name);
     message +="__"+editText.getText().toString();

          findViewById() we are using to find the EditText according to id.
           

            Our modified MainActivity.java code will look like as follows:-
        package com.example.firstgui;

        import android.os.Bundle;
        import android.app.Activity;
        import android.content.Intent;
        import android.view.Menu;
        import android.view.View;
        import android.widget.EditText;

        public class MainActivity extends Activity {
 
 public final static String EXTRA_MESSAGE = "Message from MainActivity";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is                 present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 /** Called when the user clicks the Send button */
 public void sendData(View view) {
     // Do something in response to button
  Intent intent = new Intent(this, DisplayActivity.class);
     EditText editText = (EditText) findViewById(R.id.first_name);
     String message = editText.getText().toString();
     
     editText = (EditText) findViewById(R.id.last_name);
     message += "__"+editText.getText().toString();
     
     message ="Welcome , "+message;
     intent.putExtra(EXTRA_MESSAGE, message);
     startActivity(intent);
 }
      }


            In EXTRA_MESSAGE we are keeping some constant message.

          Our modified activity_main.xml file will look like as follows:-
 
    

    
    
    
    
    
    


    

Step 5: Create the Second Activity

               Steps to follow :-

            a)  File à New à Other à Android à AndroidActivity
            b)  Select BlankActivity, click Next.
            c)  Select the GUI Project, “FirstGUI”
            d)  Activity name “DisplayActivity”
            e)  Hierarchical Parent , select the MainActivity of the FirsrGUI app
            f)  Click Finish.





Step 6: Receive the Intent
           
            We can get the Intent by calling getIntent() function. We can also retrieve the data contained within it.


Step 7: Display Message

            We are using a TextView widget to show the received message on the Screen.

            Modify the onCreate() of the DisplayActivity.java , as follow :-
 
         protected void onCreate(Bundle savedInstanceState) 
         {
  super.onCreate(savedInstanceState);
  
   // Get the message from the intent
     Intent intent = getIntent();
     String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

     // Create the text view
     TextView textView = new TextView(this);
     textView.setTextSize(40);
     textView.setText(message);

     // Set the text view as the activity layout
     setContentView(textView);
  }

           
           


Clean and Build your Project. Test it with Emulator or Android Device.






Please give your valuable suggestions / comments. Do not forgot to share :)


Tuesday, 2 July 2013

How to Setup Android Developer Tool and "Hello World" of the Android


Hi Friends,
            Welcome you all in the Android Tutorial. 

Today we will learn "How to Setup the Android Developer Tool (ADT)" and "How to create first android Application".

           

First of all we will setup our development environment for Android.
For that you need to download the ANDROID DEVELOPER TOOL (ADT).

You can use the following link to download the ADT :-
http://developer.android.com/sdk/installing/bundle.html

            This single bundle gives everything you need for developing apps.
1)    Eclipse + ADT plugin
2)    Android SDK Tools
3)    Android Platform-tools
4)    Simulator

Setting up the Developer Tool:-
1)    Unzip the zip file named adt-bunlde-<os-platform>.zip and save it to some location where you want to save.
2)    Move to adt-bundle-<os-platform>/eclipse/ directory and run the eclipse exe.


Create our first Android Project:-

The steps for creating a new Android Application are as follows:-

1)    Go to File à New  and click on Android Application Project.






2)    Write your application name in the Application Name.

a.     Project Name: is the name of your project directory.

b.     Package Name: is the name package namespace.

c.      Minimum Required SDK: is the lowest version of Android that your app support.
d.     Target SDK: is the highest version of Android what your app support.
e.     Compile With: is the platform version against which your app will compile.
f.       Theme specifies: the Android UI style apply for your app.
3)    Click on the next button.
4)    Leave the next screen default and click on the next button.
5)    Next screen is the launcher icon screen. You can customize also. Leave this screen as default , click on the next button.
6)    Next screen belongs to the activity template. For this project select BlankActivity and click next button.
7)    Leave the next screen default and do Finish.
                      
   Now your first android application is ready with some default files.





How to Run on the Emulator:-

            First of all before running our application on the Emulator, we need to create an Android Virtual Device (AVD).
            
1)    Click on the Android Virtual Device Manager.
    The following image shows how AVD manager look like.


2)    Click on New Button. Type AVD name. I have given Galaxy Nexus. Select Device, choose Galaxy Nexus device. We will try to run our application on Galaxy Nexus emulator.








3)    Click on the OK button.

4)    Select your AVD device and click on the start button.

5)    Click on the Launch Button.


6)    You might get some error like the following image.


7)    To fix this error, select your AVD device and click on the edit button, change the ram size to 512.
8)    Start your AVD once again. This will take some long time.
9)    Then unlock your emulator screen.
10)           Click Run Button from the toolbar. 
         This will run your first application on the Emulator.

Your application on the Emulator will look like this.






Porting of the application on an Android Device:-
1)    Plug in your device to the development machine with a USB cable.
2)    Enable USB DEBUGGING on your device.
a.     On device Android 3.2 or older,  you can find this option under Settings à Applications à Development.
b.     On Android 4.0 and newer, it’s in Settings à Developer options.
On Android 4.2 and newer versions, Developer options is hidden by default. To make it available go to Setting à About phone and tap Build number seven times.
Return to previous screen to find the Developer option.

If you are developing on Windows then you might need to install a proper USB drive for you device.
If you are connected with net windows 7 will automatically install the proper driver.
The following link helps to install driver related things.


3)    Open your first application project and click on the RUN menu and select Run Configuration.
4)    Go to Target Tab.


5)    Select Always prompt to pick device and click on the run button
6)    Then choose a running Android device.
7)    Click ok.
Then you will see some messages on console window like Uploading FirstApp.apk on device.
Installing FirstApp.apk
Success!

Check it out your android device; you will be seeing the application running.

Enjoy your First Android Application buddies. 


Do comments, ask questions, and don't forgot to share it with your buddies.






                                

Android Tutorial Index

How to develop a Graphical User Interface ( GUI ) application for an Android



Hello Friends,
Welcome you all in the Android Tutorial.
Today we will learn how we can develop a GUI application for an Android.


            To develop a GUI app for an android is very easy.
            There are two main things we need to think before creating any GUI application.
            1)        User Interface
            2)        Layout
           
            1) User Interface:-
                        What are the interfaces you are providing to the user as a part of your GUI application?
                        These UI (user interface) interacts with user directly.
                        User Interfaces are like buttons, text fields, list, radio-button etc.
                       
            2) Layout:-
                        The second important thing is how we are positioning the UI in our GUI app.
                        Like you want to put all the UIs in a linear format, vertical format or grid format etc.
                       
            In our Fist GUI application, we are going to use two UIs. They are text field and button.
            And layout we are going to use is Linear Layout.
           
                       
            To build a GUI application for an android we use View and ViewGroup Objects.
            Views are like UI widgets. Example button, textbox, radio button etc.
            ViewGroup are invisible containers. This defines how the views are laid out. Example in grid format or in a linear format, or like vertical format.
           
            Let's start with creating a new Project:-
           
            Step 1: Create a New Project
           
                        File --> New --> Android Application Project
                       Give "FirstGUI" as your application name.
                        and Press Finish.
           
Your "FistGUI" application has been created with default “BlankActivity".
                       
            Step 2: Create a Layout
           
                        Open the activity_main.xml file from the layout directory.
                        Replace the Relativelayout with the LinearLayout.
                        Add the "vertical" orientation.
                        Delete the TextView from the activity_main.xml file. We do not need    this in our current project.
                        So the modified activity_main.xml file will be looking like as follows:-


      

           Step 3:  Add User Interface widgets
           
                        Add a TextField. We will use it for “FirstName”.
                       
                        To create a user editable text field we use will use <EditText> element.
                        Add the following code into your activity_main.xml inside the LinearLayout.

 
  
                      Add another TextField. We will use it for “LastName”.

 
                        

            Let’s have a brief info of some contents:-
           
            a)        android:id: This provides a unique identifier for the view, which we can use to reference the object from the code. Example to read and manipulate the object.
           
                        @ sign is required when we are referring to any resource object from XML.
                        + sign before the resource type is needed only when we are defining a resource ID for a first time.
                       
                        When we compile the app, the SDK use the ID name to create a new resource ID in your project's gen/R.java.
                       
            b)        android:layout_width and android:layout_height:
                        We are not specifying any size for the width and height. We are using the "wrap_content".
                        So the textfield size only as big as needed to fit the contents.
                       
            c)         android:hint
                        We can put the default string to display when the text field is empty.
                        We can hardcode the default value or we can use “@string/first_name" value refers to a string resource defined in a separate file.
                       
       
        Step 4: Add the default string
       
            Open the strings.xml file from the /res/values directory
           Add the following string name, so that we can access it from the other files:-           

First Name
Last Name
Send
                       
            Step 5: Add a Button
           
                      Copy the following code int the activity_main.xml. The following code will add a button into your application.

                       
           
           

 Your final activity_main.xml /res/layout will look like as follows:-


    
    
    
    
    
    




           
Your final strings.xml /res/values will look like as follows:-


    FirstGUI
    Hello world!
    Settings
    First Name
     Last Name
    Send




           
Your "FirstGUI" application is ready, run it and enjoy it ...
Your application will look like as follows :---


              
Do not forgot to share !!!