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

    Activities in Android

    Background

    An Activity in Android represents an User Interface that is rendered on a Single screen. It is what an user sees on Android devices and user interacts. Activity as an entity in Android has it's own set of APIs and life cycle. We will see that in this post.

    Activity Lifecycle

    Each Activity that you write will ultimately extend the class android.app.Activity.

    Android Activity lifecycle is as follows -


    As per the documentation an activity has essentially four states:

    1. If an activity in the foreground of the screen (at the top of the stack), it is active or running.
    2. If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
    3. If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
    4. If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

    Sample Activity

    public class HelloWorldMainActivity extends ActionBarActivity {
    
    
    
        @Override
    
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_hello_world_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.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);
    
        }
    
    }
    

    Declaring the activity in the manifest

            <activity
    
                android:name=".HelloWorldMainActivity"
    
                android:label="@string/app_name" >
    
                <intent-filter>
    
                    <action android:name="android.intent.action.MAIN" />
    
    
    
                    <category android:name="android.intent.category.LAUNCHER" />
    
                </intent-filter>
    
            </activity>
    

    Starting an Activity

    Intent intent = new Intent(this, HelloWorldMainActivity.class);
    
    intent.putExtra("Key", "Value");
    
    startActivity(intent);
    

    Terminating an Activity

    public class TicTacToe extends Activity implements OnClickListener {
    
    
    
        @Override
    
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_tic_tac_toe);
    
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
    
    
    
            View exitButton = findViewById(R.id.exit_button);
    
            exitButton.setOnClickListener(this);
    
        }
    
    
    
    
    
        @Override
    
        public void onClick(View v) {
    
    
    
            switch(v.getId()) {
    
            case R.id.exit_button:
    
                finish();
    
                break;
    
            }
    
    
    
        }
    
    
    
    }
    

    Handling Runtime Changes

    Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate()). The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that match the new device configuration.

    To properly handle a restart, it is important that your activity restores its previous state through the normal Activity lifecycle, in which Android calls onSaveInstanceState() before it destroys your activity so that you can save data about the application state. You can then restore the state during onCreate() or onRestoreInstanceState().

    Note :  Prefer using the onRestoreInstanceState() method than onCreate()  for restoring the instance state. Also the onSaveInstanceState() method is not called back button is pressed.

    Handling the Configuration Change Yourself

    If your application doesn't need to update resources during a specific configuration change and you have a performance limitation that requires you to avoid the activity restart, then you can declare that your activity handles the configuration change itself, which prevents the system from restarting your activity.
    Note: Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.

    For example, the following manifest code declares an activity that handles both the screen orientation change and keyboard availability change:

    <activity android:name=".HelloWorldMainActivity"
              android:configChanges="orientation|keyboardHidden"
              android:label="@string/app_name">
    

    Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.

    Notes  

    • To be of use with Context.startActivity(), all activity classes must have a corresponding <activity> declaration in their package's AndroidManifest.xml.
    • Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.
    • We can call finish() in an Activity to terminate it and return all the resources to OS.
    • When you rotate your Screen on Android device Activity is actually destroyed and recreated. However you can change this behavior by handling such configuration changes in your activity.

    Some time back I had create a demo Tic-Tac-Toe Android Application covering most of the basic concepts and if you are new you can give it a glance. Should be pretty easy to understand. I have put it up on the git. Clone it on you local machine, import it in your Eclipse and go through it.

    • https://github.com/aniket91/TicTacToe


    Note : Most of the above information is taken up from the documentation pages and combined to add all info about Activities that I find useful from programming point of view. Documentation pages liks are provided in Related links section below.

    Related Links

    Android Programming Basics

    Background

    Today Android has become very popular operating System. Most of the smart phones have Android as it's OS. Also if you don't know Android OS is not only used in smart phones but also in
    1. Tablet
    2. Computers
    3. Laptops
    4. Watches
    5. Cars
    6. Guns ......
    and the list will continue...... . Lets start knowing more about Android.




    To start with.....

    At the backend we have Linux kernel running. If you are a software developer than you might already be familiar with many aspects of Android such as 
    • Linux kernel
    • SQLite database [Yes Android has this in built for persistent storage]
    • Open GL library
    Other aspects like Activities, it's life cycle, virtual machine that manages the processes are different. We will get to those.

    Android Versions

    Android versions that have been released till now - 

    1. Alpha (1.0)
    2. Beta (1.1)
    3. Cupcake (1.5)
    4. Donut (1.6)
    5. Eclair (2.0–2.1)
    6. Froyo (2.2–2.2.3)
    7. Gingerbread (2.3–2.3.7)
    8. Honeycomb (3.0–3.2.6)
    9. Ice Cream Sandwich (4.0–4.0.4)
    10. Jelly Bean (4.1–4.3.1)
    11. KitKat (4.4–4.4.4)
    12. Lollipop (5.0)

    Android Runtime

    If  you are familiar with Java then you must be aware of Java runtime (JRE) and also the JVM (Java virtual machine that runs the actual java processes). .java files are converted to .class files by java compiler . class files are essentially byte code that java interpreter in JVM understands. 

    Similarly Android has it's own set of APIs. We use this APIs to write Android applications in Java. Important changes in Android are - 

    • Android uses Dalvik virtual machine to to manage Android processes. Dalvik is Google's implementation of JVM that is optimized for handheld devices.

      From Jelly bean we also have another option for Android runtime and that is ART .So from Jelly Bean onwards we can select either of the runtimes from Developer options - 
      • Dalvik
      • ART

        (Above screenshot is from my  Moto E running Kitkat)
    • .class files and jar files generated from .java files are further converted to .dex files as .dex files are more compact and efficient and form an important aspect memory limitations.

    Android System Architecture




    Android System architecture is as shown in above diagram. Top most layer is your Applications/Widgets. They talk to the underlying framework. For example Activity Manager manages the activity lifecycle of all the activities that form a part of your Application.Each module in the framework will inturn use libraries which may be 3rd pary like OpenGL or own APIs (Android runtime libraries). Finally at the bottom is the Linux kernel that takes care of processes, drivers etc.

    Building Blocks of Android

    Every developer need to know following entities in Android

    1. Activities
    2. Intents
    3. Services
    4. Content Providers
    You can read about them in a separate post that I had written some time back -


     Just to give an overview I'll try to explain the use cases of above entities. If you have an Android smart phone the icons you see on your screen are nothing but intents. Intents are basically a mechanism for performing an action like stating an Activity or Make a call or share your picture. So when you click on the icon you basically trigger an intent that start your Application. Another exaple would be sharing your picture. When you click share you must have see a lot of options like Facebook, Gmail, Twitter etc. These are basically Applications that are listening to the intent specific to sharing some status. When you click on share it will fire an intent and will give you list of applications that are listening or registered for this intent. Activities are UIs that form you Application. Each application can have one or more activities. Each Activity can further have fragments (Don't worry about this if you are not aware - but it's the tabs you see on the screen like for dual SIM). Services are nothing but daemon processes that run in background. Music ? Does it get closed when you navigate or open some other application ? No... That's a service. Service will continue to run unless you explicitly terminate it. Content providers are basically way to share data between applications.


    Resources in Android Project

    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.

    Android Manifest file

    Manifest file form a very important part of any Android Application project. It provides Android OS information about the application.
    • It must always be named as AndroidManifest.xml and should be available in projects root directory.
    • It should contain permissions that application uses. These are shown to user for accepting when the application is installed.
    • It also has the Minimum API level or Android version that your application supports. Google play will decide compatibility of application for your device on the basis of this..
    • It also has other components listed such as Activities in the application, intent filters that the app listens too etc.

    Recommended book

    I have found following book to be very useful for beginners (like me :))




    Related Links

    Friday, 17 October 2014

    Install and use Git on Windows

    Background

    There are multiple code versioning tools. Some of them are SVN, Git, Mercurial, Perforce etc. In this post we will see how can we install git on windows and use it to create a local repository of a existing repository on github.

    For installing git on Linux from source you can refer to one of my earlier posts - 


    Installation

    1. Download the installer from the official git website.
    2. Run the installer. 
    3. If you are a beginner leave every setting in the installation workflow to default except probably the screen that says add git to the classath (This would alter your $PATH env variable).
    4. Finally click on finish to complete the intallation.

    Screenshots for installation












    Quick way to know if git is installed in your system is to open your command prompt and type git or git --version


    If you see above output you have successfully installed git on your System.


    Cloning a Git repository from Github

    I have a repository on github that I had created fir creating a simple tic-tac-toe android application some time back. I am going to clone the same one. You can view the project at https://github.com/aniket91/TicTacToe

    To clone a repository you have to use git clone repoUrl command. 
    •  C:\Users\athakur\GitSources>git clone https://github.com/aniket91/TicTacToe.git


    Pushing changed to Github repository

    Prior to pushing your changes you need to be aware of the changes that you have made. For that you can use git status command.

    • git status

    Before pushing you need to  commit your changes. Use
    • git commit -a 
    to confirm your change. You will be asked to provide commit message. An empty commit message will abort the commit.



    If you want to redo your commit then you need to execute - 

    • git reset --soft HEAD~1  
    This will reset all your commit.

    To push your changes you need to execute git push command. 

    • git push



    You can see your commit changes on github. Below is the screenshot for my demo changes in this post.



    Related Links

    Wednesday, 15 October 2014

    Installing Google Nexus 5 USB Drivers (for ADB)

    Background

    In one of the previous posts we had discussed the scenarios in which android device is not detected by Eclipse ADT.

    This post is covers same aspect with more depth with Nexus 5 device as an example.

    Check

    That post will give you very basic idea on how to make your android device recognized by Eclipse ADT/ Android ADB. There are two ways to know if your device is regognized - 

    1. You try to push your android App to the device and notice there is no device listed to push the app to.
    2.  Or simply run 'adb devices' to see if ADB is recognizing your devices.

    2nd point can have 3 outcomes -

    1. You get no devices :

    C:\Users\athakur>adb devices
    List of devices attached
    


    This is the case we will discuss today in this post.

    2. You see your device but as unauthorized :

    C:\Users\athakur>adb devices
    List of devices attached
    07f4545f00f333c8        unauthorized
    


    In this case you should Enable USB debugging. Connect you machine to device via usb and select authorize  connection from device.
    See Can't connect Nexus 4 to adb: unauthorized
    After you successfully do so you should get case 3

    3.You see your device with ID :

    C:\Users\athakur>adb devices
    List of devices attached
    07f4545f00f333c8        device
    


    In this case you are good to go.

    Installing Google Nexus 5 USB Drivers (for ADB)


    Though this post is specific to Nexus 5 steps are same for any OEM. You can get the driver from 

    Steps :
    1. Install google USB driver from SDK manager (SDK manager is inside your ADT bundle). It should get installed under  <sdk>\extras\google\usb_driver\ .

    2. Connect your android device to your machine. Enable USB debugging. (How to enable developers option in your android device?)
    3. Right click on My computer then select Manage. Then select Device on left panel.In the other devices section you should see your device. Nexus 5 in this case.

    4. Right click on your device entery and select Update Driver Software.

    5. Select Browse my computer for driver software option and select the USB driver folder (<sdk>\extras\google\usb_driver\.)

    6. Install the driver.

    To confirm your ADB will now be able to recognize your device repeat check section of this post. You should see point 3 as the outcome (if you get point 2 see the solution in the same point).













    If your Eclipse detects the device but does not recognize it you may have to restart adb server -


    Related Links

    t> UA-39527780-1 back to top