Friday, December 16, 2016

Event Handling in Android

In our previous post we created a very basic Android app which displayed a static text to user. In this post we are going to add some functionality to that app so user can  interact with the app because staring at a static text gets boring really quickly so let's get to it then.

There are various user events that you can capture in your application like 'tap/click', 'long click', 'drag' and there are different ways you can capture these events. We'll focus entirely on 'click/tap' event which occurs whenever user taps any UI element on the screen.

To get started create a new project in Android Studio or use the project that you created in last tutorial.

To capture the event we first need some UI element on the screen so open activity_main.xml located in res/layout/ and switch to 'Design' view. Between the project explorer and designer view you have palette. There are various UI widgets you can drag & drop onto the designer view. For now find 'Button' and drag & drop it to the screen anywhere you like.

Click the button which should open it's Properties window on far right side of the screen. Find and change it's 'text' property to whatever you like. This is the text that'll be displayed on the button. Also change the ID property to 'my_button'.

If you  have a 'hello world' text on screen click on it to bring up it's properties otherwise drag & drop a new 'TextView' from palette to anywhere on screen. In properties window of TextView find and delete it's 'text' property. Next change it's ID property to 'my_text_view'.


Our UI part is complete now let's move to the code part. What we want to achieve is when user clicks the button we want to show some text on the label / TextView that we just placed on the screen.

1st Method: (XML Attribute)


                                                                             Open the Java file, it should be named 'MainActivity.java'  if you accepted the default name when creating the project  and it should be located in java/{package.name} inside your app module.


Below the onCreate(Bundle savedInstanceState) create a new method like this:

public void onMyButtonClick(View view) {
    Log.i("onMyButtonClick", "Button is clicked");
}

Now open the activity_main.xml  file again and click on Button to bring up it's properties.
Find 'onClick' property and from drop down select the name of the method we just created.

If you run your app you'll see a new log statement being printed everything you click the Button which means our event handler is working as expected.


What's going on?

                              Let's take a moment to understand what we did so far, first of all we placed two UI elements on screen, a Button and a TextView then we created a Java method in our MainAcitivty class to handle the click event of the button and finally we attached the event handler to our button by setting it's 'onClick' property in xml.

The event handler method itself needs to be declared as public and it's return type should be void and it accepts one argument of type View.

Note: If you don't see Android log window simply click the green Android mascot icon at bottom bar of the Android Studio window labeled 'Android Monitor' and it should be visible to you.

Android Log Window


So when user clicks the button we print a log statement, we actually want to display that same text on screen instead of log window so we need to change our onMyButtonClick(View view) method to achieve this task.

Open MainActivity.java file and inside onMyButtonClick(View view) write following lines of code:

public void onMyButtonClick(View view) {
     TextView label = (TextView) findViewById(R.id.my_text_view);
     label.setText("Button is clicked");
 }


To change to text property of the TextView from Java code first we need to refer to the TextView object itselt. Every UI element that we place on screen using xml is a View and every class that extends from Activity base class has a method 'findViewById(int id)' which returns you the reference of the View object with given Id, this id is the same that we give to any view using xml.

Everytime you give an element an id Android Studio behind the scene create an int representation of that id which you can refer to using the R.id.name_of_id so in our case we call the findViewById() method and provide R.id.my_text_view as argument which refers to the id we gave to this particular element.

Another thing that's happening on the first line of code is the type casting of the returned View from findViewById method to TextView type. Because findViewById returns a View object we have to explicitly cast it to TextView.

You might be wondering why didn't they created findTextViewById() method in the first place? Well if they did then they'd have to write a method for each type of view like findButtonById(), findCheckBoxById() and so on...Instead there's just one method and you can type cast the returned View to whatever you like.

On the second line of the code we simply call setText() method on label object and give it an argument of type String. Calling this method actually displays the desired text on the label.



2nd Method: (Anonymous Inner Class)


                                                                                                         Open activity_main.xml and click Button element in the designer and delete its onClick property.

Open MainActivity.java and inside onCreate(Bundle savedInstanceState) write following lines of code:


Button button = (Button) findViewById(R.id.my_button);
button.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View view) {
        
    }
});

Copy everything inside our previous method onMyButtonClick() and paste it inside onClick(View view) and delete 'onMyButtonClick()' method, so MainActivity.java looks like this.



public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.my_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                TextView label = (TextView) findViewById(R.id.my_text_view);
                label.setText("Button is clicked");
            }
        });
    }
}


Run the app again and you should see the same behaviour as before. Let's go through what's going on in this method. 

First of all you should know that onCreate is automatically called when your activity is launched. First call inside the onCreate is the call to super class and after that a function call 'setContentView(int layout)' this method call is what links our xml file to this Activity. This is how this activity knows that it needs to display whatever is in the activity_main.xml file. 

After that we get a reference to the button object we placed in the xml file and then we call setOnClickListener() and give it an object of View.OnClickListener which is an interface declared in View class.

By doing this the function 'onClick' gets executed whenever this particular button is clicked. Rest of the code inside onClick is same as before.


There is another way to hanlde the same event by having your Activity to implement the View.OnClickListener interface and handling the events in overridden method 'OnClick(View view)' but we are not going to do that in this post, maybe some other time. 

If you have any problem post it in the comments section and I'll be glad to help. If you think I can improve these tutorials in any way please let me know in comments or email me at qijaz221@gmail.com.

Thank you for reading, stay tuned for more.

Related Articles:

Wednesday, December 14, 2016

Creating Your First Android App

Hi I'm Qaiser Ijaz and I'm a contributing author to this blog, I've been developing Android Apps for last 4 to 5 years and I'm going to do a series of posts here each one of which is going to focus one Android component/topic starting from most basic level to much more advance topics. I hope you enjoy reading them.

So let's start with the 'Hello World' app which will familiarize you to the process of creating and deploying an Android application.

First of all you need to have Android Studio installed and setup properly, if you don't have Android Studio please follow this post. 

1- Run Android Studio and select 'Start New Android Studio project'.

Welcome to Android Studio

2- Doing so will bring up following screen.

Create New Project

Application Name: 

       This is the name of your app that will be displayed to the user, for this tutorial 'My Application' is just fine.

Company Domain: 

       This is where you put your or your company's web site address. This is used to generate a unique Java package. Think of it as a unique identity of your application. All apps in Google Play Store are required to have a unique package name. For the purpose of this tutorial write whatever you like as it doesn't really matter because we are not going to publish this app.


Leave everything else as it is for now and click 'Next'.

Target Android Devices

You'll be asked to select Target Android Devices, Android runs various kinds of devices but we are not going to create app for anything other than Android Phones/Tablets so select the first option if it's not selected already.

Minimum SDK: 

                           With every new version of Android a new version of SDK (Software Development Kit) is released to Android developers. Selecting Minimum SDK version is important because it'll make sure your app runs on as many devices as possible. Android Studio gives you an estimate of how many devices your app will run on so select the Minimum version that Android Studio suggests and click 'Next'.

Add an Activity to Mobile

On next screen you are asked you 'Add an Activity to Mobile', Every single screen on an Android app is one activity so an Android app is essentially composed of many activities bundled together, what you see on above screen are 'templates' of different types of Activities which means selecting any of these template will automatically generate some code for you which is great but not so if you are in learning phase. Select 'Empty Activity' which is bare minimum that is required to display an empty screen on an Android device. Finally click 'Next'.

Customize the Activity


Next you are asked to enter name for your activity, type any name you want just be sure to start with a capital letter because a Java class with same name will be created for you and it is the standard practice to start Java class name with a capital.

Below that there is a checkbox 'Generate Layout File', let me explain this. In Android every screen you see is separated in two different languages, everything visible on screen is created using XML where as all the logic of application is written in Java.  Although technically you could eliminate XML and write all your UI using pure Java but it's not the recommended practice, plus your code wouldn't be easy to read.

Having this separation of UI and application logic makes your life as a developer much easier because it makes your code easier to read/understand to you and to others and you can use the same 'layout' file in as many activities as you want.

So checking the ''Generate Layout File' essentially means that Android Studio will automatically create an XML layout file to displayed by your activity.

Hit 'Finish' and wait for Android Studio to create your project. When it finishes you'll be presented with the following screen.

Android Studio Main Activity



This is the Java file for MainActivity that we just created, don't worry if you don't understand the code in this file we'll go through each line one by one in later posts. For now just click the small green 'Play' button below the top menu bar.

Android Studio is going to ask you to select a device on which your app will execute.

Select Virtual Device

Physical Device:

                              If you have a physical Android phone, open Settings, go to 'Developer Options' and turn on 'USB Debugging', this step is required for Android Studio to recognize your phone.

After that just connect your phone to your computer using the USB cable and Android Studio will display your phone as an option in above screen. select that and click 'OK'.

Virtual Device:

                          If you don't have an actual device you can use a virtual device, to setup an AVD (Android Virtual Device) please follow the instructions here. Once you have an AVD setup that will be presented as an option in above screen, select it and hit 'OK'


Android Studio will now compile your app, create an apk package, install it on selected device and launch your app. If everything goes ok you'll be presented with following screen on selected device.


First Android Application


Congratulations! You have created your first app and successfully deployed it. It doesn't really do anything other than displaying a static text 'Hello world!' which we'll fix in the next post and add some controls/functionality so it doesn't look as boring as currently does. 

If you have any problem please feel free to post in comments and I'll be glad to help.

Thank you for reading, stay tuned for more...


Related posts:

Thursday, December 8, 2016

Getting Started with Android Development

Hello, Welcome to my blog Android Programming from Scratch. I'm Maaz Ahmed, I have Masters in Computer Science and I've been developing Android app for last few years. I'm starting this blog as an effort to make information/guide/tutorials easily available to new Android developers. 

Let's start this journey with the most basic guide 'How to install Android Studio'.


Installation guide on Ubuntu:

I am using Ubuntu 16.04 LTS but generally speaking this should work on Ubuntu 14.04 and onward as well as on any other Debian based distro.

First and the foremost thing you need is the JDK (Java Development Kit). You have two options when it comes to JDK on Ubuntu, you can use the OpenJDK which comes preinstalled with Ubuntu or you can install Oracle JDK by following the steps below. Personally I recommend that you do install Oracle JDK and to do so: 


1- Open the terminal by pressing CTRL + ALT + T and execute following line one by one. Depending one the speed of your internet connection this might take a few moments.

                             sudo add-apt-repository ppa:webupd8team/java
              sudo apt-get update
              sudo apt-get install oracle-java8-installer
              sudo apt-get install oracle-java8-set-default

2- Once you have installed JDK 
Download Android Studio , this again might take some time depending on the speed of your internet connection.




3- After downloading Android Studio extract the .zip file and move it to  in /opt directory, to do so simply execute following line in terminal. (Replace '145.3360264' with whatever version it is that you downloaded.

          sudo unzip android-studio-ide-145.3360264-linux.zip -d /opt




4- Navigate to the Android Studio executable directory by typing following line in terminal (assuming that you extracted it to /opt)
                 
                    cd /opt/android-studio/bin



5- Execute Android Studio.


                          ./studio.sh

 Android Studio will start and setup wizard will guide you through initial setup process. It will automatically download required compoenents (Android SDK, Android AVD system images). This again can take quite some time depending on your internet speed. 


After it completes you'll be greeted with the welcome screen.

      



Create a desktop entry by clicking on 'Configure' and select 'Create Desktop Entry' so it becomes available in Ubuntu application drawer.

6-
        There is one additional step the you have to perform if If you are using the 64 bit version of Ubuntu. There are some 32bit libraries required by Android Studio which you can install by executing following line in terminal.


         sudo apt-get install libc6:i386 libncurses5:i386 
    libstdc++6:i386 lib32z1 libbz2-1.0:i386


That's it, your Android development environment is ready and you can start building Android applications. Join me in the next post where I'll create a 'Hello World' application and run it on an Android device. 

If you encounter any problems during installation/setup please feel free to post it in the comments and I'll be glad to help.

Thanks for reading.