0% found this document useful (0 votes)
5 views

Mobile Application Development Lab Manual

The document is a lab manual for a Mobile Application Development course at Sri Balaji College of Engineering & Technology, detailing various experiments and applications to be developed using Android Studio. It includes step-by-step instructions for creating applications such as a Hello World app, login screen, calculator, and more, along with explanations of essential components like the AndroidManifest.xml and layout files. The manual serves as a guide for students in their practical learning of mobile app development.

Uploaded by

sanjay sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Mobile Application Development Lab Manual

The document is a lab manual for a Mobile Application Development course at Sri Balaji College of Engineering & Technology, detailing various experiments and applications to be developed using Android Studio. It includes step-by-step instructions for creating applications such as a Hello World app, login screen, calculator, and more, along with explanations of essential components like the AndroidManifest.xml and layout files. The manual serves as a guide for students in their practical learning of mobile app development.

Uploaded by

sanjay sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 173

LAB MANUAL

Subject Code: 6CS4-24


MOBILE APPLICATION DEVELOPMENT LAB
(III B. Tech VI Semester CSE)

Established in year 2000

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

SRI BALAJI COLLEGE OF ENGINEERING & TECHNOLOGY,


BENAD ROAD, JAIPUR – 302013

Website: www.sbss.ac.in

i
S.NO. Title Page no.

1. Create a Hello World Android Application. 1

2. Create a Login Screen Android Application. 14

3. Create Calculator Android Application. 25


4. To develop a Android Application that makes use of RSS Feed. 43

5. To develop a Simple Android Application that draws basic Graphical 56


Primitives on the screen.

6. Create a Database Android Application using SQLite Database. 65

7. Develop a native application that uses GPS location information 80


.
8. To develop a Android Application that writes data to the SD Card 100
.
9. Design a gaming application. 126

10. Create an application to handle images and videos according to size. 171

ii
Exp 1: Create a Hello World Android Application.

Create Android Application

The first step is to create a simple Android Application using Android studio. When you click on
Android studio icon, it will show screen as shown below

You can start your application development by calling start a new android studio project. in a new
installation frame should ask Application name, package information and location of the project.−

1
After entered application name, it going to be called select the form factors your application runs
on, here need to specify Minimum SDK, Let it be declared as API23: Android 6.0(Marshmallow)

2
The next level of installation should contain selecting the activity to mobile; it specifies the default
layout for Applications.

3
At the final stage it going to be open development tool to write the application code.

Anatomy of Android Application

Before you run your app, you should be aware of a few directories and files in the Android project

4
Sr.No. Folder, File & Description

Java

1. This contains the .java source files for your project. By default, it includes
an MainActivity.java source file having an activity class that runs when your app is launched
using the app icon.

5
res/drawable-hdpi
2.
This is a directory for drawable objects that are designed for high-density screens.

res/layout
3.
This is a directory for files that define your app's user interface.

res/values

4. This is a directory for other various XML files that contain a collection of resources, such as
strings and colours definitions.

AndroidManifest.xml

5. This is the manifest file which describes the fundamental characteristics of the app and defines
each of its components.

Build.gradle

6. This is an auto generated file which contains compileSdkVersion, buildToolsVersion,


applicationId, minSdkVersion, targetSdkVersion, versionCode and versionName

Following section will give a brief overview of the important application files.

The Main Activity File

The main activity code is a Java file MainActivity.java. This is the actual application file which
ultimately gets converted to a Dalvik executable and runs your application. Following is the default
code generated by the application wizard for Hello World! application −

package com.example.helloworld;

6
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder.
The onCreate() method is one of many methods that are figured when an activity is loaded.

The Manifest File

Whatever component you develop as a part of your application, you must declare all its
components in a manifest.xml which resides at the root of the application project directory. This
file works as an interface between Android OS and your application, so if you do not declare your
component in this file, then it will not be considered by the OS. For example, a default manifest
file will look like as following file −

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.tutorialspoint7.myapplication">

<application

7
android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>

Here <application>...</application> tags enclosed the components related to the application.


Attribute android:icon will point to the application icon available under res/drawable-hdpi. The
application uses the image named ic_launcher.png located in the draw able folders

The <activity> tag is used to specify an activity and android:name attribute specifies the fully
qualified class name of the Activity subclass and the android:label attributes specifies a string to
use as the label for the activity. You can specify multiple activities using <activity> tags.

The action for the intent filter is named android.intent.action.MAIN to indicate that this activity
serves as the entry point for the application. The category for the intent-filter is

8
named android.intent.category.LAUNCHER to indicate that the application can be launched from
the device's launcher icon.

The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to
the app_name string defined in the strings.xml file, which is "HelloWorld". Similar way, other
strings get populated in the application.

Following is the list of tags which you will use in your manifest file to specify different Android
application components −

• <activity>elements for activities

• <service> elements for services

• <receiver> elements for broadcast receivers

• <provider> elements for content providers

The Strings File

The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types of strings
go into this file. This file is responsible for their textual content. For example, a default strings file
will look like as following file −

<resources>

<string name="app_name">HelloWorld</string>

<string name="hello_world">Hello world!</string>

<string name="menu_settings">Settings</string>

<string name="title_activity_main">MainActivity</string>

</resources>

The Layout File

9
The activity_main.xml is a layout file available in res/layout directory that is referenced by your
application when building its interface. You will modify this file very frequently to change the
layout of your application. For your "Hello World!" application, this file will have following
content related to default layout −

<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" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:padding="@dimen/padding_medium"

android:text="@string/hello_world"

tools:context=".MainActivity" />

</RelativeLayout>

This is an example of simple RelativeLayout which we will study in a separate chapter.


The TextView is an Android control used to build the GUI and it have various attributes
like android:layout_width, android:layout_height etc which are being used to set its width and
height etc.. The @string refers to the strings.xml file located in the res/values folder. Hence,

10
@string/hello_world refers to the hello string defined in the strings.xml file, which is "Hello
World!".

Running the Application

Let's try to run our Hello World! application we just created. I assume you had created
your AVD while doing environment set-up. To run the app from Android studio, open one of your
project's activity files and click Run icon from the tool bar. Android studio installs the app on
your AVD and starts it and if everything is fine with your set-up and application, it will display
following Emulator window −

11
Exp2: Create a Login Screen Android Application.

A login application is the screen asking your credentials to login to some particular application.
You might have seen it when logging into Facebook, twitter etc.

This experiment explains how to create a login screen and how to manage security when false
attempts are made. First you have to define two TextView asking username and password of the
user. The password TextView must have inputType set to password. Its syntax is given below −

<EditText

android:id = "@+id/editText2"

android:layout_width = "wrap_content"

android:layout_height = "wrap_content"

android:inputType = "textPassword" />

<EditText

android:id = "@+id/editText1"

android:layout_width = "wrap_content"

android:layout_height = "wrap_content"

/>

Define a button with login text and set its onClick Property. After that define the function
mentioned in the onClick property in the java file.

<Button

android:id = "@+id/button1"

android:layout_width = "wrap_content"

12
android:layout_height = "wrap_content"

android:onClick = "login"

android:text = "@string/Login"

/>

In the java file, inside the method of onClick get the username and passwords text
using getText() and toString() method and match it with the text using equals() function.

EditText username = (EditText)findViewById(R.id.editText1);

EditText password = (EditText)findViewById(R.id.editText2);

public void login(View view){

if(username.getText().toString().equals("admin") &&
password.getText().toString().equals("admin")){

//correcct password

}else{

//wrong password

The last thing you need to do is to provide a security mechanism, so that unwanted attempts should
be avoided. For this initialize a variable and on each false attempt, decrement it. And when it
reaches to 0, disable the login button.

int counter = 3;

counter--;

13
if(counter==0){

//disble the button, close the application e.t.c

Example

Here is an example demonstrating a login application. It creates a basic application that gives you
only three attempts to login to an application.

To experiment with this example, you can run this on an actual device or in an emulator.

Steps Description

1. You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.

2. Modify src/MainActivity.java file to add necessary code.

3. Modify the res/layout/activity_main to add respective XML components

4. Run the application and choose a running android device and install the application on it and
verify the results

Following is the content of the modified main activity file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;

14
import android.graphics.Color;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends Activity {

Button b1,b2;

EditText ed1,ed2;

TextView tx1;

int counter = 3;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

15
b1 = (Button)findViewById(R.id.button);

ed1 = (EditText)findViewById(R.id.editText);

ed2 = (EditText)findViewById(R.id.editText2);

b2 = (Button)findViewById(R.id.button2);

tx1 = (TextView)findViewById(R.id.textView3);

tx1.setVisibility(View.GONE);

b1.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if(ed1.getText().toString().equals("admin") &&

ed2.getText().toString().equals("admin")) {

Toast.makeText(getApplicationContext(),

"Redirecting...",Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(getApplicationContext(), "Wrong

Credentials",Toast.LENGTH_SHORT).show();

tx1.setVisibility(View.VISIBLE);

16
tx1.setBackgroundColor(Color.RED);

counter--;

tx1.setText(Integer.toString(counter));

if (counter == 0) {

b1.setEnabled(false);

});

b2.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

finish();

});

Following is the modified content of the xml res/layout/activity_main.xml.

In the following code abc indicates about logo of tutorialspoint.com

17
<?xml version = "1.0" encoding = "utf-8"?>

<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 = ".MainActivity">

<TextView android:text = "Login" android:layout_width="wrap_content"

android:layout_height = "wrap_content"

android:id = "@+id/textview"

android:textSize = "35dp"

android:layout_alignParentTop = "true"

android:layout_centerHorizontal = "true" />

<TextView

android:layout_width = "wrap_content"

android:layout_height = "wrap_content"

android:text = "Tutorials point"

android:id = "@+id/textView"

18
android:layout_below = "@+id/textview"

android:layout_centerHorizontal = "true"

android:textColor = "#ff7aff24"

android:textSize = "35dp" />

<EditText

android:layout_width = "wrap_content"

android:layout_height = "wrap_content"

android:id = "@+id/editText"

android:hint = "Enter Name"

android:focusable = "true"

android:textColorHighlight = "#ff7eff15"

android:textColorHint = "#ffff25e6"

android:layout_marginTop = "46dp"

android:layout_below = "@+id/imageView"

android:layout_alignParentLeft = "true"

android:layout_alignParentStart = "true"

android:layout_alignParentRight = "true"

android:layout_alignParentEnd = "true" />

<ImageView

19
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:inputType="textPassword"

android:ems="10"

android:id="@+id/editText2"

android:layout_below="@+id/editText"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignRight="@+id/editText"

android:layout_alignEnd="@+id/editText"

android:textColorHint="#ffff299f"

android:hint="Password" />

20
<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Attempts Left:"

android:id="@+id/textView2"

android:layout_below="@+id/editText2"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:textSize="25dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="New Text"

android:id="@+id/textView3"

android:layout_alignTop="@+id/textView2"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:layout_alignBottom="@+id/textView2"

android:layout_toEndOf="@+id/textview"

android:textSize="25dp"

21
android:layout_toRightOf="@+id/textview" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="login"

android:id="@+id/button"

android:layout_alignParentBottom="true"

android:layout_toLeftOf="@+id/textview"

android:layout_toStartOf="@+id/textview" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Cancel"

android:id="@+id/button2"

android:layout_alignParentBottom="true"

android:layout_toRightOf="@+id/textview"

android:layout_toEndOf="@+id/textview" />

</RelativeLayout>

22
Following is the content of the res/values/string.xml.

<resources>

<string name="app_name">My Application</string>

</resources>

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.sairamkrishna.myapplication" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />

23
<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>

Let's try to run our application we just modified. I assume you had created your AVD while doing
environment setup. To run the app from Android studio, open one of your project's activity files
and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it
and if everything is fine with your setup and application, it will display following Emulator
window −

24
Type anything in the username and password field, and then press the login button. I put abc in the
username field and abc in the password field. I got failed attempt. This is shown below −

25
Do this two more time, and you will see that you have 0 login attempts left and your login button
is disabled.

Now open the application again, and this time enter correct username as admin and password as
admin and click on login. You will be successfully login.
26
If user press on cancel button, it will close an application of login screen.

27
Exp3: Create Calculator Android Application.

How To Create Calculator App In Android Studio: Step By Step Guide

Do you use calculator? Of Course you do in your regular life…

So why not create your own basic Calculator Android App in Android Studio and use it for doing
those operations. If you don’t know how to built then you are for treat as we are going to share
how the App is created in Android. This is the one of simplest App you can create to
understand Android basics.

In this Calculator App tutorial we are going use of multiple Android UI components to design and
step by step developing a Basic Calculator application in Android Studio.

Topics Used For Creating Calculator App – Before following the below steps it is
recommended you check out EditText, TextView, Button & Linear Layout topics. Also go
through JAVA OOPS concept once.

How To Create Calculator App In Android Studio:

Below you can download code, see final output and step by step explanation of Calculator App in
Android Studio.

Step 1: Firstly, get the android studio downloaded in your system, then open it.

28
Step 2: Create a new project and name it Calculator.

Step 3: Open res -> layout -> activity_main.xml (or) main.xml. Here we are going to create the
application interface like add layouts, Button ,TextView and EditText.

i of Step 3 – Create a Linearlayout vertical, add a textview followed by two textfields


Number(decimal) for writing numbers in it. Starting code of activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context="abhiandroid.com.calculater.MainActivity"

android:orientation="vertical"

android:gravity="top"

android:textAlignment="center"

android:background="@android:color/holo_blue_bright"

android:weightSum="1">

<TextView

29
android:text="@string/enter_two_numbers"

android:layout_width="match_parent"

android:id="@+id/textView"

android:layout_height="30dp"

android:gravity="center_horizontal"

android:textColorLink="?android:attr/editTextColor"

tools:textStyle="bold|italic"

android:textStyle="bold|italic"

android:fontFamily="serif"

android:visibility="visible"

android:textSize="24sp"

android:layout_weight="0.07"/>

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="number"

android:ems="10"

android:id="@+id/editOp1"

android:textSize="18sp"

android:gravity="center_horizontal"

android:layout_marginBottom="5dp"

android:visibility="visible"/>

30
<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="number"

android:ems="10"

android:id="@+id/editOp2"

android:textSize="18sp"

android:gravity="center_horizontal"

android:elevation="1dp"/>

</LinearLayout>

The UI will currently look like this:

ii of Step 3 – Then before closing the above layout define another layout as Linearlayout
horizontal, add five button ( +, -, *, / and Clear) define their properties like id , width, height etc.
in it and close the linear layout.

31
Following code of activity_main.xml. This code will be inserted in main layout:

<LinearLayout

android:orientation="horizontal"

android:layout_width="match_parent"

android:layout_height="wrap_content">

<Button

android:text="+"

android:layout_width="78dp"

android:layout_height="wrap_content"

android:id="@+id/btnadd"

android:layout_weight="0.03"/>

<Button

android:text="-"

32
android:layout_width="78dp"

android:layout_height="wrap_content"

android:id="@+id/btnsub"

android:layout_weight="0.03"/>

<Button

android:text="*"

android:layout_width="78dp"

android:layout_height="wrap_content"

android:id="@+id/btnmul"

android:layout_weight="0.03"/>

<Button

android:text="/"

android:layout_height="wrap_content"

android:id="@+id/btndiv"

android:layout_width="78dp"

android:layout_weight="0.03"/>

<Button

android:text="Clear"

android:layout_width="80dp"

android:layout_height="wrap_content"

33
android:id="@+id/btnclr"

android:layout_weight="0.03"/>

</LinearLayout>

The UI will now look like this:

iii of Step 3 – Further in continuation with previous linearlayout add a textview, textfield(Number)
for displaying result which makes the interface complete.

The complete interface code of activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

34
android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context="abhiandroid.com.calculater.MainActivity"

android:orientation="vertical"

android:gravity="top"

android:textAlignment="center"

android:background="@android:color/holo_blue_bright"

android:weightSum="1">

<TextView

android:text="@string/enter_two_numbers"

android:layout_width="match_parent"

android:id="@+id/textView"

android:layout_height="30dp"

android:gravity="center_horizontal"

android:textColorLink="?android:attr/editTextColor"

tools:textStyle="bold|italic"

android:textStyle="bold|italic"

android:fontFamily="serif"

android:visibility="visible"

android:textSize="24sp"

35
android:layout_weight="0.07"/>

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="number"

android:ems="10"

android:id="@+id/editOp1"

android:textSize="18sp"

android:gravity="center_horizontal"

android:layout_marginBottom="5dp"

android:visibility="visible"/>

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="number"

android:ems="10"

android:id="@+id/editOp2"

android:textSize="18sp"

android:gravity="center_horizontal"

android:elevation="1dp"/>

36
<LinearLayout

android:orientation="horizontal"

android:layout_width="match_parent"

android:layout_height="wrap_content">

<Button

android:text="+"

android:layout_width="78dp"

android:layout_height="wrap_content"

android:id="@+id/btnadd"

android:layout_weight="0.03"/>

<Button

android:text="-"

android:layout_width="78dp"

android:layout_height="wrap_content"

android:id="@+id/btnsub"

android:layout_weight="0.03"/>

<Button

android:text="*"

android:layout_width="78dp"

android:layout_height="wrap_content"

37
android:id="@+id/btnmul"

android:layout_weight="0.03"/>

<Button

android:text="/"

android:layout_height="wrap_content"

android:id="@+id/btndiv"

android:layout_width="78dp"

android:layout_weight="0.03"/>

<Button

android:text="Clear"

android:layout_width="80dp"

android:layout_height="wrap_content"

android:id="@+id/btnclr"

android:layout_weight="0.03"/>

</LinearLayout>

<TextView

android:text="@string/result"

android:layout_width="332dp"

android:id="@+id/textView1"

android:layout_marginTop="10dp"

38
android:layout_height="50dp"

android:gravity="center_horizontal"

android:textColorLink="?android:attr/editTextColor"

tools:textStyle="bold|italic"

android:textStyle="bold|italic"

android:fontFamily="serif"

android:visibility="visible"

android:textSize="30sp"/>

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="number"

android:ems="10"

android:id="@+id/result"

android:textSize="18sp"

android:text="0.00"

android:gravity="center_horizontal"/>

</LinearLayout>

So now we have designed the complete UI of the Calculator App.

39
Step 4: Open src -> package -> MainActivity.java. The interface part of the application is over,
let’s focus on adding functionality to the application. This calculator app basically perform five
operations i.e addition, subtraction, multiplication, division and reset. So for that we need to define
these operation over button click. For that we use setOnClickListener() function.

parseDouble() is used to convert String value to double. By default the value is String and we need
to convert it into Double to perform operation over it.

If person doesn’t enter the value and directly click on the any button then a Toast message will
appear on the screen telling user to enter the required numbers.

packageabhiandroid.com.calculater;

import android.support.v7.app.AppCompatActivity;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.widget.Button;

importandroid.widget.EditText;

importandroid.widget.TextView;

40
importandroid.widget.Toast;

publicclassMainActivityextendsAppCompatActivity{

privateEditText opr1;

privateEditText opr2;

privateButtonbtnadd;

privateButtonbtnsub;

privateButtonbtnmul;

privateButtonbtndiv;

privateButtonbtnclr;

privateTextViewtxtresult;

@Override

protectedvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

opr1 =(EditText)findViewById(R.id.editOp1);

opr2 =(EditText)findViewById(R.id.editOp2);

btnadd=(Button)findViewById(R.id.btnadd);

btnsub=(Button)findViewById(R.id.btnsub);

btnmul=(Button)findViewById(R.id.btnmul);

btndiv=(Button)findViewById(R.id.btndiv);

btnclr=(Button)findViewById(R.id.btnclr);

41
txtresult=(TextView)findViewById(R.id.result);

// Addition

btnadd.setOnClickListener(newView.OnClickListener(){

@Override

publicvoidonClick(View v){

if((opr1.getText().length()>0)&&(opr2.getText().length()>0))

double oper1 =Double.parseDouble(opr1.getText().toString());

double oper2 =Double.parseDouble(opr2.getText().toString());

double result = oper1 + oper2;

txtresult.setText(Double.toString(result));

else{

Toast toast=Toast.makeText(MainActivity.this,"Enter The Required Numbers",Toast.LENGTH_


LONG);

toast.show();

});

//Subtraction

btnsub.setOnClickListener(newView.OnClickListener(){

@Override

publicvoidonClick(View v){

42
if((opr1.getText().length()>0)&&(opr2.getText().length()>0))

double oper1 =Double.parseDouble(opr1.getText().toString());

double oper2 =Double.parseDouble(opr2.getText().toString());

double result = oper1 - oper2;

txtresult.setText(Double.toString(result));

else{

Toast toast=Toast.makeText(MainActivity.this,"Enter The Required Numbers",Toast.LENGTH_


LONG);

toast.show();

});

// Multiplication

btnmul.setOnClickListener(newView.OnClickListener(){

@Override

publicvoidonClick(View v){

if((opr1.getText().length()>0)&&(opr2.getText().length()>0))

double oper1 =Double.parseDouble(opr1.getText().toString());

double oper2 =Double.parseDouble(opr2.getText().toString());

43
double result = oper1 * oper2;

txtresult.setText(Double.toString(result));

else{

Toast toast=Toast.makeText(MainActivity.this,"Enter The Required Numbers",Toast.LENGTH_


LONG);

toast.show();

});

// Division

btndiv.setOnClickListener(newView.OnClickListener(){

@Override

publicvoidonClick(View v){

if((opr1.getText().length()>0)&&(opr2.getText().length()>0))

double oper1 =Double.parseDouble(opr1.getText().toString());

double oper2 =Double.parseDouble(opr2.getText().toString());

double result = oper1 / oper2;

txtresult.setText(Double.toString(result));

else{

Toast toast=Toast.makeText(MainActivity.this,"Enter The Required Numbers",Toast.LENGTH_


LONG);
44
toast.show();

});

// Reset Feilds

btnclr.setOnClickListener(newView.OnClickListener(){

@Override

publicvoidonClick(View v){

opr1.setText("");

opr2.setText("");

txtresult.setText("0.00");

opr1.requestFocus();

});

OUTPUT:
Now run the App and you will see the basic calculator App. Enter any number and do the
operations.

45
46
Exp4: To develop a Android Application that makes use of RSS Feed.

Procedure:

Creating a New project:

Open Android Studio and then click on File -> New -> New project.

Then type the Application name as “ex.no.6″ and click Next.

Then select the Minimum SDK as shown below and click Next.

47
Then select the Empty Activity and click Next.

Finally click Finish.

48
▪ It will take some time to build and load the project.
▪ After completion it will look as given below.

Designing layout for the Android Application:

Click on app -> res -> layout -> activity_main.xml

49
Now click on Text as shown below.

Then delete the code which is there and type the code as given below.
Code for Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ListView
android:id="@+id/listView"

50
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

Now click on Design and your application will look as given below.

So now the designing part is completed.


Adding permissions in Manifest for the Android Application:

Click on app -> manifests -> AndroidManifest.xml

Now include the INTERNET permissions in the AndroidManifest.xml file as shown below

51
Code for AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exno6" >

<uses-permission android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

52
</manifest>

So now the Permissions are added in the Manifest.


Java Coding for the Android Application:

Click on app -> java -> com.example.exno6 -> MainActivity.

Then delete the code which is there and type the code as given below.
Code for MainActivity.java:
package com.example.exno6;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

53
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity


{
List headlines;
List links;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
new MyAsyncTask().execute();
}

class MyAsyncTask extends AsyncTask<Object,Void,ArrayAdapter>


{
@Override
protected ArrayAdapter doInBackground(Object[] params)
{
headlines = new ArrayList();
links = new ArrayList();
try
{
URL url = new URL("https://codingconnect.net/feed");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);

54
XmlPullParser xpp = factory.newPullParser();

// We will get the XML from an input stream


xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;

// Returns the type of current event: START_TAG, END_TAG, etc..


int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
if (xpp.getName().equalsIgnoreCase("item"))
{
insideItem = true;
}
else if (xpp.getName().equalsIgnoreCase("title"))
{
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
}
else if (xpp.getName().equalsIgnoreCase("link"))
{
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}
else if(eventType==XmlPullParser.END_TAG &&
xpp.getName().equalsIgnoreCase("item"))
{
insideItem=false;

55
}
eventType = xpp.next(); //move to next element
}

}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (XmlPullParserException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(ArrayAdapter adapter)
{
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1,
headlines);
setListAdapter(adapter);
}
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
Uri uri = Uri.parse((links.get(position)).toString());

56
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}

public InputStream getInputStream(URL url)


{
try
{
return url.openConnection().getInputStream();
}
catch (IOException e)
{
return null;
}
}
}

▪ So now the Coding part is also completed.


▪ Now run the application to see the output.

57
Output:

Result:

Thus Android Application that makes use of RSS Feed is developed and executed successfully.

58
Exp5: To develop a Simple Android Application that draws basic Graphical Primitives on
the screen.

Procedure:

Creating a New project:

Open Android Studio and then click on File -> New -> New project.

Then type the Application name as “ex.no.4″ and click Next.

Then select the Minimum SDK as shown below and click Next.

59
Then select the Empty Activity and click Next.

Finally click Finish.

60
▪ It will take some time to build and load the project.
▪ After completion it will look as given below.

61
Designing layout for the Android Application:

Click on app -> res -> layout -> activity_main.xml.

Now click on Text as shown below.

Then delete the code which is there and type the code as given below.

62
Code for Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView" />
</RelativeLayout>

Now click on Design and your application will look as given below.

So now the designing part is completed.

63
Java Coding for the Android Application:

Click on app -> java -> com.example.exno4 -> MainActivity.

Then delete the code which is there and type the code as given below.
Code for MainActivity.java:
package com.example.exno4;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity


{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

64
setContentView(R.layout.activity_main);

//Creating a Bitmap
Bitmap bg = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);

//Setting the Bitmap as background for the ImageView


ImageView i = (ImageView) findViewById(R.id.imageView);
i.setBackgroundDrawable(new BitmapDrawable(bg));

//Creating the Canvas Object


Canvas canvas = new Canvas(bg);

//Creating the Paint Object and set its color & TextSize
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(50);

//To draw a Rectangle


canvas.drawText("Rectangle", 420, 150, paint);
canvas.drawRect(400, 200, 650, 700, paint);

//To draw a Circle


canvas.drawText("Circle", 120, 150, paint);
canvas.drawCircle(200, 350, 150, paint);

//To draw a Square


canvas.drawText("Square", 120, 800, paint);
canvas.drawRect(50, 850, 350, 1150, paint);

//To draw a Line


canvas.drawText("Line", 480, 800, paint);

65
canvas.drawLine(520, 850, 520, 1150, paint);
}
}
▪ So now the Coding part is also completed.
▪ Now run the application to see the output.
Output:

Result:

Thus a Simple Android Application that draws basic Graphical Primitives on the screen is
developed and executed successfully.

66
Exp6: Create a Database Android Application using SQLite Database.
We will create a database Android application that has a UI as follows:

My application will interact with a database named StudentDB.db, which contains a single table
named Student. The Student table schema will look like this:

The application will consist of an activity and a database handler class (MyDBHandler class). The
database handler will be a subclass of SQLiteOpenHelper and will provide an abstract layer
between the underlying SQLite database and the activity class. A third class (Student class) will
need to be implemented to hold the database entry data as it is passed between the activity and the
handler. My application model can be shown in the following figure:

67
We create the Student class in the Android Studio 3.0 by selecting app > java.

Right-click the myfirstdatabase package and selecting New > Java Class.

Type Student in the Name item, maintain the default options, and click the OK button:

68
Adding the following lines of code for the Student class:

public class Student {


// fields
private int studentID;
private String studentName;
// constructors
public Student() {}
public Student(int id, String studentname) {
this.studentID = id;
this.studentName = studentname;
}
// properties
public void setID(int id) {
this.studentID = id;

69
}
public int getID() {
return this.studentID;
}
public void setStudentName(String studentname) {
this.studentName = studentname;
}
public String getStudentName() {
return this.studentName;
}
}

Data Handler Class

The database handler class is a subclass of SQLiteOpenHelper class, named MyDBHandler, as

The MyDBHandler class contains fields, constructors, and methods, as follows:

Steps for creating the MyDBHandler class like the Student class and its code can look like this:

public class MyDBHandler extends SQLiteOpenHelper {


//information of database
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "studentDB.db";
public static final String TABLE_NAME = "Student";
public static final String COLUMN_ID = "StudentID";
public static final String COLUMN_NAME = "StudentName";

70
//initialize the database
public MyDBHandler(Context context, Stringname, SQLiteDatabase.CursorFactoryfactory, intv
ersion) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {}
public String loadHandler() {}
public void addHandler(Student student) {}
public Student findHandler(String studentname) {}
public boolean deleteHandler(int ID) {}
public boolean updateHandler(int ID, String name) {}
}

We must also use import statements, as follows:

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;

Initialize the Database

The database can be initialized in the constructor of the MyDBHandler class. The code of this
constructor looks like this:

public MyDBHandler(Context context, Stringname,

71
SQLiteDatabase.CursorFactoryfactory, intversion) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

Create the Student Table

The SQL statement creates a table:

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
....
);

We need to convert the SQL statement to a string and implement it by using the execSQL() method
of a SQLiteDatabase object. All of these statements will be put inside the onCreate method of the
handler class, as follows:

public void onCreate(SQLiteDatabase db) {


String CREATE_TABLE = "CREATE TABLE" + TABLE_NAME + "(" + COLUMN_ID +
"INTEGER PRIMARYKEY," + COLUMN_NAME + "TEXT )";
db.execSQL(CREATE_TABLE);
}

Our application can load all of the students from the database, add a new student to the database,
remove a student from the database, find a student from the database and modify the information
of a student from the database. Therefore, we need to add corresponding methods to the handler
class.

Load Data

To load data, we use a SQL query statement:

72
SELECT * FROM table_name;

The result of above SQL statement is a table. We use the rawQuery() method of a SQLiteDatabase
object to implement SQL statement and display result via a Cursor object. The following code will
demonstrate the loadHandler method:

public String loadHandler() {


String result = "";
String query = "Select*FROM" + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
int result_0 = cursor.getInt(0);
String result_1 = cursor.getString(1);
result += String.valueOf(result_0) + " " + result_1 +
System.getProperty("line.separator");
}
cursor.close();
db.close();
return result;
}

Add a New Record

To add a new record to the database, we must use the ContentValues object with the put() method
that is used to assign data to ContentsValues object and then use insert() method of
SQLiteDatabase object to insert data to the database. The addHandler method can look like this:

public void addHandler(Student student) {


ContentValues values = new ContentValues();
values.put(COLUMN_ID, student.getID());
values.put(COLUMN_NAME, student.getStudentName());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_NAME, null, values);

73
db.close();
}

Find Information by Condition

To find information in the database by condition, we must use the SQL query statement as follows:

SELECT * FROM table_name WHERE column_name;

In the next step, we save the result that is returned from implementation of the rawQuery() method
of the SQLiteDatabase object into a Cursor object and find the matching result in this object. The
code of the findHandler method looks like this:

public Student findHandler(Stringstudentname) {


Stringquery = "Select * FROM " + TABLE_NAME + "WHERE" + COLUMN_NAME + " = " +
"'" + studentname + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Student student = new Student();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
student.setID(Integer.parseInt(cursor.getString(0)));
student.setStudentName(cursor.getString(1));
cursor.close();
} else {
student = null;
}
db.close();
return student;
}

Delete a Record by Condition

To delete a record by condition, we must use a SQL query statement, as follows:

74
SELECT * FROM table_name WHERE column_name;

We will save the result that is returned from the implementation of the rawQuery() method of the
SQLiteDatabase object into a Cursor object and find the matching result in this object. In the final
step, we use the delete() method of the SQLiteDatabase object to delete the record. The code of
the deleteHandler method looks like:

public boolean deleteHandler(int ID) {


booleanresult = false;
Stringquery = "Select*FROM" + TABLE_NAME + "WHERE" + COLUMN_ID + "= '" + String
.valueOf(ID) + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Student student = new Student();
if (cursor.moveToFirst()) {
student.setID(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_NAME, COLUMN_ID + "=?",
newString[] {
String.valueOf(student.getID())
});
cursor.close();
result = true;
}
db.close();
return result;
}

Update Information of a Record

To update the information of a record, we can use the ContentValues object and the update()
method of the SQLiteDatabase object. Use the updateHandler() method as follows:

public boolean updateHandler(int ID, String name) {


SQLiteDatabase db = this.getWritableDatabase();

75
ContentValues args = new ContentValues();
args.put(COLUMN_ID, ID);
args.put(COLUMN_NAME, name);
return db.update(TABLE_NAME, args, COLUMN_ID + "=" + ID, null) > 0;
}

Main Activity

our user interface:

76
The code for the click event of the buttons and results is as follows:

Code for the LOAD DATA button:

public void loadStudents(View view) {


MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
lst.setText(dbHandler.loadHanler());
studentid.setText("");
studentname.setText("");
}

In the XML file:

<Button
android:id="@+id/btnload"
android:onClick="loadStudents"
android:text="@string/Load"
......
/>

The result looks like this:

77
Code for the ADD button:

public void addStudent(View view) {


MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
int id = Integer.parseInt(studentid.getText().toString());
String name = studentname.getText().toString();
Student student = new Student(id, name);
dbHandler.addHandler(student);
studentid.setText("");
studentname.setText("");
}

In the XML file:

<Button
android:id="@+id/btnadd"
android:onClick="addStudent"
android:text="@string/Add"

78
.... />

Code for the FIND button:

public void findStudent(View view) {


MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
Studentstudent =
dbHandler.findHandler(studentname.getText().toString());
if (student != null) {
lst.setText(String.valueOf(student.getID()) + " " + student.getStudentName() + System.getPrope
rty("line.separator"));
studentid.setText("");
studentname.setText("");
} else {
lst.setText("No Match Found");
studentid.setText("");
studentname.setText("");
}
}

In the XML file:

<Button
android:id="@+id/btnfind"
android:onClick="findStudent"
android:text="@string/Find"..../>

The result looks like this:

79
Code for the DELETE button:

public void removeStudent(View view) {


MyDBHandler dbHandler = new MyDBHandler(this, null,
null, 1);
boolean result = dbHandler.deleteHandler(Integer.parseInt(
studentid.getText().toString()));
if (result) {
studentid.setText("");
studentname.setText("");
lst.setText("Record Deleted");
} else
studentid.setText("No Match Found");
}

In the XML file:

<Button
android:id="@+id/btndelete"

80
android:onClick="removeStudent"
android:text="@string/Delete"
........ />

The result looks like this:

Code for the UPDATE button:

public void updateStudent(View view) {


MyDBHandler dbHandler = new MyDBHandler(this, null,
null, 1);
boolean result = dbHandler.updateHandler(Integer.parseInt(
studentid.getText().toString()), studentname.getText().toString());
if (result) {
studentid.setText("");
studentname.setText("");
lst.setText("Record Updated");
} else

81
studentid.setText("No Match Found");
}

In the XML file:

<Button
android:id="@+id/btnupdate"
android:onClick="updateStudent"
android:text="@string/Update"
.... />

The result looks like this:

82
Conclusion:
In this article, I have introduced how to create a simple database Android application in Android
Studio 3.0. I hope that this article is useful for beginners who are learning Android programming.

83
Exp7: Develop a native application that uses GPS location information.

Create Android Application

Step Description

1 You will use Android studio IDE to create an Android application and name it
as Tutorialspoint under a package com.example.tutorialspoint7.myapplication.

2 add src/GPSTracker.java file and add required code.

3 Modify src/MainActivity.java file and add required code as shown below to take care
of getting current location and its equivalent address.

4 Modify layout XML file res/layout/activity_main.xml to add all GUI components


which include three buttons and two text views to show location/address.

5 Modify res/values/strings.xml to define required constant values

6 Modify AndroidManifest.xml as shown below

7 Run the application to launch Android emulator and verify the result of the changes
done in the application.

Following is the content of the modified main activity file MainActivity.java.

package com.example.tutorialspoint7.myapplication;

84
import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.test.mock.MockPackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button btnShowLocation;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

// GPSTracker class
GPSTracker gps;

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

try {
if (ActivityCompat.checkSelfPermission(this, mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this, new String[]{mPermission},


REQUEST_CODE_PERMISSION);

85
// If any permission above not allowed by user, this condition will
execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}

btnShowLocation = (Button) findViewById(R.id.button);

// show location button click event


btnShowLocation.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);

// check if GPS enabled


if(gps.canGetLocation()){

double latitude = gps.getLatitude();


double longitude = gps.getLongitude();

// \n is for new line


Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "
+ latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();

86
}

}
});
}
}

Following is the content of the modified main activity file GPSTracker.java.

package com.example.tutorialspoint7.myapplication;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

87
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status


boolean isGPSEnabled = false;

// flag for network status


boolean isNetworkEnabled = false;

// flag for GPS status


boolean canGetLocation = false;

Location location; // location


double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds


private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager


protected LocationManager locationManager;

public GPSTracker(Context context) {

88
this.mContext = context;
getLocation();
}

public Location getLocation() {


try {
locationManager = (LocationManager)
mContext.getSystemService(LOCATION_SERVICE);

// getting GPS status


isGPSEnabled =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// getting network status


isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {


// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager

89
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}

// if GPS Enabled get lat/long using GPS Services


if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("GPS Enabled", "GPS Enabled");


if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

90
} catch (Exception e) {
e.printStackTrace();
}

return location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */

public void stopUsingGPS(){


if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}

/**
* Function to get latitude
* */

public double getLatitude(){


if(location != null){
latitude = location.getLatitude();
}

// return latitude
return latitude;
}

91
/**
* Function to get longitude
* */

public double getLongitude(){


if(location != null){
longitude = location.getLongitude();
}

// return longitude
return longitude;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */

public boolean canGetLocation() {


return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */

public void showSettingsAlert(){


AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title

92
alertDialog.setTitle("GPS is settings");

// Setting Dialog Message


alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

// On pressing Settings button


alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

// on pressing cancel button


alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

// Showing Alert Message


alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

93
@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}
}

Following will be the content of res/layout/activity_main.xml file −

<?xml version = "1.0" encoding = "utf-8"?>


<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:orientation = "vertical" >

<Button
android:id = "@+id/button"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "getlocation"/>

</LinearLayout>

Following will be the content of res/values/strings.xml to define two new constants −

94
<?xml version = "1.0" encoding = "utf-8"?>
<resources>
<string name = "app_name">Tutorialspoint</string>
</resources>

Following is the default content of AndroidManifest.xml −

<?xml version = "1.0" encoding = "utf-8"?>


<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.tutorialspoint7.myapplication">
<uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name = "android.permission.INTERNET" />
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">

<activity android:name = ".MainActivity">


<intent-filter>
<action android:name = "android.intent.action.MAIN" />

<category android:name = "android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

Let's try to run your Tutorialspoint application. I assume that, you have connected your actual
Android Mobile device with your computer. To run the app from Android Studio, open one of
your project's activity files and click Run icon from the toolbar. Before starting your

95
application, Android studio installer will display following window to select an option where you
want to run your Android application.

Now to see location select Get Location Button which will display location information as
follows −

96
97
Exp 8: To develop a Android Application that writes data to the SD Card.

Procedure:

Creating a New project:

Open Android Studio and then click on File -> New -> New project.

Then type the Application name as “ex.no.9″ and click Next.

Then select the Minimum SDK as shown below and click Next.

98
Then select the Empty Activity and click Next.

Finally click Finish.

99
▪ It will take some time to build and load the project.
▪ After completion it will look as given below.

Designing layout for the Android Application:

Click on app -> res -> layout -> activity_main.xml.

100
Now click on Text as shown below.

Then delete the code which is there and type the code as given below.
Code for Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical">

<EditText

101
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="30dp" />

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Write Data"
android:textSize="30dp" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Read data"
android:textSize="30dp" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Clear"
android:textSize="30dp" />

</LinearLayout>

102
Now click on Design and your application will look as given below.

So now the designing part is completed.


Adding permissions in Manifest for the Android Application:

Click on app -> manifests -> AndroidManifest.xml

Now include the WRITE_EXTERNAL_STORAGE permissions in the AndroidManifest.xml


file as shown below

103
Code for AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exno9" >

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>

104
</application>
</manifest>
So now the Permissions are added in the Manifest.
Java Coding for the Android Application:

Click on app -> java -> com.example.exno9 -> MainActivity.

Then delete the code which is there and type the code as given below.
Code for MainActivity.java:
package com.example.exno9;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

105
public class MainActivity extends AppCompatActivity
{
EditText e1;
Button write,read,clear;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

e1= (EditText) findViewById(R.id.editText);


write= (Button) findViewById(R.id.button);
read= (Button) findViewById(R.id.button2);
clear= (Button) findViewById(R.id.button3);

write.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String message=e1.getText().toString();
try
{
File f=new File("/sdcard/myfile.txt");
f.createNewFile();
FileOutputStream fout=new FileOutputStream(f);
fout.write(message.getBytes());
fout.close();
Toast.makeText(getBaseContext(),"Data Written in
SDCARD",Toast.LENGTH_LONG).show();

106
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});

read.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String message;
String buf = "";
try
{
File f = new File("/sdcard/myfile.txt");
FileInputStream fin = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
while ((message = br.readLine()) != null)
{
buf += message;
}
e1.setText(buf);
br.close();
fin.close();
Toast.makeText(getBaseContext(),"Data Recived from
SDCARD",Toast.LENGTH_LONG).show();
}
catch (Exception e)

107
{
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});

clear.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
e1.setText("");
}
});
}
}
▪ So now the Coding part is also completed.
▪ Now run the application to see the output.

Output:

108
Result:

Thus Android Application that writes data to the SD Card is developed and executed successfully.

Exp 9: Design a gaming application.

109
Creating a New Project

1. Open Android Studio and create a new project.


2. Once the project is loaded you will get MainActivity.java and activity_main.xml
3. First paste all the images that you downloaded inside the drawable folder of your project.

Designing the Start Screen

Above you can see the first screen of the game. It has a nice background image with
two ImageButtons. You already downloaded the images used in this screen.

As you can see it is a full screen activity. So to make your application full screen, you need to
go res->values->styles.xml and modify it as the following code.

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>

110
</style>

</resources>

Inside activity_main.xml write the following xml code.

<?xml version="1.0" encoding="utf-8"?>


<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/splash"
tools:context="net.simplifiedcoding.simplegame.MainActivity">

<ImageButton
android:id="@+id/buttonPlay"
android:background="@drawable/playnow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/buttonScore"
android:layout_centerHorizontal="true" />

<ImageButton
android:id="@+id/buttonScore"
android:background="@drawable/highscore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

111
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />

</RelativeLayout>

• When we tap the Play Now button our Game Activity will start.
• Now come inside MainActivity.java and write the following code.

package net.simplifiedcoding.simplegame;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

//image button
private ImageButton buttonPlay;

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

//setting the orientation to landscape


setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

112
//getting the button
buttonPlay = (ImageButton) findViewById(R.id.buttonPlay);

//adding a click listener


buttonPlay.setOnClickListener(this);
}

@Override
public void onClick(View v) {

//starting game activity


startActivity(new Intent(this, GameActivity.class));
}
}

Now you need to create a new activity named GameActivity. To create a new activity right click
on the package name -> new -> activity -> empty activity

Building Game View

Now its time to build our Game View. We will be using SurfaceView for building our game view.
Surfaceview provides a dedicated drawing surface.

Create a new class named GameView and write the following code.

public class GameView extends SurfaceView implements Runnable {


volatile boolean playing;
private Thread gameThread = null;

public GameView(Context context) {


super(context);

113
}

@Override
public void run() {
while (playing) {
update();
draw();
control();
}
}
private void update() {
}
private void draw() {
}
private void control() {
try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void pause() {


playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
}
}

public void resume() {

114
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
}

• The above class is our GameView class. It is the actual game panel where we will play the
game. The class is implementing Runnable interface. We have a volatile boolean type
variable running that will track whether the game is running or not. After that we have
our gameThread, it is the main game loop. Then we have the constructor to the class. We are
not doing anything inside the constructor right now. Then we have the overriden
method run(), here we are running a loop until the playing variable running is true. Inside the
loop we are calling the following methods.
update() -> Here we will update the coordinate of our characters.
draw() -> Here we will draw the characters to the canvas.
control() -> This method will control the frames per seconds drawn. Here we are calling the
delay method of Thread. And this is actually making our frame rate to aroud 60fps.
After these we have two more methods.
pause() -> To pause the game, we are stopping the gameThread here.
resume() -> To resume the game, here we are starting the gameThread.

Adding GameView to GameActivity

After tapping the play now button we are launching the GameActivity. We will set our GameView
to the content of this activity. So go to GameActivity.java and modify the code as below.

I will be adding the comments only above the new code added so that you can understand what is
new in this code so that you can modify your code easily.

115
GameActivity.java

package net.simplifiedcoding.spacefighter;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class GameActivity extends AppCompatActivity {


private GameView gameView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new GameView(this);
setContentView(gameView);
}

@Override
protected void onPause() {
super.onPause();
gameView.pause();
}
@Override
protected void onResume() {
super.onResume();
gameView.resume();
}
}

116
Creating Player

Create a new class Player inside your package and write the following code.

package net.simplifiedcoding.spacefighter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Player {


//Bitmap to get character from image
private Bitmap bitmap;

//coordinates
private int x;
private int y;

//motion speed of the character


private int speed = 0;

//constructor
public Player(Context context) {
x = 75;
y = 50;
speed = 1;
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.player);
}
public void update(){
x++;
}

117
public Bitmap getBitmap() {
return bitmap;
}

public int getX() {


return x;
}

public int getY() {


return y;
}

public int getSpeed() {


return speed;
}
}

The above code is very easy to understand. I have written comments to explain everything. So let’s
move ahead.

Drawing Player to GameView

To draw the player to our GameView you need to come back to the GameView.java class and
modify it as below.

public class GameView extends SurfaceView implements Runnable {

volatile boolean playing;


private Thread gameThread = null;
private Player player;
private Paint paint;
private Canvas canvas;

118
private SurfaceHolder surfaceHolder;

public GameView(Context context) {


super(context);
player = new Player(context);
surfaceHolder = getHolder();
paint = new Paint();
}

@Override
public void run() {
while (playing) {
update();
draw();
control();
}
}

private void update() {


player.update();
}

private void draw() {


if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(
player.getBitmap(),
player.getX(),
player.getY(),
paint);

119
surfaceHolder.unlockCanvasAndPost(canvas);
}
}

private void control() {


try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void pause() {


playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
}
}

public void resume() {


playing = true;
gameThread = new Thread(this);
gameThread.start();
}
}

Now try executing your application. Put your emulator in landscape mode. When you tap the play
now button in the first activity you will see the moving Space Jet as shown below.

120
Android Game Development Tutorial

If you are getting the output as shown in the above image then Hurray!. You might have got the
concept about drawing images in canvas using SurfaceView. And the movement is the magic of
the coordinates. We are changing the x coordinate so it is moving horizontally ahead.

Now let’s add control to our Space Jet.

121
Adding Controls

We will now add control to the player’s Space Jet. When the player will tap on the screen the
Space Jet will boost up and after releasing the screen the Space Jet will boost down. The movement
is inspired by the most popular game Flappy Bird.

To add this control we will need to detect touches of the screen. So lets begin.

• Come inside GameView.java file and override the method onTouchEvent().

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_DOWN:
break;
}
return true;
}

Currently we need these two events only which are ACTION_UP and ACTION_DOWN. What
we need to do is we need to boost up the Space Jet on ACTION_UP and boost down the Space
Jet on ACTION_DOWN.

Adding Booster to Space Jet

Now we will add the booster to our Space Jet so that our player can control the Space Jet. Follow
these steps to do this.

Modify the code of Player.java file as follows.

public class Player {

122
private Bitmap bitmap;
private int x;
private int y;
private int speed = 0;
private boolean boosting;
private final int GRAVITY = -10;
private int maxY;
private int minY;

private final int MIN_SPEED = 1;


private final int MAX_SPEED = 20;

public Player(Context context) {


x = 75;
y = 50;
speed = 1;
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.player);
boosting = false;
}
public void setBoosting() {
boosting = true;
}
public void stopBoosting() {
boosting = false;
}

public void update() {


if (boosting) {
speed += 2;
} else {
speed -= 5;

123
}
if (speed > MAX_SPEED) {
speed = MAX_SPEED;
}
if (speed < MIN_SPEED) {
speed = MIN_SPEED;
}
y -= speed + GRAVITY;
if (y < minY) {
y = minY;
}
if (y > maxY) {
y = maxY;
}
}

public Bitmap getBitmap() {


return bitmap;
}

public int getX() {


return x;
}

public int getY() {


return y;
}

public int getSpeed() {


return speed;
}

124
}

We also need to detect the size of screen so go inside GameActivity.java file and add the
following code inside onCreate().

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);

gameView = new GameView(this, size.x, size.y);


setContentView(gameView);
}

In the above code we are passing screen size to GameView constructor, so we also need to change
the GameView constructor. So change the GameView constructor as follow.

public GameView(Context context, int screenX, int screenY) {


super(context);
player = new Player(context, screenX, screenY);

surfaceHolder = getHolder();
paint = new Paint();
}

In the above code you can see we are passing the screen size to player constructor. So again we
also need to modify the Player class constructor.

public Player(Context context, int screenX, int screenY) {


x = 75;

125
y = 50;
speed = 1;
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.player);
maxY = screenY - bitmap.getHeight();
minY = 0;
boosting = false;
}

Now to complete adding the boosters come inside GameView.java file and modify
the onTouchEvent() as follows.

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
player.stopBoosting();
break;
case MotionEvent.ACTION_DOWN:
player.setBoosting();
break;
}
return true;
}

Now execute your application again to test the boosters. If it is working fine then you can move
ahead.

Adding Background Stars

Now we will add background stars to make the background looks animating.

Star.java

126
package net.simplifiedcoding.spacefighter;

import java.util.Random;

public class Star {


private int x;
private int y;
private int speed;

private int maxX;


private int maxY;
private int minX;
private int minY;
public Star(int screenX, int screenY) {
maxX = screenX;
maxY = screenY;
minX = 0;
minY = 0;
Random generator = new Random();
speed = generator.nextInt(10);

//generating a random coordinate


//but keeping the coordinate inside the screen size
x = generator.nextInt(maxX);
y = generator.nextInt(maxY);
}

public void update(int playerSpeed) {


x -= playerSpeed;
x -= speed;
if (x < 0) {

127
x = maxX;
Random generator = new Random();
y = generator.nextInt(maxY);
speed = generator.nextInt(15);
}
}

public float getStarWidth() {

float minX = 1.0f;


float maxX = 4.0f;
Random rand = new Random();
float finalX = rand.nextFloat() * (maxX - minX) + minX;
return finalX;
}

public int getX() {


return x;
}

public int getY() {


return y;
}
}

• Now come inside GameView.java and modify it as follows.

public class GameView extends SurfaceView implements Runnable {

volatile boolean playing;


private Thread gameThread = null;

128
private Player player;
private Paint paint;
private Canvas canvas;
private SurfaceHolder surfaceHolder;
private ArrayList<Star> stars = new
ArrayList<Star>();

public GameView(Context context, int screenX, int screenY) {


super(context);
player = new Player(context, screenX, screenY);

surfaceHolder = getHolder();
paint = new Paint();
int starNums = 100;
for (int i = 0; i < starNums; i++) {
Star s = new Star(screenX, screenY);
stars.add(s);
}
}

@Override
public void run() {
while (playing) {
update();
draw();
control();
}
}

private void update() {


player.update();

129
//Updating the stars with player speed
for (Star s : stars) {
s.update(player.getSpeed());
}
}

private void draw() {


if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
paint.setColor(Color.WHITE);
for (Star s : stars) {
paint.setStrokeWidth(s.getStarWidth());
canvas.drawPoint(s.getX(), s.getY(), paint);
}

canvas.drawBitmap(
player.getBitmap(),
player.getX(),
player.getY(),
paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}

private void control() {


try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();

130
}
}

public void pause() {


playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
}
}

public void resume() {


playing = true;
gameThread = new Thread(this);
gameThread.start();
}

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
player.stopBoosting();
break;
case MotionEvent.ACTION_DOWN:
player.setBoosting();
break;
}
return true;
}
}

131
Now execute your app again. You will see a infinite scrolling background this time as shown in
the following image.

Android Game Development Tutorial

Adding Enemies

So far in this Android Game Development Tutorial, we have added our player, we added an
infinite scrolling background. We also added controls to our player. Now we need to add some
enemies. So lets start coding the enemies.

Create a new java class named Enemy and write the following code.

Enemy.java
package net.simplifiedcoding.spacefighter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;

132
import java.util.Random;

public class Enemy {


private Bitmap bitmap;
private int x;
private int y;
private int speed = 1;
private int maxX;
private int minX;
private int maxY;
private int minY;

public Enemy(Context context, int screenX, int screenY) {


bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.enemy);
maxX = screenX;
maxY = screenY;
minX = 0;
minY = 0;
Random generator = new Random();
speed = generator.nextInt(6) + 10;
x = screenX;
y = generator.nextInt(maxY) - bitmap.getHeight();

public void update(int playerSpeed) {


x -= playerSpeed;
x -= speed;
if (x < minX - bitmap.getWidth()) {
Random generator = new Random();

133
speed = generator.nextInt(10) + 10;
x = maxX;
y = generator.nextInt(maxY) - bitmap.getHeight();
}
}
public Bitmap getBitmap() {
return bitmap;
}

public int getX() {


return x;
}

public int getY() {


return y;
}

public int getSpeed() {


return speed;
}

We need to add the enemies in the GameView now. So come inside GameView.java and modify
the code as follows.

public class GameView extends SurfaceView implements Runnable {

volatile boolean playing;


private Thread gameThread = null;
private Player player;

134
private Paint paint;
private Canvas canvas;
private SurfaceHolder surfaceHolder;
private Enemy[] enemies;
private int enemyCount = 3;

private ArrayList<Star> stars = new


ArrayList<Star>();

public GameView(Context context, int screenX, int screenY) {


super(context);
player = new Player(context, screenX, screenY);

surfaceHolder = getHolder();
paint = new Paint();

int starNums = 100;


for (int i = 0; i < starNums; i++) {
Star s = new Star(screenX, screenY);
stars.add(s);
}
enemies = new Enemy[enemyCount];
for(int i=0; i<enemyCount; i++){
enemies[i] = new Enemy(context, screenX, screenY);
}
}

@Override
public void run() {
while (playing) {

135
update();
draw();
control();
}
}

private void update() {


player.update();
for (Star s : stars) {
s.update(player.getSpeed());
}
for(int i=0; i<enemyCount; i++){
enemies[i].update(player.getSpeed());
}
}

private void draw() {


if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);

paint.setColor(Color.WHITE);

for (Star s : stars) {


paint.setStrokeWidth(s.getStarWidth());
canvas.drawPoint(s.getX(), s.getY(), paint);
}

canvas.drawBitmap(
player.getBitmap(),
player.getX(),

136
player.getY(),
paint);

//drawing the enemies


for (int i = 0; i < enemyCount; i++) {
canvas.drawBitmap(
enemies[i].getBitmap(),
enemies[i].getX(),
enemies[i].getY(),
paint
);
}

surfaceHolder.unlockCanvasAndPost(canvas);

}
}

private void control() {


try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void pause() {


playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {

137
}
}

public void resume() {


playing = true;
gameThread = new Thread(this);
gameThread.start();
}

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
player.stopBoosting();
break;
case MotionEvent.ACTION_DOWN:
player.setBoosting();
break;
}
return true;
}
}

• Execute your application again and you should see the following output.

138
Android Game Development Tutorial

So we are almost done at this part of the Android Game Development Tutorial. Only the last
thing is left. When our Space Jet touches the enemy, the enemy ship should blast. So we need a
blast image and you already got it inside your drawable folder. To show the blast image we need
to detect the collision between the player and enemy jet. So lets do this.

Detecting Collision

To detect collision we will use Rect object. So come inside Enemy class modify the code as
follows.

public class Enemy {


private Bitmap bitmap;
private int x;
private int y;
private int speed = 1;

private int maxX;


private int minX;

139
private int maxY;
private int minY;
private Rect detectCollision;

public Enemy(Context context, int screenX, int screenY) {


bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.enemy);
maxX = screenX;
maxY = screenY;
minX = 0;
minY = 0;
Random generator = new Random();
speed = generator.nextInt(6) + 10;
x = screenX;
y = generator.nextInt(maxY) - bitmap.getHeight();
detectCollision = new Rect(x, y, bitmap.getWidth(), bitmap.getHeight());
}

public void update(int playerSpeed) {


x -= playerSpeed;
x -= speed;
if (x < minX - bitmap.getWidth()) {
Random generator = new Random();
speed = generator.nextInt(10) + 10;
x = maxX;
y = generator.nextInt(maxY) - bitmap.getHeight();
}
detectCollision.left = x;
detectCollision.top = y;
detectCollision.right = x + bitmap.getWidth();
detectCollision.bottom = y + bitmap.getHeight();

140
}
public void setX(int x){
this.x = x;
}
public Rect getDetectCollision() {
return detectCollision;
}
public Bitmap getBitmap() {
return bitmap;
}

public int getX() {


return x;
}

public int getY() {


return y;
}

public int getSpeed() {


return speed;
}

• The same thing you need to do inside the Player.java file.

public class Player {


private Bitmap bitmap;
private int x;
private int y;

141
private int speed = 0;
private boolean boosting;
private final int GRAVITY = -10;
private int maxY;
private int minY;

private final int MIN_SPEED = 1;


private final int MAX_SPEED = 20;

private Rect detectCollision;

public Player(Context context, int screenX, int screenY) {


x = 75;
y = 50;
speed = 1;
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.player);
maxY = screenY - bitmap.getHeight();
minY = 0;
boosting = false;
detectCollision = new Rect(x, y, bitmap.getWidth(), bitmap.getHeight());
}

public void setBoosting() {


boosting = true;
}

public void stopBoosting() {


boosting = false;
}

public void update() {

142
if (boosting) {
speed += 2;
} else {
speed -= 5;
}

if (speed > MAX_SPEED) {


speed = MAX_SPEED;
}

if (speed < MIN_SPEED) {


speed = MIN_SPEED;
}

y -= speed + GRAVITY;

if (y < minY) {
y = minY;
}
if (y > maxY) {
y = maxY;
}
detectCollision.left = x;
detectCollision.top = y;
detectCollision.right = x + bitmap.getWidth();
detectCollision.bottom = y + bitmap.getHeight();

}
public Rect getDetectCollision() {
return detectCollision;
}

143
public Bitmap getBitmap() {
return bitmap;
}

public int getX() {


return x;
}

public int getY() {


return y;
}

public int getSpeed() {


return speed;
}
}

Now to complete the collision detection, again to inside GameView.java file and modify
the update() method as follows.

private void update() {


player.update();
for (Star s : stars) {
s.update(player.getSpeed());
}

for(int i=0; i<enemyCount; i++){


enemies[i].update(player.getSpeed());
if (Rect.intersects(player.getDetectCollision(), enemies[i].getDetectCollision())) {

144
enemies[i].setX(-200);
}
}
}

Again execute the app. You should see the enemies getting hidden after collision. Now after
collision we will show a blast image for a fraction of second to make it look like destroying.

Adding Blast Effect

Now we are at the last phase for this part of this Android Game Development Tutorial. We need
to display a blast effect after collision.

We already have a blast image inside the drawable folder. We will use that image to display for a
fraction of second after the collision. So follow the following step.

Create a new java class named Boom and write the following code.

Boom.java
package net.simplifiedcoding.spacefighter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Boom {


private Bitmap bitmap;
private int x;
private int y;
public Boom(Context context) {
bitmap = BitmapFactory.decodeResource
(context.getResources(), R.drawable.boom);

145
x = -250;
y = -250;
}
public void setX(int x) {
this.x = x;
}

public void setY(int y) {


this.y = y;
}
public Bitmap getBitmap() {
return bitmap;
}

public void setBitmap(Bitmap bitmap) {


this.bitmap = bitmap;
}

public int getX() {


return x;
}

public int getY() {


return y;
}

146
Now again come inside GameView.java file and modify the code as follow.

public class GameView extends SurfaceView implements Runnable {

volatile boolean playing;


private Thread gameThread = null;
private Player player;

private Paint paint;


private Canvas canvas;
private SurfaceHolder surfaceHolder;

private Enemy[] enemies;

private int enemyCount = 3;

private ArrayList<Star> stars = new


ArrayList<Star>();
private Boom boom;

public GameView(Context context, int screenX, int screenY) {


super(context);
player = new Player(context, screenX, screenY);

surfaceHolder = getHolder();
paint = new Paint();

int starNums = 100;


for (int i = 0; i < starNums; i++) {
Star s = new Star(screenX, screenY);
stars.add(s);

147
}

enemies = new Enemy[enemyCount];


for (int i = 0; i < enemyCount; i++) {
enemies[i] = new Enemy(context, screenX, screenY);
}
boom = new Boom(context);
}

@Override
public void run() {
while (playing) {
update();
draw();
control();
}
}

private void update() {


player.update();
boom.setX(-250);
boom.setY(-250);

for (Star s : stars) {


s.update(player.getSpeed());
}

for (int i = 0; i < enemyCount; i++) {


enemies[i].update(player.getSpeed());
if (Rect.intersects(player.getDetectCollision(), enemies[i].getDetectCollision())) {
boom.setX(enemies[i].getX());

148
boom.setY(enemies[i].getY());

enemies[i].setX(-200);

}
}
}

private void draw() {


if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);

paint.setColor(Color.WHITE);

for (Star s : stars) {


paint.setStrokeWidth(s.getStarWidth());
canvas.drawPoint(s.getX(), s.getY(), paint);
}

canvas.drawBitmap(
player.getBitmap(),
player.getX(),
player.getY(),
paint);

for (int i = 0; i < enemyCount; i++) {


canvas.drawBitmap(
enemies[i].getBitmap(),
enemies[i].getX(),
enemies[i].getY(),

149
paint
);
}
canvas.drawBitmap(
boom.getBitmap(),
boom.getX(),
boom.getY(),
paint
);

surfaceHolder.unlockCanvasAndPost(canvas);

}
}

private void control() {


try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void pause() {


playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
}
}

150
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
player.stopBoosting();
break;
case MotionEvent.ACTION_DOWN:
player.setBoosting();
break;
}
return true;
}
}

Now again execute the application and you will see a blast effect on collision.

151
Exp 10: Create an application to handle images and videos according to size.

Create a basic Android project with an Activity that sets the main view from a layout file and does
nothing else. Then open the layout file and add the ImageView and a button as shown below:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingLeft="16dp"

android:paddingRight="16dp"

android:orientation="vertical">

<ImageView

android:id="@+id/imageDisplay"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<Button

android:id="@+id/btnRotateImage"

152
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Next Image" />

</LinearLayout>

In the code above we created a LinearLayout and added an ImageView to display an image and a
button which will rotate the images in the imageView.

Add some images to the resource folder depending on the screen sizes you are planning to support
as shown below:

Now update your Activity code as follows, using appropriate names for your project:

public class ImageChangingActivity extends Activity {

private Integer images[] = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3};

153
private int currImage = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_image_changing);

setInitialImage();

setImageRotateListener();

private void setImageRotateListener() {

final Button rotatebutton = (Button) findViewById(R.id.btnRotateImage);

rotatebutton.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View arg0) {

currImage++;

154
if (currImage == 3) {

currImage = 0;

setCurrentImage();

});

private void setInitialImage() {

setCurrentImage();

private void setCurrentImage() {

final ImageView imageView = (ImageView) findViewById(R.id.imageDisplay);

imageView.setImageResource(images[currImage]);

155
Above we created an Array of the resource IDs for the images stored in our resources folder. In
the OnCreate method we set the content view to the layout created. In
the setImageRotateListener function we set up a listener to the onClick event of the button which
changes the currentImage counter and sets the new image in the ImageView.

The setCurrentImage function gets the ImageView object using the findViewById function, then
sets the resource id of the current image using the setImageResource function on
the ImageView which will display the image in the image view.

If you run the program you should see the image in the image view and clicking it should change
the image to the next one:

Using the Image Switcher View in Android.

156
In the above example we switched the image in the image view. This switching of images does
not happen in a very smooth way and you might want to use a transition when the image changes.
For this we use the ImageSwitcher View.

First add an image switcher view to the layout as follows:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingLeft="16dp"

android:paddingRight="16dp"

android:orientation="vertical">

<ImageSwitcher

android:id="@+id/imageSwitcher"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<Button

android:id="@+id/btnRotateImage"

157
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Next Image" />

</LinearLayout>

Then add the following code to our Activity which will initialise the ImageSwitcher and setup
the button to change the image with a transition.

public class ImageSwitcherExampleActivity extends Activity {

private Integer images[] = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3};

private int currImage = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_image_switcher_example);

initializeImageSwitcher();

setInitialImage();

setImageRotateListener();

158
}

private void initializeImageSwitcher() {

final ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);

imageSwitcher.setFactory(new ViewFactory() {

@Override

public View makeView() {

ImageView imageView = new ImageView(ImageSwitcherExampleActivity.this);

return imageView;

});

imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.slide_in_left));

imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.slide_out_right));

159
private void setImageRotateListener() {

final Button rotatebutton = (Button) findViewById(R.id.btnRotateImage);

rotatebutton.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View arg0) {

currImage++;

if (currImage == 3) {

currImage = 0;

setCurrentImage();

});

private void setInitialImage() {

setCurrentImage();

160
}

private void setCurrentImage() {

final ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);

imageSwitcher.setImageResource(images[currImage]);

In the code above we get the ImageSwitcher object and then set the ViewFactory which creates a
plain ImageView. Then we set the animation to fade in and fade out. We update
the setCurrentImage function to set the images in the ImageSwitcher.

Now the image will change with an animation.

161
.

You should not undertake any network operations in the UI thread, instead the download should
happen in a different background thread. We will do this in an Async Task. First set the permission
to use the Internet in our AndroidManifest.xml as follows:

<uses-permission android:name="android.permission.INTERNET" />

The layout of your project should have one ImageView and a Button as shown:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingLeft="16dp"

162
android:paddingRight="16dp"

android:orientation="vertical">

<ImageView

android:id="@+id/imageDisplay"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<Button

android:id="@+id/btnRotateImage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Next Image" />

</LinearLayout>

Then we create an AsyncTask which takes the ImageView and URL to download, downloads the
image and sets the image in the ImageView.

163
The ImageDownloader async task downloads the image data and sets the ImageView. The
complete activity code should now be as follows:

public class ImagedownloaderActivity extends Activity {

private String imageUrls[] = {"http://www.abc.com/image1.jpg",

"http://www.abc.com/image2.jpg",

"http://www.abc.com/image3.jpg"

};

private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {

ImageView bmImage;

public ImageDownloader(ImageView bmImage) {

this.bmImage = bmImage;

protected Bitmap doInBackground(String... urls) {

String url = urls[0];

Bitmap bitmap = null;

164
try {

InputStream in = new java.net.URL(url).openStream();

bitmap = BitmapFactory.decodeStream(in);

} catch (Exception e) {

Log.e("MyApp", e.getMessage());

return bitmap;

protected void onPostExecute(Bitmap result) {

bmImage.setImageBitmap(result);

private int currImage = 0;

@Override

165
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_imagedownloader);

setInitialImage();

setImageRotateListener();

private void setImageRotateListener() {

final Button rotatebutton = (Button) findViewById(R.id.btnRotateImage);

rotatebutton.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View arg0) {

currImage++;

if (currImage == 3) {

currImage = 0;

166
}

setCurrentImage();

});

private void setInitialImage() {

setCurrentImage();

private void setCurrentImage() {

final ImageView imageView = (ImageView) findViewById(R.id.imageDisplay);

ImageDownloader imageDownLoader = new ImageDownloader(imageView);

imageDownLoader.execute(imageUrls[currImage]);

In the above code we stored the URLs of the images in the imageUrls array. In
the setCurrentImage function we pass the ImageView to the ImageDownloader Async task and

167
pass the URL of the image to download and set in the ImageView. The ImageDownloader Async
task will download the image and set it in the ImageView.

Implementing a Gallery Using the Horizontal Scroll View.

In the above examples we saw how to display one image at a time using an ImageView. Sometimes
we might want to display a variable number of images and let the user scroll through them. This
we can achieve by putting a LinearLayout inside a horizontal scrollView and then dynamically
add ImageViews to that linear layout. For this we create a new activity
called ImageGalleryActivity and update the layout file accordingly:

<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:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context="com.example.imagegallery.ImageGalleryActivity">

<HorizontalScrollView

android:layout_width="match_parent"

168
android:layout_height="wrap_content">

<LinearLayout

android:id="@+id/imageGallery"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:orientation="horizontal" />

</HorizontalScrollView>

</RelativeLayout>

And code of the Activity:

public class ImageGalleryActivity extends Activity {

private Integer images[] = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_image_gallery);

169
addImagesToThegallery();

private void addImagesToThegallery() {

LinearLayout imageGallery = (LinearLayout) findViewById(R.id.imageGallery);

for (Integer image : images) {

imageGallery.addView(getImageView(image));

private View getImageView(Integer image) {

ImageView imageView = new ImageView(getApplicationContext());

LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

lp.setMargins(0, 0, 10, 0);

imageView.setLayoutParams(lp);

imageView.setImageResource(image);

170
return imageView;

In the code above we dynamically create the ImageViews and add margins to them.
The LinerLayout has the orientation set to horizontal. Now if we run the program, we will be able
to see the images in a Horizontally scrollable gallery as seen below.

Conclusion

Images are a big part of modern mobile interfaces and hopefully this tutorial has shown you some
of the tools Android provides to make this easy.

171

You might also like