You are on page 1of 64

Abhinav Bakshi P a g e 1 | 64

Abhinav Bakshi P a g e 2 | 64
A Preview at the Final App

Abhinav Bakshi P a g e 3 | 64
Chapter 1
Setting Up the Environment

Lesson 1: Downloading Android Studio


Before you get started with your ninja coding skills, its necessary to setup
the environment. This tutorial assumes that you have already installed JDK. If
you havent, go fetch it from oracle.com. Visit developer.android.com and
download the latest version of Android Studio for your target platform. The same
version works for both 32-bit and 64-bit version of your Operating System, so,
you dont have to worry about that. I will be using the Windows platform for the
rest of the tutorial, so, I will download Android Studio for Windows. You can
choose any platform you wish as long as it supports Android Studio. Make sure to
check the system requirements since Android Studio is pretty resource heavy.

Abhinav Bakshi P a g e 4 | 64
Lesson 2: Installing Android Studio
Once you have downloaded Android Studio successfully, you can launch
the installer to continue with the setup.

Once the installer window shows up, click the next


button like a crazy monkey till the installation starts (unless
you want to change the default settings.)

Choose all components when asked during the installation process.

After the installation has finished, launch Android Studio. You will be
greeted by the Splash Screen after which the Android Studio starts begging for
an Internet Connection. If you have an active internet connection, you can
download the Android Studio Components (which will take ages, beware),

Abhinav Bakshi P a g e 5 | 64
otherwise, you can start the Android Studio offline and install the tools using
SDK manager, where you also see a nice progress bar indicating the progress.

Unfortunately, I went with the first option

So, one Hollywood Movie later

Abhinav Bakshi P a g e 6 | 64
It finally finished its installation.

If you take a look at the data consumption, you see it sucked up more than
500Mb data and 1+ hour.

Abhinav Bakshi P a g e 7 | 64
So, once you click finish, you will see a Welcome Screen. This means you have
successfully installed Sucker Studio.

Close the Sucker Studio Welcome window and give yourself a pat on the back.

Abhinav Bakshi P a g e 8 | 64
Lesson 3: Setting up the Emulator
The Sucker Studio we setup in the previous lesson is developed to create
Android Apps. So, you need an Android device to run the App. Even though most
teens have an Android device, the problem lies in the hardware. Given the mass
manufacturers shipping open-source Android OS
powered phones, you never know what
configuration your Android Device has. So, finding
ADB drivers for your device is a problem unless your
device manufacturer is reputed and provides
support. So, lets get rid of all that hassle, and get
going with the emulator to prevent any further
inconvenience. I will be using Genymotion instead of
default android emulator, because its Awesome.
You can choose to stick with the default emulator if
you have got all the time in the world.

Download Genymotion emulator from genymotion.com, but you will have


to create a free account. Choose the installer with virtual-box since it is pre-
configured for use.

Abhinav Bakshi P a g e 9 | 64
Once you have downloaded it successfully, start the
installer by clicking the application. Finish the installation by
slaying buttons like a ninja, dont break your finger though.
When it finally asks if you would like to restart, click NO. Reach
till the screen shown below, finish the setup, and then restart.

Abhinav Bakshi P a g e 10 | 64
The welcome screen of Genymotion will ask you to add a virtual device. Sign in to
add a virtual device.

Abhinav Bakshi P a g e 11 | 64
Once you sign in, you will be given a list of devices to choose from. For this
tutorial, I am going for Android Version 6.0.0 Custom Phone API 23(768x1280).
You can choose any device from the list depending upon your requirement. Click
next button twice to start downloading. At the time of making this tutorial, the
emulator size is 292Mb, and Genymotion also has resume support for download,
so you can resume in case your download fails.

Abhinav Bakshi P a g e 12 | 64
Patiently wait while the Emulator downloads, maybe watch another Hollywood
movie rescue a kitten save the world

Abhinav Bakshi P a g e 13 | 64
and once its done, click Finish

Now, you can see the device you downloaded in the Genymotion window.

Launch the device by pressing the button from the Menu bar. If the

application crashes, click on settings button and set screen size to a


resolution smaller than your screen size.

Now start the Virtual Device again.

Abhinav Bakshi P a g e 14 | 64
And VOILA!!!

You have a fully functioning, buttery smooth android emulator ready at your
service.

Abhinav Bakshi P a g e 15 | 64
Lesson 4: Integrating the Emulator with Android Studio
Now you need a way to launch Android Studio Apps using Genymotion. Go
ahead and launch Android Studio

Click on configure

Click on Plugins

Hit Browse Repositories

Abhinav Bakshi P a g e 16 | 64
Then search for and install Genymotion plugin

Go ahead and restart android studio to update changes.

Abhinav Bakshi P a g e 17 | 64
Now Android Studio and Android Emulator are configured properly. Which
concludes the Chapter 1. Now we are all set to code like a pro. But before that,
go, celebrate. You finished the toughest part of learning android

THE FREAKIN INSTALLATION

Abhinav Bakshi P a g e 18 | 64
Chapter 2
Creating the first App

Lesson 1: Creating a new project


This chapter will focus on deploying your first application with as minimum
gyaan as possible. The later chapters will deal with the android ecosystem and its
working.
So, without further ado, launch Android Studio.

Abhinav Bakshi P a g e 19 | 64
Start a new project. Give application name as My First App and press Next

Choose Minimum SDK level as 14

Select Blank Activity and press next

Abhinav Bakshi P a g e 20 | 64
Your settings should look like this

Press Finish.
A window shows up for initializing the project. Wait for the initialization to finish
successfully. Make sure Android Studio and JDK are connected and allowed
access to the Internet. If everything goes well, you should see an empty window
with a Tip of the Day popup. Close that window.

Abhinav Bakshi P a g e 21 | 64
Now if you take a look at the window, you will notice

There is a Genymotion button on the toolbar. Which means our integration was
successful. Now, click on Project sidebar on the left.

You can see the newly created project in the tree hierarchy, which means we
have successfully created the first project.

Abhinav Bakshi P a g e 22 | 64
Lesson 2: Running the App
Simply click the button to launch the app. A new window will open
asking for the Genymotion path. Unless you have made changes during
installation, the default path will be C:\Program Files\Genymobile\Genymotion.
Use that path and press OK. This will close the Window.

Abhinav Bakshi P a g e 23 | 64
Now, click on button. Genymotion Device Manager will open. Choose your
phone from List of devices, and then press Start.

Abhinav Bakshi P a g e 24 | 64
A window will open showing Genymotion Android emulator.

Now, go back to Android Studio, close the window showing the list of devices,
and then click the button to launch the App. It will ask you to choose a
running device. Choose Genymotion and press OK.

Abhinav Bakshi P a g e 25 | 64
Wait for some time until App installs on your device. If everything goes
right, you will see your App in Genymotion as

If you dont see any errors, but you still dont see your first App launch
automatically, manually open App Drawer and launch the App.

Abhinav Bakshi P a g e 26 | 64
Shut down the emulator safely by long pressing the power button and then
pressing Power Off

This concludes the second chapter. In the third chapter, we will be making our
Calculator app step by step starting from the basics.

Abhinav Bakshi P a g e 27 | 64
Chapter 3
Designing the Android Calculator

Lesson 1: Creating a new project


Before starting our project, lets take a look at the requirements. The
Unipune syllabus states,

So, breaking it down, we have to develop


1. An output textbox
2. An output indicator for memory
3. Ten buttons for giving numeric input
4. Four buttons for four basic operators
5. Three buttons for trigonometric operators
6. One decimal button
7. Three buttons for memory store, recall and clear
8. One button for AC(all clear)

Abhinav Bakshi P a g e 28 | 64
Lets prototype this quickly using MSPaint :p

So, this is how our application will be looking once its done. As you are
already aware of the process of creating a new app (psst it was covered in last
chapter), quickly fire up Android Studio and create a new project.

Abhinav Bakshi P a g e 29 | 64
Name the App Calculator

Choose Minimum API 14 and Empty activity. Then press Finish button.

Abhinav Bakshi P a g e 30 | 64
Once your project is setup, you will see the Calculator app in android studio.

Dont get fooled by the looks, run the app on the emulator firsthand to make sure
your project and
environment are
setup properly, else
you will face
problems later. This
time, Ill launch
Genymotion app
from my Start Menu
but you can do it
from Android Studio
as well just like we did earlier.

Abhinav Bakshi P a g e 31 | 64
Choose screen size as 480x800 since we will be working in portrait mode for
mobile devices(Note: If the app crashes, go for even lower size, like 320x480)

And launch it

If it launches successfully, you should be able to see it in Android Studio by


pressing the button.

Launch your app in emulator. It will take some time for first build. Wait
patiently
If the build process completes successfully, you will see your app in Genymotion

Abhinav Bakshi P a g e 32 | 64
Now, if you are using the same environment as me, after launching the
app, you will get an error saying

The reason behind this is that we are making our App for Android 4.0,
which had an actionbar, and the API we have downloaded is Android 6.0 which
has a toolbar. WHY GOOGLE WHY!!!
At least the solution is simple, just go to >app>values>styles.xml and
change the line
parent="Theme.AppCompat.Light.DarkActionBar"
to
parent="Base.Theme.AppCompat.Light.DarkActionBar"

When you start coding in Android, always remember that Android is a very
new platform compared to the other players. So, you will always encounter
problems or bugs like the one we encountered even before starting to develop
our app. Whenever such thing happens, just remember, you are not special,
Google isnt doing this purposely to make you get on your knees and cry, and you
will survive developing apps in android. Always remember, StackOverflow is your
friend, and feel free to ask questions on their forum. It doesnt even cost a dime
and you get better advice than what you get from books or professors.

Abhinav Bakshi P a g e 33 | 64
Lesson 2: Getting the hang of it

If you are just like me, you dont have any idea what the is going on
behind the scenes. Dont worry, the key is to take it all in, one step at a time.
Start by visiting the project explorer on the left and expanding every list you see.
Ill spare you from Gradle Scripts since its beyond the scope of this tutorial.
Lets take an analogy to understand what we see here. The app is your
android application as a whole. The java directory can be considered as the
skeleton of your app, and the res directory makes for the flesh which covers the
skeleton.

Abhinav Bakshi P a g e 34 | 64
So, everything you put under res makes up for what you see, and
everything you put under java makes up for how it works. Now, you might ask
what about values. The thing is, when you are developing a large application,
you have to focus on reusability. For example, the color scheme. When you make
an app, you try to keep the color scheme consistent unless you want the user to
die from photo epileptic seizure. So, you define the colors in colors.xml and use
them everywhere in your app.

Same thing with internationalization. What would you do if you want to


translate your app to Spanish or French. Dont say, Hire a translator!!!. You will
have to visit every single file you created for that project, and replace all text
manually. Unless, you use strings.xml under resources. By using a separate file
for storing strings, you can define and change all your strings by accessing a
single file. Makes life easier doesnt it?

I could go on about colors, dimens and styles but it would be better if you
studied them at developer.android.com.

Abhinav Bakshi P a g e 35 | 64
Lesson 3: Designing the layout
Open activity_main.xml and get rid of the Hello World TextView. Your
activity_main.xml should be looking something like this

Now, open the visual designer to design the User Interface. Drag
and drop a grid layout on top of the empty screen. Before you start laying
buttons on the grid, lets do the naamkaran of grid, for reasons you will find out
later.

Abhinav Bakshi P a g e 36 | 64
Select grid layout from component tree at the right.

Go to properties>id and name it calculatorGrid

Now we will be adding elements to the grid. Start with the Plain TextView. Drag
it from Widgets and drop to Grid Row:0,Col:0.

Change its ID to tvOutputScreen and text to 0


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="@+id/tvOutputScreen"
android:layout_row="0"
android:layout_column="0"
/>

Abhinav Bakshi P a g e 37 | 64
Do the same for laying out the buttons. Open the prototype we created in
MSPaint earlier if you need it for reference,

and arrange the buttons in this layout. Basically, just fill the grid starting from 1x0
to 6x3 with buttons. Make sure to give label and id to each button. You can do
that by simply double clicking the button.

Abhinav Bakshi P a g e 38 | 64
Getting the first row

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M+"
android:id="@+id/btnMemPlus"
android:layout_row="1"
android:layout_column="0" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M-"
android:id="@+id/btnMemMinus"
android:layout_row="1"
android:layout_column="1" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MRC"
android:id="@+id/btnMemRC"
android:layout_row="1"
android:layout_column="2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AC"
android:id="@+id/btnAllClear"
android:layout_row="1"
android:layout_column="3" />

Abhinav Bakshi P a g e 39 | 64
Getting the remaining rows.

And as you can see, our calculator app already looks lively and kicking, except,
the output window. So, lets fix that by clicking to the output text view

Going to properties sidebar at the right, and changing layout:columnSpan to 4

So, now, our Output window is 4 columns wide.

Abhinav Bakshi P a g e 40 | 64
Lets also change the height by going to Properties>layout:gravity>fill and
choosing both

This will make the Output window expand to take all available space. Finally,
change the text font size to 50sp.

Abhinav Bakshi P a g e 41 | 64
What you get is a app which looks like a calculator, feels like a calculator, but
does nothing Just sits idle, sleeps and eats. Does that remind you of
someone??? Dont worry, we will fix that (for the calculator) in the next chapter.

Make sure to run this on the emulator before jumping to the next chapter
to ensure you havent accidently introduced any errors in the code.

Abhinav Bakshi P a g e 42 | 64
Chapter 4
Making things Work
Lesson 1: Hooking the XML layout to the JAVA code
In the last chapter, we successfully designed the XML layout which did
nothing. Now, we will be writing code in MainActivity.java to control the
buttons. Before you start coding, its important to understand what we are doing.

Grid Layout
Buttons

Output Window

Abhinav Bakshi P a g e 43 | 64
Remember while designing our layout, we gave a name to our grid layout. Heres
why
In our layout, we have got a total of 24 buttons. If we write code for
handling each button individually, it would be very booooooring and inefficient.
Rather, what we will do is, call our GridLayout(with its name) and command it to
check if there are any good-for-nothing buttons lazily lying around. So, what
GridLayout does is, grabs all those buttons and brings them back to us so we can
put them to work. Heres how

Step 1: Create object for calculatorGrid


Open MainActivity.java and add the line
GridLayout calculatorGrid =

(GridLayout)findViewById(R.id.calculatorGrid);

Just below
setContentView(R.layout.activity_main);

Lets understand what this line does, which will also help solidify your
understanding of how XML interacts with Java code.

(1) (2) (3) (4) (5)

1. GridLayout is the class from Android widget library


android.widget.GridLayout
2. calculatorGrid is the name of object we want to create using GridLayout
class.

Now, one thing to note here is that we havent initialized the class object
here (Remember: GridLayout calculatorGrid = new GridLayout). Thats
because there already exists an object of type GridLayout from when we created
it in activity_main.xml.

3. GridLayout in parentheses is used to typecast the object you obtain from


activity_main.xml. If you understand polymorphism, you will get why its

Abhinav Bakshi P a g e 44 | 64
necessary, else, just assume Java is too dumb to even understand that the
object on left and right side of = sign belong to the same class.
4. Understanding how findViewById works needs some basic knowledge
about the Android SDK. Basically, when you create any button or textView
in Android Studio, the XML code is inflated by the LayoutInflater. In other
words, LayoutInflater takes as input an XML file and builds the View
objects from it. So, findViewById looks for that object in the view hierarchy
and returns a reference to that class.
5. The line R.id.calculatorGrid does what it looks like, points to the inflated
calculatorGrid and returns its reference.

You can find the R file at

Step 2: Get count of its child elements


Below previous line, add the line
int count = calculatorGrid.getChildCount()

Step 3: Identify if the element is a button


Below previous line, add
ButtonClickHandler buttonClickHandler =
new ButtonClickHandler();
for(int i=0; i<count;i++){
View v = calculatorGrid.getChildAt(i);
if(v instanceof Button){
v.setOnClickListener(buttonClickHandler);
}
}

What this code does is, it checks if the child element in calculatorGrid is a button.
If yes, it sends its reference to ButtonClickHandler class to handle it. Dont worry
if Android Studio shows error for ButtonClickHandler. It is not a library class, we
will define it soon.

Abhinav Bakshi P a g e 45 | 64
Step 4: Handle button click
Add the following code

private class ButtonClickHandler


implements View.OnClickListener{
TextView tvOutputScreen =
(TextView)findViewById(R.id.tvOutputScreen);
@Override
public void onClick(View v) {
tvOutputScreen.setText(((Button)v).getText());
}
}

below
protected void onCreate(Bundle savedInstanceState) {
//Some code
}

Now, run the code in Genymotion


and see the magic in action. You see what
you pressSUPERCOOL!!!
In the next lesson, we will make the
calculator do real mathematical operations.

Abhinav Bakshi P a g e 46 | 64
Lesson 2: Making the calculator Work
Try recalling the calculator code you did in FPL lab. Simple, but elegant
eh!!!

Abhinav Bakshi P a g e 47 | 64
Now take out your smartphone and gaze at its calculator.

Your TurboC calculator doesnt seem so elegant and appealing anymore :p.

Abhinav Bakshi P a g e 48 | 64
As appealing as it feels to design a calculator like the second example,
lets face it, neither you nor me will be able to design a math parser along with
the android app in time to complete the exam. So, on a scale of 1 to 10, 1 being
the TurboC app, 10 being the Android app, our app will stand somewhere close to
5. So lets proceed further by accepting this fact.

Step 1: Allowing only numbers on output window


Presently, the ButtonClickHandler class looks like

Create a new Java Class by right clicking on com.pccoe.cl3.calculator folder in


project explorer

Name the class as TestValidator

Abhinav Bakshi P a g e 49 | 64
Create a new method isNumOrDecimal in testValidator class as

The purpose of this method is to check if the button pressed is a number or


decimal point. Now, create an object of this class in MainActivity.java

Replace the line

with the method

Now, if you launch your app,


you see only the numeric
buttons and decimal point
works. Looks more like IP
address.

Abhinav Bakshi P a g e 50 | 64
The current app has the following issues:
1. The zero doesnt go away automatically.
2. The number of decimal points has no limit.
3. The output window cannot be cleared.

We can fix first problem by adding following line

The second problem can be fixed by simply checking for a decimal point. Replace

line with the following block of code

And for the last problem, just add the following code

Now if you run your app, you will see the above problems have been fixed.

Abhinav Bakshi P a g e 51 | 64
Step 2: Getting 2+2=4 right
Now we will be working on our app to get the arithmetic operations
working. Before writing any actual code, lets clear out what we want to achieve.
1. We should be able to give floating point number as input.
2. The answer should also be in floating point.
3. Pressing any operator should show the total result of all previous
operations
4. After pressing any operator, if we press any number, the output window
should clear before displaying the pressed button.
5. The operations go on as long as the user doesnt press either AC or =.

Here, the first two requirements have already been satisfied. If you
arent clear about the third requirement, lets just focus on getting 2+2=4 right.
You will automatically understand the third requirement once thats done.
Start by creating a method in TestValidator.java called isOperator

Call that method from MainActivity.java to find whether the button pressed is
an Operator or not.

Abhinav Bakshi P a g e 52 | 64
Coming back to the 2+2=4 problem, we see, when need to store the
value entered by user to perform operations on it. We will do that whenever user
presses any operator. Define a result and a operator variable in
ButtonClickHandler

Now add following code to the else if part added earlier

If you launch the application now, you can perform some weird
arithmetic operations. For example, entering 2++ will give 4.0 as the answer.
Thats because we are performing the same operation on the value repeatedly.
We will fix this later, first, lets get done with the 2+2=4 problem.

Abhinav Bakshi P a g e 53 | 64
If you run the app, you will see, the output doesnt reset after pressing
any operator. This leads to 2+2 looking like 2.02. To fix that, add the following
code:

Now, if you run the code, you will get 2+2=4.0 Finally!!!

Step 3: Fixing the arithmetic


A simple testing of the app reveals a lot of problems which can be
resolved easily.
1. Subtraction, Multiplication and Division dont work as expected.
2. Equals button is good for nothing.
3. Pressing any operator twice crashes the app

1. We will define a variable prevOperator for storing the operator used in


previous operation. That will help solve most of the problems.

Abhinav Bakshi P a g e 54 | 64
Lets start by modifying the code of Operator Part as

As you can see from the code above, all we are doing is using the prevOperator
variable as a buffer to perform computation. If you run this code now, you can
see that all arithmetic operations are working correctly.

Abhinav Bakshi P a g e 55 | 64
2. Lets make the equals button work by adding the following code in
TestValidator.java

and this in MainActivity.java

3. The reason pressing button twice crashes the app is because when you
press any operator, the value of operator variable changes from nil to the
value of the button pressed.

Then, once the value of operator variable changes from nil,

this little piece of code sets the tvOutputScreen as blank. So, the second time
you press the operator, it tries to add blank to something, which android doesnt
like and hence crashes. Fixing this requires some decent amount of code.

Abhinav Bakshi P a g e 56 | 64
First, create a flagCheck boolean variable and set it to false.

Then set the flag to true if any operator button is pressed

Reset the flag if any numeric button is pressed

And prevent mathematical operations in Operator part if the flag is set to true

And we are all done with our calculator app which can perform basic
mathematical operations.

Abhinav Bakshi P a g e 57 | 64
Lesson 2: Getting trigonometry and memory to work
This work is relatively easy compared to what we did earlier, so, lets
get done with quickly.

Step 1: Trignometry Buttons


In your TestValidator.java, add a method for checking if the button pressed is
trigonometric function

Now, add the following code in your MainActivity.java below Operator Part

Abhinav Bakshi P a g e 58 | 64
This code does what it looks like, checks if any trigonometric button is pressed. If
yes, fetches input from the outpot box, performs operation on it, and displays
result on the same output window.
Now, for some exception handling, just add some code to
Trigonometry part to reset the flag since it overrides the last operator press. Also,
change the value of prevOperator, else it will give erroneous result.

Also, change the line

To

Abhinav Bakshi P a g e 59 | 64
Step 2: Sqrt Buttons
Next, to get the sqrt button to work, add the following code

If you run the app now, you will see that


performing trigonometric operations
after mathematical operation crashes the
app.
The culprit behind this is the code

which sets tvOutputScreen to blank. So,


sin(blank) is nothing, thats why the app
crashes.

Abhinav Bakshi P a g e 60 | 64
Quick fix: Add a little if statement to perform check in both
trigonometry part and sqrt part

Also, assign the value of button pressed to operator in both Trignometry Part and
Sqrt Part to make sure our check for operation trigger fires next time

Abhinav Bakshi P a g e 61 | 64
Step 3: Making memory buttons work
To make memory buttons work, we need to define a variable to store in
memory. Lets define some rules for memory before we actually start coding:
1. Pressing M+ will add anything on outputWindow to Memory
2. Pressing M- will subtract anything on outputWindow from Memory
3. If outputWindow is nil, it will fetch data from result.
4. Pressing MRC once will recall the value from memory.
5. Pressing MRC twice will clear the value from memory.
6. Pressing AC will not clear the memory.

Now, lets start the implementation by defining a memory variable

Then define a function to check if button pressed is memory button in


TestValidator class

Add a condition statement below sqrt condition statement

Abhinav Bakshi P a g e 62 | 64
Store the value to be added to memory in a temporary variable. If
outputWindow contains a value, store that, else get value from result
variable.

Perform operations on pressing M+ and M-

Perform operations on MRC

Abhinav Bakshi P a g e 63 | 64
With that we get a fully functioning sleek and shiny calculator app
which actually does something. We can work on the styling to make it look
better, but this is mereko basss exam nikalna hai android tutorial, not
chal playstore ke liye app banate hai android tutorial. Hope you guys find
this tutorial useful and best of luck for your exams

Abhinav Bakshi P a g e 64 | 64

You might also like