Wednesday, 27 May 2015

Stepping stones to becoming a developer - Android Studio project structure

Hi all, so previously we had discussed in brief about the Gradle and studio, we had also gone through the steps for environment setup and helloworld coding. We will now climb each step to the different aspects of android programming with studio, so, fasten your seat belts

Understand the android studios project structure

Lets start by creating a new project(click here if you want to know how), say the same hello world program for now which we discussed previously.  For any android application, the main areas to focus is the activities and layouts.
An activity can be considered as a presentation layer, it will decide the behaviour of the app from its start to end. Each activity is a class which will control how the app will interact with the user. For example, when you open any android app what do you see?, you would see a complex view with clickable, non clickable, editable, non editable components in a single page, the entire page or view is called a layout. On the other hand, try interacting with the layout, say, clicking a button or typing in your user name / password etc. all such functional behaviours as to what each individual component in a layout is to do is controlled by the activity class. You will learn more while start coding. 
Moving on, lets take a look at our project, you will see an app directory which has a few sub-directories namely manifests, java, res. We will begin with the java folder; on expanding which you would see a package name in the form "com.somthing.somethingelse".
A package name is kind of a unique identifier for an application. It is a mandatory part of any application, 2 applications may exist in the same device with same name and different package names, but if 2 applications with same package names are tried to be installed, the system will come up with a failure message. Also if you are uploading an app to the Google play store with whatever package name and after a while you want to release the same app with updated features and bug fixes, you have to use the same package name you used previously, if you are going to upload the apk with a different package name it will be treated as a new app.
In android each class files are grouped under packages. Within an application , you can declare multiple packages for grouping different types of class files such as a com.example.db for all the database classes or com.example.constant to hold all the classes which declare constants, but, only one package will act as the unique id for the application, mostly it will be the package you declared while creating the project unless you change the package forcibly.
As said activities and layouts form the main parts of an android app, you can see that under your package there is the MainActivity.java file. Open the java file and you will see something like
package androidstudio.test.com.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity2Activity extends ActionBarActivity {

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

    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main_activity2, 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();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


As you can see the MainActivity extends the Activity class. The Activity class contains a series that defines each state of the app. An activity goes through a series of lifecycle as you navigate through the app, like if the app is in started or the activity is in foreground, the onCreate and onResume method are called. 

Activity Life cycle methods
onCreate() - called when an activity is created or launched. This method will be overridden in our activity to create view,  initialise views, bind data etc

onStart() - called right after onCreate(), this may be used to implement any task before the UI becomes visible to the user such as refreshing or reloading UI contents etc. This is immediately followed by onResume()

onResume() - called when the UI is ready for user interaction.This is one of the important method to be overridden. It is method that get called whenever the activity comes to foreground hence it always is the state that may happen after onPause(). This method can be used to bind services, listeners etc.

onPause() - This method is called whenever the activity goes in background like when another activity is opened on top of the current activity or when home button is pressed etc. i.e. when the activity is no longer visible but is not killed. This can be overridden to unbind services or listeners, release system resources, save application data etc. It can be considered as the opposite of onResume(). The onPause() is always guaranteed to be called whenever the apps goes in background or turns invisible, but after that the Android system has the right to kill your app so make sure your app data is saved.

onStop() - called when the app is completely invisible and happens after onPause(). After this the onRestart(), onDestroy() or nothing may be called. We cannot depend on this system, as the system may or may not call it considering low memory scenarios. Hence write all the commit codes in your onPause().

onDestroy() -  called when the activity is temporarily or permanently killed. This happens when either the system kills your application instance when it is low on resources as well as when the activity is finished by the user, the two scenarios can be differentiated with the help of the isFinishing() method. It is the last method that would be called in an activity's life cycle. Like onStop() this method also cannot be relied on as it is up to the system whether it will be called or not. This method is usually implemented to free resources that may be used by the activity. 

Before we go into doing an example on this, I would like to talk about one more important object, called Intent.

An intent can be described as a message carrier between components. In programming world it can be considered as an object that can carry information or data between components belonging to the same application. Intents are mainly used for three major functions:
  1. To start another activity
  2. To start a service
  3. To pass messages to broadcast receivers
Intent will mainly carry three important parts; an action, data, component name. An action is a String that generally describes what action the Intent is intended for such as ACTION_VIEW, which is used to display information through an activity to the user such as displaying video in the video player, or images in the gallery etc.
A data is a bundle of information that is required to be communicated between components.
A component name is the package name of the other component to which the intent is passed. For example, you want to pass the intent to MainActivity.java residing in package com.example.sampleintent package, then, its component name is com.example.sampleintent.MainActivity which can be said as the fully qualified class name.

There are two types of Intents
  1. Explicit intents
  2. Implicit intents
Explicit intents are those in which the component names are specified. These components might be activities or other components within your application and whose component names you are aware of, mostly used when starting another activity from your current activity. Implicit intents are those in which the the component is not specified, whereas an action will be declared with it. These types of intents are usually used if you want to use a specific function on an in built component whose component name you are not aware of such as to call a particular number you can use the phones default caller with the help of the ACTION_CALL intent action.

Lets move on to an example to understand these aspects. I hope you know how to create a project and all, if any confusions please refer to earlier posts. Assuming you would have started a new project, you will already have a MainActivity.java, lets create one more Activity. For this:
  1. Right click your application package
  2. Goto New >> Activity >> Blank Activity
  3. Name your activity as SecondActivity(you may name as you wish)
A new activity and its corresponding layout file will be created

Once this is done, let's move back to the MainActivity.java and override our lifecycle methods. To override in Android Studio, point and click the cursor to any location you like to create your methods and from the Keyboard press Alt+Insert, you can also right click on the emoty space and select Generate, It will open up a small window with a list of actions, select Override Methods...
From the list that follows, keep pressing CTRL from your keyboard and click the following methods:
onResume()
onStart()
onPause()
onRestart()
onStop()
onDestroy()

and click OK.

The methods will get added up at the point where your cursor was clicked. Inside each method, we will write a Log statement(a log is used to print out a text while a specific code is being run, it is basically used for debug purposes, in our case to check when each method is being called, based on the log that appears). A log statement is in the form:
Log.d("","");                  //d for debug
Log.i("","");                  //i for info
Log.e("","");                 //e for error
There are many types of log, we will use Log.d

Next, goto activity_main.xml the layout file for this activity. Go to the Design mode
If your see any Helloword text in the mobile screen, just click and press Delete from keyboard.
From the pallete available in the left hand side, drag and drop the button into the mobile screen.
Double click on the button and a window will appear, in the text field type "Click to goto next activity", in the id give "click_button"(you may give any, but you should remember it).  Now click in the empty space outside the window and the button label will get updated. Beside the Design field at the bottom left , there is another label called Text, click on that and you will see the xml file of the layout you just edited.

Come back to the MainActivity.java.  In the declaration area, declare a button as 
private Button clickButton;                        //name your variable as you wish

inside onCreate lets initialize the button as 
clickButton=(Button)findViewById(R.id.click_button);  //this is he std format to declare any                                                         view components

Next, we will implement the click functionality for the button as
clickButton.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
 
    }
});

inside the onClick method write the following code to pass control to the next activity when the button is clicked. The onClick is an event and whatever you write inside of it will define the buttons function:

clickButton.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        Intent goToSecondActivity=new Intent(MainActivity.this,SecondActivity.class);
        goToSecondActivity.putExtra("data","dataToBePassed");
        startActivity(goToSecondActivity);
    }
});


code snippet

public class MainActivity extends ActionBarActivity {
public static final String TAG = "ACTIVITY_LIFECYCLE";
    private Button clickButton;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate called");
        setContentView(R.layout.activity_main);
        clickButton=(Button)findViewById(R.id.click_button);
        clickButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                Intent goToSecondActivity=new Intent(MainActivity.this,SecondActivity.class);
                goToSecondActivity.putExtra("data","dataToBePassed");
                startActivity(goToSecondActivity);
            }
        });
    }

    @Override    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy called");
    }

    @Override    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart called");
    }

    @Override    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop called");
    }

    @Override    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart called");
    }

    @Override    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume called");
    }

    @Override    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause called");
    }


    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_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();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
Now in your SecondActivity, write the below snippet in its onCreate, below the setContentView method.

Let's set the received string content in the TextView present in the activity's layout. Inorder to access any view(TextView in our case), make sure the view has an id defined in its xml. So, go the layout and in the TextView xml, declare a unique id(if not present), say, 

android:id="@+id/my_textview"

Now you need to initialize your TextView, inorder to set the content. For this, create an object of the TextView class say,

private TextView mTextView;

and then we can initialize it as

mTextView = (TextView)findViewById(R.id.my_textview);

Now the mTextView object will officially represent the my_textview.

So, we can set its text with the receivedText as

mTextView.setText(receivedText);

Lets also override the life cycle methods here as well so that we can understand the state of this activity when we try to navigate fro here,

code snippet

SecondActivity.java

public class SecondActivity extends ActionBarActivity {
    public static final String TAG = "SECONDACTIVITY_LIFECYCL";
    private TextView mTextView;
    String receivedText;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate called");
        setContentView(R.layout.activity_second);
        receivedText=getIntent().getStringExtra("data");
        System.out.println(receivedText);
        mTextView=(TextView)findViewById(R.id.my_textview);
        mTextView.setText(receivedText);
    }

    @Override    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy called");
    }

    @Override    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart called");
    }

    @Override    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop called");
    }

    @Override    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart called");
    }

    @Override    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume called");
    }

    @Override    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause called");
    }
    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_second, menu);
        return true;
    }
}

Layout for the activity - activity_second.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    tools:context="androidstudio.test.com.myapplication.SecondActivity">

    <TextView        android:id="@+id/my_textview"        android:text="@string/hello_world" 
        android:layout_width="wrap_content"        android:layout_height="wrap_content" />

</RelativeLayout>

Vola, we are done with our project. Lets now run and check the ouput's. To run the project, click the green play button onthe top, or click Run>>Run 'app'

:::Output::::

Check your logcat to see the out put, to view logcat you can see the Android tab in the bottom left of your studio, and inside it you can see log cat.
Remember the TAG string representing the logs from the MainActivity is ACTIVITY_LIFECYCLE and that from the SecondActivity is SECONDACTIVITY_LIFECYCL, this will help us differentiate the output from each activity.

When the app is launched, you will see
D/ACTIVITY_LIFECYCLE﹕ onCreate called                        //represent the log we have written in the                                                                                                    onCreate of MainActivity, D represents                                                                                                    that it is a debug log
D/ACTIVITY_LIFECYCLE﹕ onStart called
D/ACTIVITY_LIFECYCLE﹕ onResume called

Press your device's home button and check the logcat, the following comes up
D/ACTIVITY_LIFECYCLE﹕ onPause called
D/ACTIVITY_LIFECYCLE﹕ onStop called

Resume the app from your recent app list(long press the home button)
D/ACTIVITY_LIFECYCLE﹕ onRestart called
D/ACTIVITY_LIFECYCLE﹕ onStart called
D/ACTIVITY_LIFECYCLE﹕ onResume called

Click Button > CLICK TO GOTO NEXT ACTIVITY, the SecondActivity Opens up through the Intent and you can see the message that was passed through the Intent has been set in the TextView, the logcat will show
D/ACTIVITY_LIFECYCLE﹕ onPause called

D/SECONDACTIVITY_LIFECYCL﹕ onCreate called             //logs from SecondActivity
D/SECONDACTIVITY_LIFECYCL﹕ onStart called
D/SECONDACTIVITY_LIFECYCL﹕ onResume called
D/ACTIVITY_LIFECYCLE﹕ onStop called                              //MainActivity Stopped after                                                                                                                       SecondActivity is visible

Press device's back button
D/SECONDACTIVITY_LIFECYCL﹕ onPause called
D/ACTIVITY_LIFECYCLE﹕ onRestart called
D/ACTIVITY_LIFECYCLE﹕ onStart called
D/ACTIVITY_LIFECYCLE﹕ onResume called
D/SECONDACTIVITY_LIFECYCL﹕ onStop called
D/SECONDACTIVITY_LIFECYCL﹕ onDestroy called

There you go, now you know what goes on when you navigate through an application. Have a good day. I will be back soon with another topic. Please see below if you wish to see the app screenshots.



Tuesday, 26 May 2015

Android Environment Setup and basic code

Android Studio is a slightly heavy app, even in a machine with reasonable specs it sometimes hangs, yet that would do the job, just don’t run too many applications while you are working with studio. Moving on, I will first talk about the system requirements which would be any modern system with at least 2.5+GHz processor , a 4 Gb or above RAM(this is the minimum, please don’t  go below this it will kill your system).
However, for Linux users, it is recommended to install Studio in 64 bit systems. But to install Studio which is a 32 bit application in a 64 bit machine you need to have the 32-bit support library package ia32-libs.
For Ubuntu users, you can execute the below command:
sudo apt-get install ia32-libs
1)      Install Java Development Kit(JDK)
Download  and install the required JDK package from the below link which is apt for your system OS.
For windows , the JAVA_HOME environment variable. The steps of which are:
  1. Open My Computer.
  2. Go to System Properties.
  3. Open Advance system settings.
  4. Goto Advanced Tab and Open Environmental Variables.
  5. Then Click on New and Set Variable Name : Path and Set Variable Value : C:\Program Files (x86)\Java\jdk1.7.0_25\bin (The Directory In which JDK is installed.)
  6. Click OK
Verify the JDK installation by typing
java -version
from the command prompt, it should output
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) Client VM (build 24.71-b01, mixed mode, sharing)
If it works properly, else it will show command not found error
Install Android Studio
Install Android  Studio from the below link
Go through the license agreement and download the file as exe or zip. Install the exe file or unzip the zip file.
Run Android Studio, for the very first run you will get a dialog prompting  to import settings from an existing installation, followed by the setup guide.  Go through the guide and in the end press the finish button.
On starting Studio, you will be greeted with a welcome screen as follows

If you have already created projects it will be listed in the Recent Projects tab.
Now starting fresh,  click on the Start a new Android Studio project  and go through the guide. 

You can give your project a name say “HelloWorld” in camel case in the Application name field, also give a proper package name say ”com.example.firstproject.helloworld” in lower case, click next.

Select your desired platform, say you are developing a mobile app, select phone and tablet and also choose the minimum sdk version as to which version of android release can support your app(its advised to choose the lowest version, so that you app may run in most devices), click next.



Select a template, say Blank Activity. An activity is a code to support the UI. It will help you to design your application to behave as you wish in each lifecycle of the application like when the app is in foreground or background etc. The next page allows you to name your project components such as your activity, layout (a layout is view design on how you want to see each activity in your device), click Finish.

The android studio opens up with a layout displayed in front of you. You can see it contains a view with a label “Hello World”. In android all activity layouts by default comes up this way, so for now just click the play button on top if you have a device plugged in.
To run in emulator
·         Select Tools>Android>AVD Manager or click the icon https://developer.android.com/images/tools/avd-manager-studio.png in the toolbar.
·         Click Create Virtual Device
·         Select a device configuration say Nexus 6 and click next.
·         Select the version of the AVD
·         Click Finish
Once the emulator is launched and the home screen appears (it may take a while, have patience) click the run button from the toolbar and you can see the Hello World in your screen.






Android Studio and Gradle in brief

The features of the Android Studio consist of the following:
  1. Intellij or the intelligent code editor -  provides powerful code editing, code completion, refactoring etc. so that developers can save a lot of time. This feature was available with the ADT bundle as well which was used for android development earlier.
  2.  UI - The new Studio is shaped for better developer interactions. Easily accessible tools and settings and all other development related buttons are their within reach and there is no need to fish around much. Also the Layout Editors are better designed and layout previews are more real looking.
  3.  Rich AVD - The AVD manager has a rich set of devices in all shapes and sizes. This is one great boon.
  4.  Built in google cloud support.
  5.  Build tools - This is one of the most confusing point for developers who switched from eclipse. I would be going to this in detail hence.
    • Android Studio makes use of the Gradle build tools which is an automated build toolkit, basically a plugin. It consists of a set of files to configure and manage the build process. The scripts are based on the Groovy programming language.  
    • Compared to Eclipse IDE, where the developers were unaware about the backend apk building process, Android studio’s Gradle allows a seamless way for developers to manage their builds. With this plugin you will be able to build different versions of the same project like paid, unpaid or device specific apks etc. Developers can also trigger the build from command line as well.
    • The gradle allows including dependencies from within your local repos as well as remote repos. The gradle build normally takes place by assuming a default project convention or structure. It also gives you the freedom to alter your project structure; only, you have to make sure to configure the build files accordingly.

There are two levels of build files: module build file and project build file.  The project level build file is the topmost and it will contain basic information. An example project gradle file is as follows:
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
         // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
 allprojects {
    repositories {
        jcenter()
    }
}

This file simply states that the build is based on the Android plugin and all the remote libraries will be obtained through the jcenter repository.
The Module build file contains the module wise build configurations. It also allows                 you override the main manifest file setting and configure custom packaging/compiling              option etc.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.demo.sample"
        minSdkVersion 19
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
debug {
            debuggable true
        }

    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services:+'
}

Thursday, 21 May 2015

Android Software Stack

The android software stack consists of 5 parts:


  1. Linux kernel
  2. Native libraries
  3. Android Runtime
  4. Application Framework
  5. Applications

Linux kernel: It is the sole of the entire Android structure. As the name signifies, it handles all the device specific resources, drivers, memory management etc.

Native libraries: On top of the kernel resides the native libraries, such as OpenGL, SQLite etc. Inorder to access the resources the users need to call these libraries, say, if a developer needs to implement the database he needs to call the SQLite library.

Android Runtime: This consists of the core libraries and the Dalvik Virtual Machine which is responsible for running the applications.

Application Framework: Over the native libraries and the android runtime lies the android framework which consists of the API's such as the UI, content providers, package managers etc.

Applications: On top of all these lies the application set. All the applications that you see in your android device such as games, browser, music players etc belongs to this category. This set provides the user with specific functions with the help of the underlying architectural layers.








Android SDK

It consists of the following:



  • Android API: The API libraries provides the developer an interface to the devices in-built functions. Its the same libraries google uses to develop their native apps. As each api update release happens for your android handset, the SDK manager also receives updates, so that the developer can use the latest apis to built more featured applications.
  • Development tools: These are tools to compile and build executable applications out of the written source codes.
  • Android Emulator: In order to run and test your applications during the development phase, the SDK provides you a variety of emulator types. Using this you can get a visual experience of how your app runs in different devices. 
  • Sample codes: The SDK manager also has a huge collection of sample codes which describes on how to use different apis for different development needs.

Environment Setup


Today, there is a huge mass of android developers out there. Earlier the android developers only used the Eclipse IDE for their development purposes, but, these days Google is encouraging developers to get use the Android Studio. Though Googles words are strong most developers still use the Eclipse out of habit. Jokes apart, lets start...

For android development you need to :

  1. Download the Android Studio.
  2. Download the latest SDK tools and platforms using the SDK Manager.



Android - from scratch



Android is an OS not a Language


                   Lets start with this phrase, this simple fact that Android is an OS based on the Linux kernel and not a language. The Project was lead by Google and was called as the Android Operating System Development(AOSD). Today billions of Android users are there around the world. Many huge mobile development companies such as Samsung, Sony etc have built and released billions of Android devices. Being one of the most widely used platforms of the current times, along with the user account Android also has a long line of development communities.