Mobile Application Development Lab Manual
Mobile Application Development Lab Manual
Website: www.sbss.ac.in
i
S.NO. Title Page no.
10. Create an application to handle images and videos according to size. 171
ii
Exp 1: Create a Hello World 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.
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
Following section will give a brief overview of the important application files.
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;
@Override
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.
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 −
<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>
</intent-filter>
</activity>
</application>
</manifest>
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 −
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="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
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>
10
@string/hello_world refers to the hello string defined in the strings.xml file, which is "Hello
World!".
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"
<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.
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){
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.
4. Run the application and choose a running android device and install the application on it and
verify the results
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;
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
@Override
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
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
finish();
});
17
<?xml version = "1.0" encoding = "utf-8"?>
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
android:layout_height = "wrap_content"
android:id = "@+id/textview"
android:textSize = "35dp"
android:layout_alignParentTop = "true"
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/textView"
18
android:layout_below = "@+id/textview"
android:layout_centerHorizontal = "true"
android:textColor = "#ff7aff24"
<EditText
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/editText"
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"
<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>
</resources>
<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>
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.
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.
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.
<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>
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>
iii of Step 3 – Further in continuation with previous linearlayout add a textview, textfield(Number)
for displaying result which makes the interface complete.
<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>
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))
txtresult.setText(Double.toString(result));
else{
toast.show();
});
//Subtraction
btnsub.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(View v){
42
if((opr1.getText().length()>0)&&(opr2.getText().length()>0))
txtresult.setText(Double.toString(result));
else{
toast.show();
});
// Multiplication
btnmul.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(View v){
if((opr1.getText().length()>0)&&(opr2.getText().length()>0))
43
double result = oper1 * oper2;
txtresult.setText(Double.toString(result));
else{
toast.show();
});
// Division
btndiv.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(View v){
if((opr1.getText().length()>0)&&(opr2.getText().length()>0))
txtresult.setText(Double.toString(result));
else{
});
// 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:
Open Android Studio and then click on File -> New -> New project.
Then select the Minimum SDK as shown below and click Next.
47
Then select the Empty Activity and click Next.
48
▪ It will take some time to build and load the project.
▪ After completion it will look as given below.
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.
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" />
52
</manifest>
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;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
new MyAsyncTask().execute();
}
54
XmlPullParser xpp = factory.newPullParser();
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);
}
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:
Open Android Studio and then click on File -> New -> New project.
Then select the Minimum SDK as shown below and click Next.
59
Then select the Empty Activity and click Next.
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:
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.
63
Java Coding for the Android Application:
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;
64
setContentView(R.layout.activity_main);
//Creating a Bitmap
Bitmap bg = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);
//Creating the Paint Object and set its color & TextSize
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(50);
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:
69
}
public int getID() {
return this.studentID;
}
public void setStudentName(String studentname) {
this.studentName = studentname;
}
public String getStudentName() {
return this.studentName;
}
}
Steps for creating the MyDBHandler class like the Student class and its code can look like this:
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) {}
}
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
The database can be initialized in the constructor of the MyDBHandler class. The code of this
constructor looks like this:
71
SQLiteDatabase.CursorFactoryfactory, intversion) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
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:
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
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:
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:
73
db.close();
}
To find information in the database by condition, we must use the SQL query statement as follows:
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:
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:
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:
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
76
The code for the click event of the buttons and results is as follows:
<Button
android:id="@+id/btnload"
android:onClick="loadStudents"
android:text="@string/Load"
......
/>
77
Code for the ADD button:
<Button
android:id="@+id/btnadd"
android:onClick="addStudent"
android:text="@string/Add"
78
.... />
<Button
android:id="@+id/btnfind"
android:onClick="findStudent"
android:text="@string/Find"..../>
79
Code for the DELETE button:
<Button
android:id="@+id/btndelete"
80
android:onClick="removeStudent"
android:text="@string/Delete"
........ />
81
studentid.setText("No Match Found");
}
<Button
android:id="@+id/btnupdate"
android:onClick="updateStudent"
android:text="@string/Update"
.... />
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.
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.
3 Modify src/MainActivity.java file and add required code as shown below to take care
of getting current location and its equivalent address.
7 Run the application to launch Android emulator and verify the result of the changes
done in the application.
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;
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) {
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();
}
@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);
86
}
}
});
}
}
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;
88
this.mContext = context;
getLocation();
}
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
89
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
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
* */
/**
* Function to get latitude
* */
// return latitude
return latitude;
}
91
/**
* Function to get longitude
* */
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
92
alertDialog.setTitle("GPS is settings");
@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;
}
}
<Button
android:id = "@+id/button"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "getlocation"/>
</LinearLayout>
94
<?xml version = "1.0" encoding = "utf-8"?>
<resources>
<string name = "app_name">Tutorialspoint</string>
</resources>
</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:
Open Android Studio and then click on File -> New -> New project.
Then select the Minimum SDK as shown below and click Next.
98
Then select the Empty Activity and click Next.
99
▪ It will take some time to build and load the project.
▪ After completion it will look as given below.
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.
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" />
104
</application>
</manifest>
So now the Permissions are added in the Manifest.
Java Coding for the Android Application:
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);
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.
109
Creating a New Project
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>
<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;
//image button
private ImageButton buttonPlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
112
//getting the button
buttonPlay = (ImageButton) findViewById(R.id.buttonPlay);
@Override
public void onClick(View v) {
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
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.
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();
}
}
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.
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;
@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;
//coordinates
private int x;
private int y;
//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;
}
The above code is very easy to understand. I have written comments to explain everything. So let’s
move ahead.
To draw the player to our GameView you need to come back to the GameView.java class and
modify it as below.
118
private SurfaceHolder surfaceHolder;
@Override
public void run() {
while (playing) {
update();
draw();
control();
}
}
119
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
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.
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.
@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.
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.
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;
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;
}
}
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);
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.
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.
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.
Now we will add background stars to make the background looks animating.
Star.java
126
package net.simplifiedcoding.spacefighter;
import java.util.Random;
127
x = maxX;
Random generator = new Random();
y = generator.nextInt(maxY);
speed = generator.nextInt(15);
}
}
128
private Player player;
private Paint paint;
private Canvas canvas;
private SurfaceHolder surfaceHolder;
private ArrayList<Star> stars = new
ArrayList<Star>();
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();
}
}
129
//Updating the stars with player speed
for (Star s : stars) {
s.update(player.getSpeed());
}
}
canvas.drawBitmap(
player.getBitmap(),
player.getX(),
player.getY(),
paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
130
}
}
@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.
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;
133
speed = generator.nextInt(10) + 10;
x = maxX;
y = generator.nextInt(maxY) - bitmap.getHeight();
}
}
public Bitmap getBitmap() {
return bitmap;
}
We need to add the enemies in the GameView now. So come inside GameView.java and modify
the code as follows.
134
private Paint paint;
private Canvas canvas;
private SurfaceHolder surfaceHolder;
private Enemy[] enemies;
private int enemyCount = 3;
surfaceHolder = getHolder();
paint = new Paint();
@Override
public void run() {
while (playing) {
135
update();
draw();
control();
}
}
paint.setColor(Color.WHITE);
canvas.drawBitmap(
player.getBitmap(),
player.getX(),
136
player.getY(),
paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
137
}
}
@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.
139
private int maxY;
private int minY;
private Rect detectCollision;
140
}
public void setX(int x){
this.x = x;
}
public Rect getDetectCollision() {
return detectCollision;
}
public Bitmap getBitmap() {
return bitmap;
}
141
private int speed = 0;
private boolean boosting;
private final int GRAVITY = -10;
private int maxY;
private int minY;
142
if (boosting) {
speed += 2;
} else {
speed -= 5;
}
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;
}
Now to complete the collision detection, again to inside GameView.java file and modify
the update() method as follows.
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.
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;
145
x = -250;
y = -250;
}
public void setX(int x) {
this.x = x;
}
146
Now again come inside GameView.java file and modify the code as follow.
surfaceHolder = getHolder();
paint = new Paint();
147
}
@Override
public void run() {
while (playing) {
update();
draw();
control();
}
}
148
boom.setY(enemies[i].getY());
enemies[i].setX(-200);
}
}
}
paint.setColor(Color.WHITE);
canvas.drawBitmap(
player.getBitmap(),
player.getX(),
player.getY(),
paint);
149
paint
);
}
canvas.drawBitmap(
boom.getBitmap(),
boom.getX(),
boom.getY(),
paint
);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
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:
<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"
</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:
153
private int currImage = 0;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_changing);
setInitialImage();
setImageRotateListener();
rotatebutton.setOnClickListener(new OnClickListener() {
@Override
currImage++;
154
if (currImage == 3) {
currImage = 0;
setCurrentImage();
});
setCurrentImage();
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:
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.
<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"
</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.
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_switcher_example);
initializeImageSwitcher();
setInitialImage();
setImageRotateListener();
158
}
imageSwitcher.setFactory(new ViewFactory() {
@Override
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() {
rotatebutton.setOnClickListener(new OnClickListener() {
@Override
currImage++;
if (currImage == 3) {
currImage = 0;
setCurrentImage();
});
setCurrentImage();
160
}
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.
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:
The layout of your project should have one ImageView and a Button as shown:
<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"
</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:
"http://www.abc.com/image2.jpg",
"http://www.abc.com/image3.jpg"
};
ImageView bmImage;
this.bmImage = bmImage;
164
try {
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("MyApp", e.getMessage());
return bitmap;
bmImage.setImageBitmap(result);
@Override
165
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imagedownloader);
setInitialImage();
setImageRotateListener();
rotatebutton.setOnClickListener(new OnClickListener() {
@Override
currImage++;
if (currImage == 3) {
currImage = 0;
166
}
setCurrentImage();
});
setCurrentImage();
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.
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>
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
169
addImagesToThegallery();
imageGallery.addView(getImageView(image));
LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
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