Thursday 15 September 2016

Android Tutorial #3 (Code explanation for Hello World - Android)


Android



This tutorial contains a detailed explanation of the Hello World application created in Android Tutorial #1.

MainActivity.java

package com.computerscience101.testmap;

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

public class MainActivity extends FragmentActivity {

    @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.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);
    }
}
package com.computerscience101.testmap;
 A 'package' in Java is used to organise classes in Java in a particular namespace, similar to how we arrange similar files in a folder.
package <package-name> denotes which package the file belongs to.


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

The 'import' keyword in Java is used to import (include from external source) built-in and user-defined packages into your Java class. This allows you to access classes and methods from imported packages as if they are defined in the current package

Access specifiers: Access specifiers as its name suggests determine how a particular entity can be accessed i.e. whether it can be accessed from all classes, only the class to which the variable belongs, etc.
In this case an 'entity' could be a class, method, variable. etc.

In Java there are 4 types of access specifiers :
1. public
Can be accessed by all classes in the program, whether they are in the same package or in different packages.

2. private
Can be accessed only by the enclosing class.

3. protected
Entities made protected in super class can be accessed only from sub class. Super classes and subclasses can be better understood after understanding the concept of inheritence will be covered in the next part.

4. default
Java provides a default access specifier when no access specifier is specified. Entities with default access specifier can only be accessed by classes in the same package.

public class MainActivity extends AppCompatActivity { 


Inheritance
Inheritance is the process by which one class gets the methods and properties (variables) of another class.
In this situation the receiving class is called the 'sub class' where as the class who's methods and variables will be acquired by the 'sub class' is called the 'super class'.
In Java the keyword 'extends' is used to show inheritence.

For eg.
Sub class extends super class {

The class MainActivity represents an Activity and hence it must contain the necessary methods and variables required by an Activity.
AppCompatActivity internally extends the Activity class.
Hence MainActivity acquires the methods and variables of the AppCompatActivity class which include the methods and variables of the Activity class.
AppCompatActivity is used since it allows you to set an ActionBar and a theme for the Activity.


@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.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);
    }
}
Overriding is a feature of OOP which is related to runtime-polymorphism. Polymorphism on a very simplistic level means the same name for many entities.
In this particular case polymorphism refers to methods. We override methods of the super class in the sub class by using the annotation @Override Which method is to be used depends upon the Object used for the class. The method in the sub class should have the same signature as that of the super class.

The signature of a method consists of:
Method Name + parameters

onCreate()
The onCreate() method is used to initialise the Activity. It comes first in the lifecycle of an Activity. Hence when an Activity is created first the onCreate() method is called.
super.onCreate() calls the onCreate() method of the super class.

onCreateOptionsMenu()
The onCreateOptionsMenu() method is used to initialise the contents of the Activity's standard options menu.





As shown above the options menu is enclosed within the red box.
The getMenuInflater().inflate(R.menu.menu_main); method is used to inflate the options menu.
This method returns true if the list is successfully inflated.
The file menu_main.xml contains the list of items to be inflated.



onOptionsItemSelected()
The onOptionsItemSelected() method is used to define what happens when each of the elements in the menu list is clicked.

Thursday 8 September 2016

Android Tutorial #2 (Basic components of Android)



Android

This tutorial helps you understand in depth the basic components of an Android application.

Components


1. Java files

Java is a programming language and computing platform first released by Sun Microsystems in 1995.
The Java files contain pieces of code that define how the Android application will react to events at run-time.
The Java files put life into the basic skeleton provided by the layouts allowing the user to interact with the Android application.

App components are the building blocks of an Android application. The system can enter the application from each component, however not all components are user entry points. Each component exists on its own and performs a specific task. Hence basically an Android application is a collection of one or more App components interacting with each other in order to perform specific functions.
There are four type of App components :

A. Activity

The Activity class in Android represents a single screen. Every Java program starts execution from the main function, similarly an Activity starts execution from the onCreate() method. The lifecycle of an Activity is as given below



B. Service 

A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface.
There are two types of services :
    1. Bounded Service
An application component can bind a service by calling bindService(), such a service offers a client-server interface that allows components to interact with the service, send requests, get results and even supports Inter Process Communication (IPC). The service is bound to the application component that started it and dies when the corresponding application component dies.

    2. Unbounded Service
An unbounded service is started when an application component, such as an activity starts it by calling startService(). Once started a service can run in the background indefinitely, even if the component that started it is destroyed.

Lifecycle of a service is given below.


C. Content Providers

A Content Provider manages a shared set of app data. Data can be stored in the file system, an SQLite database, on the web or any other persistent storage location the application can access. Content providers are useful for reading and writing data that is private to your app and not shared. It is implemented as a subclass of ContentProvider.


D. Broadcast Receivers

It responds to a system-wide broadcast announcements, these include broadcasts announcing that the battery is low, screen is turned off, etc. The application can also initiate custom broadcasts. Broadcast Receivers don't create a user interface, they may create a status bar notification. A broadcast receiver can be thought of as a gateway to other components and is intended to do a minimal amount of work.

2. Resource files

Resource files are present in the resource folder. They form the skeleton of the Android application. This resource folder consists of various subfolders such as

A. drawable


The drawable folder consists of all the drawable files in the Android application.
In order to optimise the UI for different screen sizes the drawables need to be used
according to screen size. To do this we use the following folders
1. drawable-ldpi 
2. drawable-mdpi
3. drawable-hdpi
4. drawable-xhdpi
5. drawable-xxhdpi

LDPI, MDPI, HDPI, XHDPI, XXHDPI refers to screen density, which means how
many pixels can fit in once inch.
The ratio in pixels between them is
1. ldpi - 1:0.75 (low dot per inch)
2. mdpi - 1:1 (medium dot per inch)
3. hdpi - 1:1.5 (high dot per inch)
4. xhdpi - 1:2 (extra high dot per inch)
5. xxhdpi - 1:3 (extra extra high dot per inch.


B. layout

The layout folder contains layout files (.xml extension) that basically define the structure of the UI of the android application. The layouts form the skeleton of the Android application which is given life by the Java files. The layout file consists of views, these views are called the children of the layout. 
The View object is the basic building block of the UI which is created from the View Class and it occupies a rectangular area the screen and is responsible for drawing and event handling. The base class for widgets is View, and these widgets are used to create interactive UI components like buttons, text fields, etc.
There are five standard layouts :
    1. Linear Layout :
Arranges it's children in a single column or row. The orientation of the row can be set using the orientation attribute.

    2. Relative Layout :
Displays the child views in relative positions. The position of each child can be specified as relative to a sibling view.

    3. Frame Layout :
Used to block out an area on the screen to display a single item. Child views are drawn in stack with the most recent views drawn on top. This can be used to draw multiple views overlapping each other.

    4. Absolute Layout :
It allows you to specify exact locations of it's children using x, y co-ordinates.


    5. Table Layout :
Allows you to arrange groups of views in rows and columns.


C. menu

It consists of Menu Resource files. A Menu Resource file is a .xml file which defines an application menu such as an Options menu, Context menu, submenu that can be inflated
using MenuInflator.


D. mipmap

The Mipmap folder is used to place application/ launch icons. Similar to the drawables folder they have different subfolders mipmap-ldpi, mipmap-mdpi, mipmap-hdpi, etc. for different screen resolutions. 


E. values


The values folder contains various constant values that you keep using through the course of the application. For example it may contain constant strings.xml file which stores constant strings that are used throughout the program. It provides a single point of access to values that may be used from different parts of the application avoiding the creation of multiple variables. To retrieve string from strings.xml we can use "R.string.string_name". Similarly we can have a dimens.xml file which allows us to associate names with various dimension values.
The values folder may have different subfolders for different screen resolutions.


Wednesday 7 September 2016

Android Tutorial #1

Android

Android is a mobile Operating System (OS) developed by Google and it's based on the Linux Kernel. It's designed mainly for touchscreen phones. It is an open source initiative and the Android source code is released by Google under the Open Source licences.

Components

So at a very abstract level developing Android applications consists of two components :
1) Resource files.
2) Java files.

1.Resource Files

Resource files are stored under the res directory and can be considered as the skeleton of the Android application.

2.Java Files

Java files are stored in the java directory and are used to add life to the Android application and make it respond to dynamic events.


Other than this broad categorisation there are other types of files which will be explained in the coming parts.


Example

Without spending more time on the nitty gritty's lets begin writing your first Android application.

Since Android has stopped support for Eclipse I urge you to use Android Studio and this tutorial will contain screenshots of projects in Android studio.


After installing Android Studio and setting up your SDK, start Android Studio.



 Click on the "Start a new Android Studio project " option under "Quick Start".


Fill up the field "Application name" with something suitable.
"Company Domain" should be the web domain name of your company so that it is unique, however it is not necessary for the domain to exists. The "Package name" depends on the "Company Domain" you provide which in turn is used to name your package and while uploading your .apk file to the Google Playstore. So as of now you needn't worry about it.

After filling up the data suitably click "Next".


Check the "Phone and Tablet" checkbox since we are going to develop and Android application for a phone/tablet in this tutorial.

The other check boxes need to be checked when developing applications for the respective devices as suggested in the name. Wear for watches, TV for televisions, etc.

 Depending on the SDK you have downloaded set up the "Minimum SDK"."The Minimum SDK" means that the application we are building will work only on devices running at least this version of Android.

Click the next button after filling up all the details.


Activity
An Activity is an application component that provides a screen with which users can interact in order to do something , such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.

Android Studio allows us to chose from a set of Activity templates. We will choose the "Blank Activity" for now and we will use the other templates in further tutorials.

Click the "Next" button after choosing the "Blank Activity".


Usually most Android applications begin with an Activity called "MainActivity". This name can be changed. For the purpose of maintaining uniformity it will be kept as "MainActivity" in this example.
Each Activity has a Layout file (XML Layout) associated with it.
The field "Layout Name" denotes the name of the XML Layout associated with this Activity. 
As the complexity of your program increases and more complex components are added it becomes difficult to maintain the code, hence the prefix "activity" is added before the layout name. It is not compulsory but it is recommended.
The field "Menu Resource Name" contains the name of an XML Resource file. This file contains a number of constants which are used to populate and Options Menu, Context Menu, submenu, etc.
These constants cane be referenced from the Java files.

Click "Finish" to create your First Android project.






Connect an Android device to your computer. As you connect the device you will get a pop-up asking you to enable "USB Debugging". Enable USB Debugging on your device.
Click the Green Play button which is within the red circle in the previous screenshot.
If you do not have an android device you can create an Android Virtual Device by clicking on AVD which is within the blue circle in the previous screenshot.
Click here to learn how to create your Android Virtual Device.

Congratulations!!

You successfully created your first Android Application.
The next tutorial will contain a detailed analysis of the code explaining key concepts. 
Until then
DREAM OF CODE.

Create Android Virtual Device

Create your Android Virtual Device 

Click on the AVD Manager button within the blue circle and follow the screenshots.













Click ok to launch your application using Emulator.
Thank you.

DREAM OF CODE.






Sunday 20 March 2016

Revignite: Ignite the Revolution


For those of you who would like to have constructive conversations with like minded people on topics ranging from current affairs to leisurely topics like music as well as business ideas, placement policies in colleges, etc; this is definitely the platform to assist you in doing so. The Developer sincerely believes that to make a difference today, all you need to do is ignite the revolution. One spark is all it takes.


Revignite is the ultimate platform for you to get your thoughts out there. It is the next step in anonymous social media.
Revignite allows you to share your ideas and views in an unrestricted and anonymous fashion. Revignite aims at providing people with a platform on which they can share their views on a topic anonymously and the most interesting feature here is that these revolutions themselves are created by the people.
Users can begin their own revolution or join existing revolutions.
Ignite a revolution you would like to talk about to make it trending.
Revignite creates new chatrooms based on revolutions ignited by users.