The document is a bonafide certificate from Bharathidasan Engineering College for a 6th semester Computer Science Engineering student. It details the practical work done by the student in Mobile Application Development LAB-CS6611 from January 2016 to April 2016. It includes the student's details, table of contents, objectives of the lab, list of experiments conducted, and details of one experiment on creating a simple UI design Android application where the student creates an app using GUI components, fonts and colors in Android Studio.
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Cs 6611 mad lab manual
1. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
1
NATTRAMPALLI – 635 854
(Approved by AICTE New Delhi and Affiliated to Anna University)
NAME :
REGISTER NUMBER
SUBJECT CODE / NAME : ………………………………………..
YEAR/SEM : …………………………………….......
MAY 2016
Department of Computer Science Engineering
2. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
2
NATTRAMPALLI - 635 854. VELLORE DISTRICT
Department of Computer Science Engineering
BONAFIDE CERTIFICATE
Certified with this is a bonafide record of the practical work done by _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 6h Semester Computer Science
Engineering in Mobile Application Development LAB-CS6611 during the period JAN 2016 to
APR 2016
Staff In-Charge Head of the Department
University RegisterNumber:
3. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
3
Submitted for the Practical examination held on……….....…………….at Bharathidasan
Engineering College, Nattrampalli.
Internal Examiner External Examiner
TABLE OF CONTENTS
Ex.
No
Date Name of the Experiment
Page
No.
Staff
Signature
4. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
4
CS6611 MOBILE APPLICATION DEVELOPMENT LABORATORY
OBJECTIVES:
The student should be made to:
Know the components and structure of mobile application development frameworks for
Android and windows OS based mobiles.
Understand how to work with various mobile application development frameworks.
Learn the basic and important design concepts and issues of development of mobile
applications.
Understand the capabilities and limitations of mobile devices.
LIST OF EXPERIMENTS:
1. Develop an application that uses GUI components, Font and Colours
2. Develop an application that uses Layout Managers and event listeners.
3. Develop a native calculator application.
4. Write an application that draws basic graphical primitives on the screen.
5. Develop an application that makes use of database.
6. Develop an application that makes use of RSS Feed.
7. Implement an application that implements Multi-threading
8. Develop a native application that uses GPS location information.
9. Implement an application that writes data to the SD card.
10. Implement an application that creates an alert upon receiving a message.
11. Write a mobile application that creates alarm clock
5. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
5
Mission
Our mission is to be the leading mobile application development organization. We aim to
develop mobile apps that can change the way we do our day to day work, with a click of a
button.
Vision Our vision is to be one of the most innovative organizations in around the world. We
believe technology can makes life better for everyone, if used for a good cause. We want to
develop mobile application development training and methodologies, which can make cutting
edge technologies so that the world is a better place.
Ex.No. CREATION OF SIMPLE UI DESIGN ANDROID APPLICATION
Aim:
To create an application that uses GUI components, Font and Colors using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:
1. Select FileNew Project from the menu to create a new project, Studio will present you with
your first project creation screen:
6. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
6
2. Enter Application name as shown above. Feel free to put your own name in the Company
Domain text field. As you type, you’ll notice the Package Name will automatically change to
create a reverse domain style name based on your Application name and Company Domain.
Click next at the bottom of the window to progress to the next part of the project setup.
7. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
7
3. Click Next option. The next screen is where you select device types and operating systems to
target. Want an App to focus on just Phone and Tablet? For now though you just want an App
that works on an Android Phone. This option is selected as the default, alongside the
default Minimum SDK.The Minimum SDK drop down menu sets the minimum version of
Android needed to run your app. selecting this value for your own projects is a matter of
balancing the SDK capabilities you want and the devices you want to support.
8. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
8
4. Choose “Blank Activity”
Getting back to the new project window, click Next in the bottom right to pick more
options for your project. This screen lets you choose a default Activity for your app. Think of an
Activity as a window within your App that displays content the user can interact with – not
unlike a View Controller in iOS. An activity can take up the entire screen or it could be a simple
pop-up. Available activities on this template range from a blank activity with an Action Bar right
up to an Activity with a MapView embedded. You will be making a lot of activities, so it’s good
to get accustomed with them. Select the Blank Activity option and click Next.
9. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
9
5. If you have made it this far then well done, you are at the final screen before you dig into
some actual coding. To speed this part up a little bit you will use the pre-populated default
values, but what is actually done with these values?
Activity Name. This will give your Activity a name to refer to in code. Once the project
setup is complete Android Studio will create a .java class and use the contents of this text
field to give the class a name. This is the name you will use to refer to your Activity inside
your code.
Note: What it’s actually doing is making a subclass of Activity. Those familiar with
object-oriented programming will know what this is, but for newcomers, this basically
means that yourMainActivity is going to be a customized version of Activity that acts just
like the default one, handling things like its lifecycle and the user interface display.
Layout Name. You’re going to define your Activity in Java, but the layout of everything it
will show to the user is defined in a special sort of Android XML. You will learn how to
read and edit those files shortly.
Click Finish. Android Studio takes this as its cue to go do a bunch of behind-the-scenes
operations and create your project. As it shoots out some descriptions of what it’s doing from
time to time, you may notice it say something like the following:
6. You see your project name, which is familiar. But then there is this Gradle word, and then a
mention of Maven in the URL. The benefit of having a modern IDE like Android Studio is
that it handles a lot for you. But as you’re just beginning to learn how to use the software, it’s
good to know, in general, what it’s doing for you.
Cradle is a new build tool that is easy to use, but it also contains a lot of advanced options if
you investigate it further. It takes your Java code and XML layouts, and then uses the latest
Android build tools to create the app package file, known as an APK file. You can
customize your configurations to have development or production versions of the app that
behave differently, or add dependencies for third-party libraries.
10. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
10
UI Elements:
Layouts: Linear Layout o Horizontal vs Vertical, Relative Layout, Table Layout, Grid Layout,
Frame Layout
Widgets: Text View, Button, Radio Button, Toggle Button, Image View, Image Button,
Checkbox, Progress Bar, Seek Bar, Rating Bar
Web View
• Spinner
Text Fields
• Edit Text o Plain text, Name, Number, Email etc.
Containers
• Scroll View , Vertical vs. Horizontal ,List View ,Grid View ,Search View
Tab Host
11. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
11
• Background colour or draw able, id, padding, margin, TextColor colour value (Hex, Reba
etc.) draw able colour resource ,text Style ,typeface
7. Changing attributes (text color, background, typeface etc.) in java
TextView <<variable>> = (TextView) findViewById(R.id.<<id>>);
<<variable>>.setTextColor(getResources().getColor(R.color.<<name>>));
The color resource is defined in a “color.xml” resource file inside “values” resource directory.
E.g.:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="yellow">#FFFF00</color>
</resources>
<<variable>>.setBackgroundColor(getResources().getColor(R.color.<<name>>));
Changing Type Face
1. First we need to import a font face to assets directory.
2. Create an assets directory.
3. In Android Studio, select File>app>New>Java Class>Folder>Assets Folder.
4. Download a font from internet and put it under assets/fonts folder.
5. Create a new directory “font” – not necessary –
6. Modify src/MainActivity.java file to add necessary code.
7. Modify the res/layout/activity main to add respective XML components
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
13. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
13
TextView tF = (TextView) findViewById(R.id.txt); //find the textView with id theFont
//Now we need to create a new TypeFace from the .ttf file we imported
Typeface typeface = Typeface.createFromAsset(getAssets(),"font/Android Insomnia
Regular.ttf"); //Set the typeface of the textView tF.setTypeface(typeface);
//the type-face will change at
tF.setTypeface(typeface);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
16. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
16
8. First: On the Emulator
Before we can run the application, we need to setup an Android Virtual Device (AVD),
or emulator, to run it on:
Android Studio comes free with the ability to set up a software-based Android device on
your computer and run apps on it, browse websites, debug and everything you would
expect. This capability is known as the Android Emulator.
Select the menu Tools ->Android "Android SDK and AVD Manager".
Let’s run through creating a new AVD. Click Create Virtual Device… in the bottom left to
begin configuring a new virtual device.
The first decision you need to make is what type of device you want to emulate.
The Category list to the left shows all the types of device you can emulate. Clicking each
option shows you what type of devices are available to you in that category. For now you
just want to emulate a phone sized device but if you wanted to emulate an Android Wear
watch or an Android TV then you have options to do so here.Select Nexus S in the list of
devices available to you from the phone category and click next.
Your next decision is to decide what version of Android you want your virtual device to
run. You will already have one or two available to you thanks to the setup wizard, so let’s
use one of them. Select Lollipop and make sure the one selected has the value x86 in
the ABI column. We want the emulator to be running as fast as possible on our x86
computers. :)
Click Next once this is done to move to the final screen. The last screen is simply a
confirmation of your previous choices with the option to configure some other properties
of your device such as device name, start-up orientation, and RAM size. For now leave
these set as their defaults and click Finish.
17. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
17
Congratulations! With relative ease you’ve just created a fresh virtual device ready for use
to test out your new app.
Now, close the AVD Manager to go back to Android Studio’s main view. Now that you’ve
configured everything, there’s but one step left…
19. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
19
8. We're now ready to run our application.
Select the menu Run -> Run.
• Note: The emulator may take a long time to start up.
• Note: Another way to run your application is to right-click on the project in the
Package Explorer, then select Run As -> Android Application.
23. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
23
Result: Thus the UI android application that uses GUI components, Font and Colours was
successfully executed.
Ex.No.1. Layout and Event Listeners
Aim:
To create an application that uses Layout Managers and event listeners using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Layouts
1. Relative Layout
As in name this layout positions elements relative to the adjacent elements. It uses the
following attributes for each element to position them: layout:alignEnd ,layout:alignStart
,layout:toEndOf ,layout:toStartOf ,layout:alignParent , layout:centreInParent
1. We will create a Text View (Large) inside the parent Relative layout by editing the xml code:
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
24. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
24
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.kani.student.text1.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SampleProgram!"
android:id="@+id/textSample" />
</RelativeLayout>
Linear Layout
1. Linear layout are two types Horizontal and Vertical.
2. Horizontal/Vertical is set using the orientation attribute.
3. In such layout the elements are arranged in order top-to-bottom or
left-to-right.
4. Let’s add a Linear Layout now. (Now you can use the drag and drop layout
editor). Change orientation to Vertical.
5. Now add an Image View to the Linear Layout.
25. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
25
6. Import an image to the draw able directory. (Just as we have imported font
face in previous chapter).
7. Set the src attribute to the draw able we imported. (Click the browse button
and select the file from Draw able directory).
26. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
26
Table Layout:
As we all know table layout uses rows and columns to position elements.
Add table layout inside the linear layout. Table layout uses Table Row layout to create rows.
Add a Table Row to the Table Layout. Add two Buttons to the Table Row.
Change the Id’s of the two Buttons to btnClick and btnLongClick respectively.
we will use these buttons to implement event listeners
Change text to Click Me! and Long Click Me! also.
Select one of the buttons from the component tree. Pay attention to Properties window. You
can see layout: span and layout: column attributes. The table layout uses these attributes to
position elements.
If the values are unset then uses default values (span=1 and column increments according to
order of placement).
Grid Layout
This is a very useful layout. This layout has order as well as freedom.
This layout uses orderly grids with rows and columns, span and spaces.
Add a Grid Layout below the table layout.
Now drag and drop a Button to the Grid Layout.
You’ll see a green grid with many blocks.
Example:
27. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
27
2. Select this button and you can see that it uses attributes layout: column, layout: row, layout:
row Span, layout: column Span. These are the attributes to position to items in Grid Layout.
Change the row Span to.
Resize the button
Add one more button and a text field.
Edit the xml file to position them correctly
XML Coding:
<GridLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="@+id/lytGrid">
<Button
android:layout_width="202dp"
android:layout_height="156dp"
android:text="Click or Long CLick n Me"
android:id="@+id/btnAll"
android:layout_column="3"
android:layout_row="0"
android:layout_columnSpan="1"
android:layout_rowSpan="2" />
<Button
android:layout_width="143dp"
android:layout_height="match_parent"
android:text="Show nMy nName"
android:id="@+id/btnShowName"
android:layout_row="1"
android:layout_column="2"
android:layout_rowSpan="3" />
31. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
31
Setting up Java Code:
package com.kani.student.eventlisteners;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
Button clickBtn, longClickBtn, allBtn, btnShow;
TextView sample;
EditText nameTxt;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickBtn = (Button) findViewById(R.id.btnClick);
longClickBtn = (Button) findViewById(R.id.btnLongClick);
allBtn = (Button) findViewById(R.id.btnAll);
btnShow = (Button) findViewById(R.id.btnShowName);
sample = (TextView) findViewById(R.id.txtSample);
nameTxt = (EditText) findViewById(R.id.txtName);
/*Simple Click onClick Listener*/
clickBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hai III CSE!",
32. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
32
Toast.LENGTH_SHORT).show();
}
});
/*Implement Long Click Listener*/
longClickBtn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), "Hai BEC !",
Toast.LENGTH_SHORT).show();
return false;
}
});
allBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "You Just Clicked Me!",
Toast.LENGTH_SHORT).show();
}
});
allBtn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), "You clicked me for so long!",
Toast.LENGTH_SHORT).show();
return false;
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//sample.setText(nameTxt.getText().toString());
Toast.makeText(getApplicationContext(), "K.POOVAZHAKI!",
Toast.LENGTH_SHORT).show();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
33. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
33
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kani.student.eventlisteners/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
34. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
34
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kani.student.eventlisteners/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
Output:
Result: Thus the Layout and Event listener android application was successfully executed.
35. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
35
Ex.No.2. Layout and Event Listeners
Aim:
To create an application that uses Layout Managers and event listeners using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Setting up XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.library.bec.ex_1_eventlistener.MainActivity"
tools:showIn="@layout/activity_main">
<TextView android:text="hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/background"
android:weightSum="1">
36. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
36
<Button
android:layout_width="266dp"
android:layout_height="wrap_content"
android:text="Green"
android:id="@+id/btnGreen"
android:layout_weight="0.07" />
<Button
android:layout_width="269dp"
android:layout_height="wrap_content"
android:text="Blue"
android:id="@+id/btnBlue"
android:layout_weight="0.07" /> </LinearLayout>
</RelativeLayout>
Setting up Java:
package com.library.bec.ex_1_eventlistener;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
LinearLayout background;
Button btnGreen, btnBlue;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
background = (LinearLayout) findViewById(R.id.background);
37. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
37
btnGreen = (Button) findViewById(R.id.btnGreen);
btnBlue = (Button) findViewById(R.id.btnBlue);
btnGreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
background.setBackgroundColor(Color.parseColor("#00ff00"));
}
});
btnBlue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
background.setBackgroundColor(Color.parseColor("#006699"));
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
38. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
38
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.library.bec.ex_1_eventlistener/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.library.bec.ex_1_eventlistener/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Output:
Result: Thus the android Event Listener application was successfully executed.
39. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
39
ExNo. CALCULATOR APPLICATION
Aim: To create a native calculator application using Android Studio.
Algorithm:
Using the Android Studio create a project of the type mobile application.
Create a simple application in the project.
Click on the Design tab and design the prototype of the application.
Click on source tab and modify the application logic of the application.
Save the project.
Right click on the project and click on deploy and undeploy.
Then test the android application.
Steps:
• In this Tutorial we are going to start a new project Calculator.
• First of all, to start with we are going to create a simple calculator to do simple
arithmetic operations (i.e., one operator and two operands).
• Start Android Studio .Create a new Project.
• Target Android devices >> Check Phone and Tablet
• Select a Blank Activity >>
• Click Finish keeping the default settings for Activity (Name: Main Activity…..).
43. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
43
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
public String str = "";
Character op = 'q';
int i, num, numtemp;
EditText showResult;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
showResult = (EditText) findViewById (R.id.result_id);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }
public void btn1Clicked(View v) {
insert(1); }
public void btn2Clicked(View v) {
insert(2); }
public void btn3Clicked(View v) {
insert(3); }
public void btn4Clicked(View v) {
insert(4); }
public void btn5Clicked(View v) {
insert(5); }
public void btn6Clicked(View v) {
insert(6); }
public void btn7Clicked(View v) {
insert(7); }
public void btn8Clicked(View v) {
insert(8); }
public void btn9Clicked(View v) {
insert(9); }
public void btnplusClicked(View v) {
perform();
op = '+'; }
public void btnminusClicked(View v) {
perform();
44. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
44
op = '-'; }
public void btndivideClicked(View v) {
perform();
op = '/'; }
public void btnmultiClicked(View v) {
perform();
op = '*'; }
public void btnequalClicked(View v) {
calculate(); }
public void btnclearClicked(View v) {
reset(); }
private void reset() {
// TODO Auto-generated method stub
str = "";
op = 'q';
num = 0;
numtemp = 0;
showResult.setText(""); }
private void insert(int j) {
// TODO Auto-generated method stub
str = str + Integer.toString(j);
num = Integer.valueOf(str).intValue();
showResult.setText(str); }
private void perform() {
// TODO Auto-generated method stub
str = "";
numtemp = num; }
private void calculate() {
// TODO Auto-generated method stub
if (op == '+')
num = numtemp + num;
else if (op == '-')
num = numtemp - num;
else if (op == '/')
num = numtemp / num;
else if (op == '*')
num = numtemp * num;
showResult.setText("" + num); }
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
45. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
45
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.javasamples.calci1/http/host/path") );
AppIndex.AppIndexApi.start(client, viewAction); }
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.javasamples.calci1/http/host/path"));
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Output:
Result: Thus the android Calculator application was successfully executed.
46. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
46
Ex.no. CREATION OF SIMPLE GRAPHICAL APPLICATION
Aim:
To create an application that draws basic graphical primitives on the screen using Android
Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:
1. View class which is used to draw graphical items on to the android app screen.
2. In this exercise we will draw some graphic primitives using Paint, View, Canvas and a
method on Draw ().
3. Go ahead and start our project.
47. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
47
4. In the Add an Activity section Select No Activity.
5. Open the Project Window.
6. Expand the app and then the java folders.
48. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
48
7. Now we need to extend the View Class to the Sample Canvas class we just created. Go ahead
and edit the Java File.
8. Now we need to create a Paint object.
9. So above the constructor definition add the following code.
10. Now place the cursor below the constructor definition and press [ALT] + [Insert] and select
Override Methods from the popup Menu.
11. To draw a rectangle we use the function:
canvas.drawRect (float left, float top, float right, float bottom, Paint paint) ;
The arguments can be depicted as shown below:
The co-ordinates of: A = (left, top) B = (right, bottom) paint is the paint object we created.
Let’s draw a rectangle now:
canvas.drawRect(100,100,300,300,paint) ;
49. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
49
9. Drawing a circle
canvas.drawCircle (float cx, float cy, float radius, Paint paint) The co-ordinates of A =
(cx,cy).And the length AB = radius.Let’s draw a circle with fill color green center at (200,200)
and radius paint.setColor(Color.GREEN) ; canvas.drawCircle(200,200,75,paint) ;
Setting up Java:
packagecom.kani.student.kani;
importandroid.graphics.Bitmap;
importandroid.graphics.Canvas;
importandroid.graphics.Color;
importandroid.graphics.Paint;
importandroid.graphics.drawable.BitmapDrawable;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.support.design.widget.FloatingActionButton;
importandroid.support.design.widget.Snackbar;
importandroid.support.v7.app.AppCompatActivity;
importandroid.support.v7.widget.Toolbar;
importandroid.view.Menu;
importandroid.view.MenuItem;
importandroid.view.View;
importandroid.widget.LinearLayout;
importcom.google.android.gms.appindexing.Action;
importcom.google.android.gms.appindexing.AppIndex;
importcom.google.android.gms.common.api.GoogleApiClient;
importcom.google.android.gms.common.api.PendingResult;
importcom.google.android.gms.common.api.Status;
publicclassMainActivity extends AppCompatActivity {
floatx,y,radius;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
50. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
50
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Paintpaint =new Paint();
paint.setColor(Color.parseColor("#CD5C5C"));
Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bg);
canvas.drawRect(50, 50, 300, 300, paint);
LinearLayout ll = (LinearLayout) findViewById(R.id.rect);
ll.setBackgroundDrawable(new BitmapDrawable(bg));
paint.setColor(Color.parseColor("#FF0786FC"));
canvas.drawCircle(200, 200, 100,paint);
LinearLayout ll1 = (LinearLayout) findViewById(R.id.circle);
paint.setColor(Color.BLACK);
canvas.drawLine(100, 200, 300, 200, paint);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} });
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
51. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
51
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true; }
return super.onOptionsItemSelected(item); }
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kani.student.kani/http/host/path") );
AppIndex.AppIndexApi.start(client, viewAction); }
52. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
52
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kani.student.kani/http/host/path") );
PendingResult<Status> end = AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Content_main.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.kani.student.kani.MainActivity"
tools:showIn="@layout/activity_main">
<LinearLayout
53. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
53
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="184dp"
android:id="@+id/rect"></LinearLayout>
</RelativeLayout>
Output:
Result: Thus the android Graphical Primitive Screens application was successfully
executed.
54. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
54
Ex.No. CREATION OF SIMPLE DATA HANDLING APPLICATION
Aim:
To create an application that makes use of database using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:
To use a database to save and access data.
We will use the SQLite Database and SQLiteOpenHelper classes to implement database
handling.
57. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
57
Open the activity_main.xml layout and in my android studio 1.5 there is bunch of custom
views with a floating button.
Setting up XML:
61. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
61
public void addData()
{
btnaddData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted=
mydb.insertData(name.getText().toString(),age.getText().toString());
if(isInserted=true)
Toast.makeText(MainActivity.this,"data
inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"insertion
failed",Toast.LENGTH_LONG).show(); } }); }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) { return true; }
return super.onOptionsItemSelected(item); }}
Output:
Result: Thus the android Database handling application was successfully executed.
62. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
62
Ex.No. CREATION OF SIMPLE RSS FEED PARSING APPLICATION
Aim:
To develop an application that parse RSS feeds from XML RSS File in internet using Android
Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:
Create a new project with an empty activity.
Edit the xml layout file to create a layout with a List View with id lstMain.
Setting up Main Activity java:
package com.infotech.rit.database_con;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
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 android.widget.TextView;
import android.widget.Toast;
63. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
63
public class AndroidRssReader extends ListActivity
{
private RSSFeed myRssFeed= null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new MyTask().execute();
}
private class MyTask extends AsyncTask
{
@Override
protected Void doInBackground(Void... arg0)
{
try
{
URL rssUrl = new URL("http://www.gov.hk/en/about/rss/govhkrss.data.xml");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed= myRSSHandler.getFeed();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
66. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
66
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
</manifest>
Output:
68. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
68
Ex.No. 1. CREATION OF MULTITHREADING IN ANDROID APPLICATION
Aim:
To develop Multithreading in an application using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:
• When an application is launched, the system creates a thread of execution for the
application, called "main." This thread is very important because it is in charge of
dispatching events to the appropriate user interface widgets, including drawing events.
• It is also the thread in which your application interacts with components from the
Android UI toolkit (components from the android.widget and android.view packages). As
such, the main thread is also sometimes called the UI thread.
• The system does not create a separate thread for each instance of a component. All
components that run in the same process are instantiated in the UI thread, and system calls
to each component are dispatched from that thread.
• When your app performs intensive work in response to user interaction, this single
thread model can yield poor performance unless you implement your application properly.
• Specifically, if everything is happening in the UI thread, performing long
operations such as network access or database queries will block the whole UI.
• When the thread is blocked, no events can be dispatched, including drawing events.
From the user's perspective, the application appears to hang. Even worse, if the UI thread
is blocked for more than a few seconds (about 5 seconds currently) the user is presented
with the infamous "application not responding" (ANR) dialog.
69. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
69
• Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate
your UI from a worker thread—you must do all manipulation to your user interface from
the UI thread. Thus, there are simply two rules to Android's single thread model:
• Do not block the UI thread.
• Do not access the Android UI toolkit from outside the UI thread?
WORKER THREADS
Because of the single thread model described above, it's vital to the responsiveness of your
application's UI that you do not block the UI thread. If you have operations to perform that are
not instantaneous, you should make sure to do them in separate threads ("background" or
"worker" threads).
• We are going to create an app that loads image bitmap from a URL and sets it to an
ImageView.
• We are using two interface here – The User Interface and the Network Interface,
we need to implement multi-threading i.e. create a new thread to interact with the network.
• Create a new Project (Multi Threading) with an empty activity (MainActivity).
• Edit the activity_main.xml to add an ImageView and a Button which when clicked
loads image to the ImageView. Testing:
Run the application in an emulator or a device and test it.
You need to be connected to internet to load image from internet.
Setting up XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.javasamples.multi1.MainActivity"
tools:showIn="@layout/activity_main">
70. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
70
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/TextView01"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/Button01" android:text="click to change text"
android:layout_below="@+id/EditText01"
android:layout_alignParentStart="true"
android:layout_marginTop="89dp"
android:textColor="#f90303"
android:textSize="34sp" />
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/EditText01"
android:text="@+id/EditText01"
android:textSize="34dp"
android:textColor="#fc0505" />
</RelativeLayout>
Setting up Java:
package com.javasamples.multi1;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
71. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
71
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Button)findViewById(R.id.Button01)).setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
updateUI("start of long operation");
// This will cause the UI to freeze
updateUI(doLongOperation());
//This causes the application to crash
/* (new Thread(new Runnable() {
@Override
public void run() {
updateUI(doLongOperation());
}
})).start(); */
/*
// option 1
final Handler myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
updateUI((String)msg.obj);
}
};
(new Thread(new Runnable() {
72. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
72
@Override
public void run() {
Message msg = myHandler.obtainMessage();
msg.obj = doLongOperation();
myHandler.sendMessage(msg);
}
})).start();
*/
// option 2
final Handler myHandler = new Handler();
(new Thread(new Runnable() {
@Override
public void run() {
final String res = doLongOperation();
for (int i = 0; i < 30; i++) {
myHandler.post(new Runnable() {
@Override
public void run() {
updateUI(res);
}
});
}
}
})).start();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
73. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
73
public void updateUI(String str) {
((TextView) findViewById(R.id.TextView01)).setText(str);
}
public String doLongOperation() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "end of long operation";
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's
content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.javasamples.multi1/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
74. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
74
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's
content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.javasamples.multi1/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Output:
Result: Thus the android Multithreading application was successfully executed.
75. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
75
Ex.No. 2. CREATION OF MULTITHREADING IN ANDROID
APPLICATION
Aim:
To develop Multithreading in an application using Android Studio.
Algorithm:
8. Using the Android Studio create a project of the type mobile application.
9. Create a simple application in the project.
10. Click on the Design tab and design the prototype of the application.
11. Click on source tab and modify the application logic of the application.
12. Save the project.
13. Right click on the project and click on deploy and undeploy.
14. Then test the android application.
Steps:
• When an application is launched, the system creates a thread of execution for the
application, called "main." This thread is very important because it is in charge of
dispatching events to the appropriate user interface widgets, including drawing events.
• It is also the thread in which your application interacts with components from the
Android UI toolkit (components from the android.widget and android.view packages). As
such, the main thread is also sometimes called the UI thread.
• The system does not create a separate thread for each instance of a component. All
components that run in the same process are instantiated in the UI thread, and system calls
to each component are dispatched from that thread.
• When your app performs intensive work in response to user interaction, this single
thread model can yield poor performance unless you implement your application properly.
• Specifically, if everything is happening in the UI thread, performing long
operations such as network access or database queries will block the whole UI.
• When the thread is blocked, no events can be dispatched, including drawing events.
From the user's perspective, the application appears to hang. Even worse, if the UI thread
is blocked for more than a few seconds (about 5 seconds currently) the user is presented
with the infamous "application not responding" (ANR) dialog.
76. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
76
• Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate
your UI from a worker thread—you must do all manipulation to your user interface from
the UI thread. Thus, there are simply two rules to Android's single thread model:
• Do not block the UI thread.
• Do not access the Android UI toolkit from outside the UI thread?
WORKER THREADS
Because of the single thread model described above, it's vital to the responsiveness of your
application's UI that you do not block the UI thread. If you have operations to perform that are
not instantaneous, you should make sure to do them in separate threads ("background" or
"worker" threads).
• We are going to create an app that loads image bitmap from a URL and sets it to an
ImageView.
• We are using two interface here – The User Interface and the Network Interface,
we need to implement multi-threading i.e. create a new thread to interact with the network.
• Create a new Project (Multi Threading) with an empty activity (MainActivity).
• Edit the activity_main.xml to add an ImageView and a Button which when clicked
loads image to the ImageView. Testing:
Run the application in an emulator or a device and test it.
You need to be connected to internet to load image from internet.
Setting up XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
78. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
78
Setting up Java
package com.library.bec.ex_multithrading1;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
private ProgressBar progress;
private TextView t1;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (ProgressBar) findViewById(R.id.progressBar);
t1 = (TextView) findViewById(R.id.txtdis);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
79. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
79
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void startprogress(View view) {
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
final int value = i;
doSomeWork();
progress.post(new Runnable() {
@Override
public void run() {
t1.setText("Updating");
progress.setProgress(value); } }); } } };
new Thread(runnable).start(); }
private void doSomeWork() {
try {
Thread.sleep(2000);
} catch (Exception e) { } }
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
80. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
80
Uri.parse("android-app://com.library.bec.ex_multithrading1/http/host/path") );
AppIndex.AppIndexApi.start(client, viewAction); }
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.library.bec.ex_multithrading1/http/host/path") );
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Output:
Result: Thus the android GPS location application was successfully executed.
81. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
81
Ex.No. CREATION OF SIMPLE GPS LOCATION APPLICATION
Aim:
To develop a GPS Location application using Android Studio.
Algorithm:
• Using the Android Studio create a project of the type mobile application.
• Create a simple application in the project.
• Click on the Design tab and design the prototype of the application.
• Click on source tab and modify the application logic of the application.
• Save the project.
• Right click on the project and click on deploy and undeploy.
• Then test the android application.
Steps:
For this we will use:
• System location service
• LocationManager and LocationListener
• Permission to access FINE_LOCATION
• Start a new project “GeoLocation” with an empty activity.
• Edit the activity_main.xml to change the parent layout to LinearLayout (Verical)
and to add the - GPS locating cannot be used indoors.
- If using an emulator you need to pass the location values yourself using the settings of the
emulator.
- So, it is better to test it in a device outdoor.
Setting up XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
84. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
84
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onLocationChanged(Location location) {
TextView t1 = (TextView) findViewById(R.id.textview1);
TextView t2 = (TextView) findViewById(R.id.textview2);
t1.setText("" + location.getLatitude());
t2.setText("" + location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}}
86. 5105 –BHARATHIDASAN ENGINEERING COLLEGE
86
Ex.No. CREATION OF WRITING DATA TO SD CARD APPLICATION
Aim:
To develop a Writing data to SD Card application using Android Studio.
Algorithm:
• Using the Android Studio create a project of the type mobile application.
• Create a simple application in the project.
• Click on the Design tab and design the prototype of the application.
• Click on source tab and modify the application logic of the application.
• Save the project.
• Right click on the project and click on deploy and undeploy.
• Then test the android application.
Steps:
• To learn how to use memory to store data in android studio app.
• For this we use output stream classes.
• Here we will use FileOutputStream to write data and FileInputStream to read data.
• Edit the layout to add a text field through which we will input the text to be written
into file.
• Two buttons to execute writing and reading of file respectively.
• A TextView to display the text inside the file after reading.
Setting up XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.javasamples.ex_9.MainActivity"
tools:showIn="@layout/activity_main">
<LinearLayout