skill development laboratory · 2018-07-16 · skill development laboratory [sd module-i] te...

68
Lab Manual Skill Development Laboratory Class/Branch: TE(Comp)

Upload: others

Post on 08-Jul-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 1

Lab Manual

Skill

Development

Laboratory

Class/Branch: TE(Comp)

Page 2: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 2

Sandip Foundation's

Sandip Institute of Engineering and Management, Nashik

Department of Computer

Engineering

SEMESTER-I

[A.Y. 2018 - 2019]

LABORATORY MANUAL

SDL

(Subject Code: 310246)

TEACHING SCHEME: EXAMINATION SCHEME:

Practical: 4 Hrs/Week Term Work: 50 Marks

Presentation: 50 Marks

Prepared by:

Prof. D.S.Shingate

Page 3: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 3

List of Assignments

Advanced JAVA

1] Design a system with the help of advance data structures in Java and enhance the

system using collections and generics.

2] Enhance the above system with the help of socket programming use client server

architecture.

3] Enhance above system by using JDBC, Multithreading, concurrency, synchronous and

asynchronous callbacks, ThreadPools using ExecutorService.

4] Transform the above system from command line system to GUI based application

Mobile Application Development

5] Download Install and Configure Android Studio on Linux/windows platform.

6] Design a mobile app for media player.

7] Design a mobile app to store data using internal or external storage.

8] Design a mobile app using Google Map and GPS to trace the location.

Page 4: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 4

Experiment No: 01

Title:

Roll No: ________ Class: _____ Batch: _____

Date of Performance: ___ /___/_____

Date of Assessment: ___ /___/_____

Particulars Marks

Attendance (05)

Journal (05)

Performance (05)

Understanding(05)

Total (20)

Signature of Staff Member

Page 5: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 5

Experiment No: 01

Problem Statement::

Design a system with the help of advance data structures in Java and enhance the system

using collections and generics.

Objectives::

To adapt the usage of modern tools and recent software.

To evaluate problems and analyze data using current technologies

To learn the process of creation of data-driven web applications using current

technologies

To understand how to incorporate best practices for building enterprise applications

To learn how to employ Integrated Development Environment(IDE) for

implementing and testing of software solution

To construct software solutions by evaluating alternate architectural patterns.

Software Requirements:-

- Ubuntu 14.04 , Geditor,JDK

Hardware Requirements:-

-Any Processor above Pentium 4

Theory & Concept::

Introduction to the Collection Framework

We can use an array to store a group of elements of the same type (either

primitives or objects). The array, however, does not support so-called dynamic

allocation - it has a fixed length which cannot be changed once allocated. Furthermore,

array is a simple linear structure. Many applications may require more complex data

structure such as linked list, stack, hash table, sets, or trees.

In Java, dynamically allocated data structures (such as ArrayList, LinkedList,

Vector, Stack, HashSet, HashMap, Hashtable) are supported in aunified architecture

called the Collection Framework, which mandates the common behaviors of all the

Page 6: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 6

classes.

Collection: -

Collections in java is a framework that provides an architecture to store and

manipulate the group of objects . Each item in a collection is called an element. All the

operations that you perform on a data such as searching, sorting, insertion,

manipulation, deletion etc. can be performed by Java Collections. Java Collection

simply means a single unit of objects. Java Collection framework provides many

interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,

PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

Framework: -

A framework by definition is a set of interfaces that force you to adopt some design

practices. A well-designed framework can improve your productivity and provide ease of

maintenance.

The collection framework provides a unified interface to store, retrieve and

manipulate the elements of a collection, regardless of the underlying and actual

implementation. This allows the programmers to program at the interfaces, instead of

the actual implementation.

The Java Collection Framework package (java.util) contains

1. A set of interfaces,

2. Implementation classes, and

3. Algorithms (such as sorting and searching).

Hierarchy of Collection Framework

Let us see the hierarchy of collection framework. The java.util package

contains all the classes and interfaces for Collection framework.

Page 7: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 7

Introduction to Generics

The Java Generics programming is introduced in J2SE 5 to deal with type-safe

objects. We can store any type of objects in collection i.e. non-generic. Now generics,

forces the java programmer to store specific type of objects.

Advantage of Java Generics

1) Type-safety: We can hold only a single type of objects in generics. It doesn’t

allow storing other objects.

2) Type casting is not required: There is no need to typecast the object. Before

Generics, we need to type cast.

e.g.

List list=new ArrayList();

list.add("hello");

String s= (String) list.get(0);//typecasting

After Generics, we don't need to typecast the object.

e.g.

List<String> list =new

ArrayList<String>(); list.add("hello");

String s =list.get(0);

3) Compile-Time Checking: It is checked at compile time so problem will

not occur at runtime. The good programming strategy says it is far better

to handle the problem at compile time than runtime.

Page 8: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 8

Syntax to use generic collection

ClassOrInterface<Type>

e.g. ArrayList<String>

Example of Generics in Java

Import java.util.*;

class TestGenerics1

{

public static void main(String args[])

{

ArrayList<String> list=new ArrayList<String>();

list.add("rahul");

list.add("jai");

String s=list.get(1); //type casting is not

required System.out.println("element is: "+s);

Iterator<String> itr=list.iterator();

while(itr.hasNext())

{

System.out.println(itr.next());

}

}

}

Output:

element is: jai

rahul

jai

Conclusion: - we learn advance data structures in Java using collections and generics.

Page 9: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 9

Experiment No: 02

Title:

Roll No:________ Class:_____ Batch:_____

Date of Performance: ___ /___/_____

Date of Assessment: ___ /___/_____

Particulars Marks

Attendance (05)

Journal (05)

Performance (05)

Understanding(05)

Total (20)

Signature of Staff Member

Page 10: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 10

Experiment No: 02

Problem Statement::

Enhance the system with the help of socket programming use client server

architecture.

Objectives::

To understand Client-Server communication using socket.

Software Requirements:-

- Ubuntu 14.04 , geditor, JDK

Hardware Requirements:-

– Any Processor above Pentium 4

Theory & Concept::

What Is a Socket?

A socket is one end-point of a two-way communication link between two

programs running on the network. Socket classes are used to represent the connection

between a client program and a server program. The java.net package provides two

classes--Socket and ServerSocket--that implement the client side of the connection and

the server side of the connection, respectively.

Client/Server Communication

At a basic level, network-based systems consist of a server, client , and a media

for communication A computer running a program that makes a request for services is

called client machine. A computer running a program that offers requested services

from one or more clients is called server machine. The media for communication can be

wired or wireless network. Generally, programs running on client machines make

requests to a program (often called as server program) running on a server machine.

They involve networking services provided by the transport layer, which is part of the

Internet software stack, often called TCP/IP (Transport Control Protocol/Internet

Protocol) The transport layer comprises two types of protocols, TCP (Transport Control

Protocol) and UDP (User Datagram Protocol). The most widely used programming

interfaces for these protocols are sockets. TCP is a connection-oriented protocol that

Page 11: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 11

provides a reliable flow of data between two computers. Example applications that use

such services are HTTP, FTP, and Telnet.

Sockets and Socket-based Communication

Sockets provide an interface for programming networks at the transport layer.

Network communication using Sockets is very much similar to performing fi le I/O. In

fact, socket handle is treated like fi le handle. The streams used in fi le I/O operation are

also applicable to socket-based I/O. Socket-based communication is independent of a

programming language used for implementing it. That means, a socket program written

in Java language can communicate to a program written in non-Java (say C or C++)

socket program. A server (program) runs on a specific computer and has a socket that is

bound to a specific port. The server listens to the socket for a client to make a

connection request (see Fig. 13.4a). If everything goes well, the server accepts the

connection (see Fig. 13.4b). Upon acceptance, the server gets a new socket bound to a

different port. It needs a new socket (consequently a different port number) so that it

can continue to listen to the original socket for connection requests while serving the

connected client.

SOCKET PROGRAMMING AND JAVA.NET CLASS

A socket is an endpoint of a two-way communication link between two programs

running on the network. Socket is bound to a port number so that the TCP layer can

identify the application that data is destined to be sent. Java provides a set of classes,

defined in a package called java.net, to enable the rapid development of network

applications. Key classes, interfaces, and exceptions in java.net package simplifying the

complexity involved in creating client and server programs are:

The Classes

• ContentHandler

• DatagramPacket

• DatagramSocket

• DatagramSocketImpl

• HttpURLConnection

Page 12: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 12

• InetAddress

• MulticastSocket

• ServerSocket

• Socket

• SocketImpl

• URL

• URLConnection

• URLEncoder

• URLStreamHandler

The Interfaces

• ContentHandlerFactory

• FileNameMap

• SocketImplFactory

• URLStreamHandlerFactory

Exceptions in Java

• BindException

• ConnectException

• MalformedURLException

• NoRouteToHostException

• ProtocolException

• SocketException

• UnknownHostException

• UnknownServiceException

Page 13: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 13

Client-Server Communication Structure

The InetAddress Class :- • Handles Internet addresses both as host names and as IP addresses

• Static Method getByName returns the IP address of a specified host name as an

InetAddress object

• Methods for address/name conversion:

public static InetAddress getByName(String host) throws UnknownHostException

public static InetAddress[] getAllByName(String host) throws UnknownHostException

public static InetAddress getLocalHost() throws UnknownHostException

public boolean isMulticastAddress()

public String getHostName()

public byte[] getAddress()

public String getHostAddress()

public int hashCode()

public boolean equals(Object obj)

Page 14: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 14

public String toString()

e.g.

Retrieving the current machine’s address

import java.net.*; public class MyLocalIPAddress { public static void main(String[] args) { try { InetAddress address = InetAddress.getLocalHost();

System.out.println (address);

} catch (UnknownHostException e) { System.out.println("Could not find local address!"); } } }

The Java.net.Socket Class

• Connection is accomplished through the constructors. Each Socket object is

associated with exactly one remote host. To connect to a different host, you must

create a new Socket object.

1) public Socket(String host, int port) throws UnknownHostException, IOException

Page 15: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 15

2) public Socket(InetAddress address, int port) throws IOException

3) public Socket(String host, int port, InetAddress localAddress, int localPort)

throws IOException

4) public Socket(InetAddress address, int port, InetAddress localAddress, int

localPort) throws IOException

• Sending and receiving data is accomplished with output and input

streams. There are methods to get an input stream for a socket and an

output stream for the socket.

1) public InputStream getInputStream() throws IOException

2) public OutputStream getOutputStream() throws IOException Example of Java Socket Programming

1) MyServer.java

import java.io.*;

import java.net.*; public class MyServer {

public static void main(String[] args){

try{

ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept();//establishes

connection

DataInputStream dis=new

DataInputStream(s.getInputStream()); String

str=(String)dis.readUTF();

System.out.println("message=

"+str); ss.close();

}catch(Exception e){System.out.println(e);} }

Page 16: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 16

}

2) MyClient.java

import java.io.*;

import java.net.*;

public class MyClient {

public static void main(String[] args) {

try{

Socket s=new Socket("localhost",6666); DataOutputStream dout=new

DataOutputStream(s.getOutputStream()); dout.writeUTF("Hello

Server");

dout.flush(); dout.close();

s.close();

}catch(Exception e){System.out.println(e);}

}

}

O/P 1: Server side Siem/home$ javac MyServer.java MyServer message =Hello server

O/P: Clientside Siem/home$ javac MyClient.java

Siem/home$ java MyClient

Conclusion:-

We learn socket programming using client server architecture

Page 17: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 17

Experiment No: 03

Title:

Roll No: ________ Class: _____ Batch:_____

Date of Performance: ___ /___/_____

Date of Assessment: ___ /___/_____

Particulars Marks

Attendance (05)

Journal (05)

Performance (05)

Understanding(05)

Total (20)

Signature of Staff Member

Page 18: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 18

Experiment No: 03

Problem Statement::

Enhance system by using JDBC, Multithreading, concurrency, synchronous and

asynchronous callbacks, ThreadPools using ExecutorService

Objectives::

1) To understand JDBC concept.

2) to understand java mysql connectivity

Software Requirements:-

- Ubuntu 14.04 , Geditor,JDK

Hardware Requirements:-

-Any Processor above Pentium 4

Theory & Concept::

Java JDBC:

Java JDBC is a java API to connect and execute query with the database. JDBC API

uses jdbc drivers to connect with the database.

Why use JDBC

Before JDBC, ODBC API was the database API to connect and execute query with

the database. But, ODBC API uses ODBC driver which is written in C language (i.e.

platform dependent and unsecured). That is why Java has defined its own API (JDBC

API) that uses JDBC drivers (written in Java language).

Page 19: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 19

JDBC Connection Basics

Java database connectivity (JDBC) is a standard application programming

interface (API) specification that is implemented by different database vendors to allow

Java programs to access their database management systems. The JDBC API consists of a

set of interfaces and classes written in the Java programming language. Interestingly,

JDBC is not an acronym and thus stands for nothing but popular as Java Database

Connectivity. According to Sun (now merged in Oracle) JDBC is a trademark term and

not an acronym. It was named to be redolent of ODBC.

JDBC implementation comes in form of a database driver for a particular DBMS

vendor. A Java program that uses the JDBC API loads the specified driver for a particular

DBMS before it actually connects to a database.

JDBC Connection - JDBC Design

JDBC --a trademark comes bundled with Java SE as a set of APIs that facilitates Java

programs to access data stored in a database management system, particularly in a

Relational Database. At the time of designing JDBC (Java database connectivity),

following goals were kept in mind:

• JDBC (Java database connectivity) should be an SQL level API; therefore, it

should allow user to construct SQL statements and embed them into Java API

calls to run those statements on a database. And then results from the database

are returned as Java objects (ResultSets) and access-problems as exceptions.

• JDBC (Java database connectivity) should provide a driver manager to allow

third party drivers to connect to specific databases, where database vendors

could provide their own drivers to plug into the driver manager.

For example MySQL provides its driver in form of a JAR archive (e.g., mysql-

connector-java-***-bin.jar). This driver first should be loaded into memory in

order to connect to a MySQL database, and then driver manager creates a

connection with help of the loaded driver. Whole process will be explained step

by step later in this article.

• JDBC (Java database connectivity) should be simple; there would then be a

simple mechanism to register third party drivers with the driver manager.

Finally, JDBC came into existence as a result of above goals, and two APIs were

created. Application programmers use the JDBC API, and database vendors use

Page 20: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 20

the JDBC Driver API.

JDBC Connection - Create Database for Use

To start using JDBC (Java database connectivity) first you would need a database

system, and then a JDBC (Java database connectivity) driver for your database. During

this article JDBC (Java database connectivity) will be explained with MySQL, but you can

use it with any database system (such as Microsoft SQL, Oracle, IBM DB2, PostgresSQL),

provided that you have a JDBC (Java database connectivity) driver for your database

system.

Suppose you have MySQL and a functional Java environment installed on your

system, where you write and execute Java programs. For MySQL, download MySQL

Connector/J the official JDBC (Java database connectivity) driver for MySQL. You will get

a JDBC driver mysql-connector-java-***-bin.jar in zipped driver bundle. Place this JAR in

Java's classpath because this JAR is the JDBC driver for MySQL and will be used by JDBC

(Java database connectivity).

After having environment ready to experiment JDBC connectivity you need to

create a database and at least one table in the database containing a few records, we

name the example database EXPDB, and table inside EXPDB is EXPTABLE. I create this

database with root privileges, if you do so it's fine but if you create a database with

different user then ensure that you have permissions to create, update and drop tables

in the database you created (to perform above stated operations by JDBC - Java

database connectivity). Now, let's create EXPDB database, a table EXPTABLE in EXPDB,

and insert a few records as follows. Following steps we are executing manually, later we

will connect to this database with the help of JDBC - Java database connectivity.

JDBC Connection - Using JDBC

1. JDBC Connection - DataBase URL or String

Database URL for JDBC connection or JDBC connection string follows more or

less similar syntax to that of ordinary URLs. It tells the protocol used to connect to

database, subprotocol, location of database, port number on which database listens

client requests, and database name. The example syntax may look like

jdbc:mysql://localhost:3306/EXPDB. Aforementioned URL specifies a MySQL database

named EXPDB running on localhost on port 3306.

Page 21: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 21

{

// loads com.mysql.jdbc.Driver into memory

Class.forName("com.mysql.jdbc.Driver");

}

catch (ClassNotFoundException cnf)

{

System.out.println("Driver could not be loaded: " + cnf);

}

2. JDBC Connection - Driver Class

As we have obtained the JDBC driver in form of a JAR file (mysql-connector-java-

***- bin.jar) in which the driver for MySQL database is located. This driver needs to be

registered in order to access EXPDB. Driver file name for MySQL is

com.mysql.jdbc.Driver. This file has to be loaded into memory before you get connected

to database, else you will result into java.sql.SQLException: No suitable driver exception.

3. JDBC Connection - Database User Name and Password

To get a JDBC connection to the database you would require the username and

password, it is the same username and password which we used, while connecting to

MySQL.

Java Program for JDBC Connection

Now we will start writing Java program to connect to EXPDB (our example

database) through JDBC (Java database Connectivity) and perform INSERT and SELECT

operations for demonstration. To illustrate this piece of work, we would take following

steps, and finally collect all pieces of code to assemble the complete program.

1. Register JDBC Driver Class

Registering JDBC driver class with the DriverManager means loading JDBC driver

class in memory.

e.g.

try

Page 22: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 22

private String connectionUrl = "jdbc:mysql://localhost:3306/EXPDB";

private String dbUser = "root";

private String dbPwd = "mysql";

private Connection conn;

try

{

conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);

}

catch (SQLException sqle)

{

System.out.println("SQL Exception thrown: " + sqle);

}

2. Connect to Database through JDBC Driver

In order to connect to example database EXPDB you need to open a database

connection in Java program that you can do as follows by using JDBC driver:

e.g.

//jdbc driver connection string, db username and password

Using DriverManager gets you a connection to the database specified by

connectionUrl. When above code fragment is executed, the DriverManager iterates

through the registered JDBC drivers to find a driver that can use the subprotocol

specified in the connectionUrl. Don't forget to surround getConnection() code by try

block, because it can throw an SQLException.

3. Execute SQL Statements through JDBC Connection

Now that you have a JDBC Connection object conn, you would like to execute

SQL statements through the conn (JDBC connection) object. A connection in JDBC is a

session with a specific database, where SQL statements are executed and results are

returned within the context of a connection. To execute SQL statements you would

need a Statement object that you would acquire by invoking createStatement()

method on conn as illustrated below.

Page 23: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 23

{

Statement stmt = conn.createStatement();

}

e.g.

try

Statement object stmt by executing above piece of code. By definition,

createStatement() throws an SQLException so the code line Statement stmt =

conn.createStatement(); should either surrounded by try block or throw the exception

further. On successful creation of stmt you can send SQL queries to your database with

help of executeQuery(), and executeUpdate() methods. Also the Statement has many

more useful methods.

Next, form a query that you would like to execute on database. For an instance, we

will select all records from EXPDB, our example database. Method executeQuery() will

get you a ResultSet object that contains the query results. You can think a ResultSet

object as two dimensional array object, where each row of an array represents one

record. And, all rows have identical number of columns; some columns may contain null

values. It is all depend upon what is stored in database.

e.g.

String queryString = "SELECT * FROM EXPTABLE"

catch (SQLException sqle)

{

System.out.println("SQL Exception thrown: " + sqle);

}

Page 24: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 24

try

{

ResultSet rs = stmt.executeQuery(queryString);

}

catch (SQLException sqle)

{

System.out.println("SQL Exception thrown: " + sqle);

}

System.out.println("============");

while(rs.next())

{

System.out.print(rs.getInt("id") + "\t" + rs.getString("name"));

Method executeQuery() throws an SQLException, so it should either be

surrounded by try block or further throw the exception. After getting a ResultSet

object rs you may like to process records for further use. Here, for illustration we

would print them on screen.

e.g.

System.out.println("ID \tNAME");

We process one record at a time or you say one row at a time. ResultSet's next()

method helps us to move one record forward in one iteration, it returns true until

reaches to last record, false if there are no more records to process. We access

ResultSet's columns by supplying column headers to getXxx() methods as they are in

EXPTABLE e.g., rs.getInt("id"). You can also access those columns by supplying column

indices to getXxx() methods e.g., rs.getInt(1) will return you the first column of current

row pointed by rs.

4. Close JDBC Connection

JDBC connection to database is a session; it has been mentioned earlier. As soon

System.out.println();

}

Page 25: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 25

try

{

if (conn != null)

{

conn.close();

conn = null;

}

}

catch (SQLException sqle)

{

System.out.println("SQL Exception thrown: " + sqle);

}

as you close the session you are no longer connected to database; therefore, you would

not be able to perform any operation on database. Closing connection must be the very

last step when you are done with all database operations

e.g.

JAVA MySQL Connectivity Program:

import java.sql.*;

import java.io.*;

class Jay

{

public static void main(String args[])throws ClassNotFoundException

{

try

{

Class.forName("com.mysql.jdbc.Driver");

Connection

con=DriverManager.getConnection("mysql:jdbc://localhost:3306/stud","root","siem

");

Statement st=con.createStatement();

Page 26: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 26

ResultSet rs=st.executeQuery("select * from student");

while(rs.next())

{

System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));

}

con.close();

}

catch(Exception e)

{

}

}

o/p

System.out.println(" Erroe:- " +e);

}

Page 27: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 27

Conclusion:

We understand the java mysql connectivity.

ID NAME City

1. Jayraj Nashik

2. Avinash Pune

3. Ashwini Mumbai

Page 28: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 28

Experiment No: 04

Title:

Roll No:________ Class:_____ Batch:_____

Date of Performance: ___ /___/_____

Date of Assessment : ___ /___/_____

Particulars Marks

Attendance (05)

Journal (05)

Performance (05)

Understanding(05)

Total (20)

Signature of Staff Member

Page 29: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 29

Experiment No: 04

Problem Statement::

Transform the system from command line system to GUI based application using

applet

Objectives::

1) To understand GUI concept.

2) To understand Applet and Event handling using applet

Software Requirements:-

- Ubuntu 14.04 , Geditor,JDK

Hardware Requirements:-

– Any Processor above Pentium 4

Theory & Concept::

Java Applet

Applet is a special type of program that is embedded in the webpage to generate

the dynamic content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

• It works at client side so less response time.

• Secured

• It can be executed by browsers running under many plateforms, including

Linux, Windows, Mac Os etc.

Page 30: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 30

Drawback of Applet

• Plugin is required at client browser to execute applet.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends

Container which is the subclass of Component.

Lifecycle of Java Applet

1. Applet is initialized.

2. Applet is started.

3. Applet is painted.

4. Applet is stopped.

5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class

provides 1 life cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4

life cycle methods of applet.

Page 31: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 31

import java.applet.*;

import java.awt.*;

public class Main extends Applet { public void

paint(Graphics g) {

g.drawString("Welcome in Java Applet.",40,20);

}

1) public void init(): is used to initialized the Applet. It is invoked only once.

2) public void start(): is invoked after the init() method or browser is maximized. It is

used to start the Applet.

3) public void stop(): is used to stop the Applet. It is invoked when Applet is stop or

browser is minimized.

4) public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics

class object that can be used for drawing oval, rectangle, arc etc.

E.g.

What is an Event?

Change in the state of an object is known as event i.e. event describes the change

in state of source. Events are generated as result of user interaction with the graphical

user interface components. For example, clicking on a button, moving the mouse,

entering a character through keyboard,selecting an item from list, scrolling the page are

the activities that causes an event to happen

Types of Event

Page 32: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 32

The events can be broadly classified into two categories:

• Foreground Events - Those events which require the direct interaction of

user.They are generated as consequences of a person interacting with the

graphical components in Graphical User Interface. For example, clicking on a

button, moving the mouse, entering a character through keyboard,selecting an

item from list, scrolling the page etc.

• Background Events - Those events that require the interaction of end user are

known as background events. Operating system interrupts, hardware or

software failure, timer expires, an operation completion are the example of

background events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should

happen if an event occurs. This mechanism have the code which is known as event

handler that is executed when an event occurs. Java Uses the Delegation Event Model to

handle the events. This model defines the standard mechanism to generate and handle

the events.Let's have a brief introduction to this model.

The Delegation Event Model has the following key participants namely:

•Source - The source is an object on which event occurs. Source is responsible

for providing information of the occurred event to it's handler. Java provide as

with classes for source object.

•Listener - It is also known as event handler.Listener is responsible for

generating response to an event. From java implementation point of view the

listener is also an object. Listener waits until it receives an event. Once the event

is received , the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely

separated from the logic that generates the event. The user interface element is able to

delegate the processing of an event to the separate piece of code. In this model ,Listener

needs to be registered with the source object so that the listener can receive the event

notification. This is an efficient way of handling the event because the event

notifications are sent only to those listener that want to receive them.

Steps involved in event handling

Page 33: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-I]

TE Computer Engineering Page 33

•The User clicks the button and the event is generated.

•Now the object of concerned event class is created automatically and

information about the source and the event get populated with in same object.

•Event object is forwarded to the method of registered listener class.

•The method is now get executed and returns.

Event Handling Example

import java.awt.*;

import java.awt.event.*;

import java.applet.*; public class Q2 extends Applet implements ActionListener

{

TextField t1 = new TextField(10);

TextField t2 = new TextField(10);

TextField t3 = new TextField(10);

Label l1 = new Label("FIRST NO=:");

Label l2 = new Label("SECOND NO:");

Label l3 = new Label("SUM:");

Button b = new Button("ADD");

public void init()

{

add(l1);

add(t1);

add(l2);

add(t2);

add(l3);

add(t3);

add(b);

b.addActionListener(this);

}

Page 34: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

3

4

public void actionPerformed(ActionEvent e)

{

if (e.getSource() == b)

{

int n1 = Integer.parseInt(t1.getText()); int n2 =

Integer.parseInt(t2.getText()); t3.setText(" " + (n1 +

n2));

}

}

}

/*

<html><body><applet code="Q2.class" height=500 width=500>

</applet></body></html>*/

OUTPUT:

Conclusion: We learn the Applet designing and Event handling for system designing.

Page 35: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

3

5

Experiment No: 05

Title:

Roll No:________ Class:_____ Batch:_____

Date of Performance: ___ /___/_____

Date of Assessment : ___ /___/_____

Particulars Marks

Attendance (05)

Journal (05)

Performance (05)

Understanding(05)

Total (20)

Signature of Staff Member

Page 36: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

3

6

Mobile Application Development

Experiment No: 05

Title:

Download Install and Configure Android Studio on Linux /windows platform.

Problem Definition:

Install and Configure Android Studio on Linux.

1.1 Prerequisite:

Basic concepts of Installation and Configuration of Android Studio on Linux.

Concepts of Android Platform Architecture and component of Android.

1.2 Software Requirements:

Android Studio

1.3 Tools/Framework/Language Used:

Android Studio

1.4 Hardware Requirement:

PIV, 4GB RAM, 500 GB HDD, Lenovo A13-4089 Model

1.5 Learning Objectives:

Install and Configure Android Studio on Linux.

1.6 Outcomes:

After completion of this assignment student are able to Understand How to Install and

Configure Android Studio on Linux and Android Platform Architecture.

1.7 Theory Concepts:

Android is a complete set of software for mobile devices such as tablet computers,

notebooks, smartphones, electronic book readers, set-top boxes etc. It contains a Linux-based

Operating System, middleware and key mobile applications. It can be thought of as a mobile

operating system. But it is not limited to mobile only. It is currently used in various devices such as

mobiles, tablets, televisions etc.

History of Android

The history and versions of android are interesting to know. The code names of android

ranges from A to J currently, such as Aestro, Blender, Cupcake, Donut, Eclair,

Froyo,Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat and Lollipop. Let's

understand the android history in a sequence.

1) Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States in

Page 37: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

3

7

October, 2003.

2) In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary of

Google Incorporation.

3) The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris White and

Nick Sears.

4) Originally intended for camera but shifted to smart phones later because of low market for

camera only.

5) Android is the nick name of Andy Rubin given by coworkers because of his love to robots.

6) In 2007, Google announces the development of android OS.

7) In 2008, HTC launched the first android mobile.

Android Architecture

android architecture or Android software stack is categorized into five parts:

1. linux kernel

2. native libraries (middleware),

3. Android Runtime

4. Application Framework

5. Applications

Let's see the android architecture first.

Page 38: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

3

8

Page 39: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

3

9

1) Linux kernel

It is the heart of android architecture that exists at the root of android architecture. Linux

kernel is responsible for device drivers, power management, memory management, device

management and resource access.

2) Native Libraries

On the top of linux kernel, their are Native libraries such as WebKit, OpenGL, FreeType,

SQLite, Media, C runtime library (libc) etc. The WebKit library is responsible for browser support,

SQLite is for database, FreeType for font support, Media for playing and recording audio and video

formats.

3) Android Runtime

In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is

responsible to run android application. DVM is like JVM but it is optimized for mobile devices. It

consumes less memory and provides fast performance.

4) Android Framework

On the top of Native libraries and android runtime, there is android framework. Android

framework includes Android API's such as UI (User Interface), telephony, resources, locations,

Content Providers (data) and package managers. It provides a lot of classes and interfaces for

android application development.

5) Applications

On the top of android framework, there are applications. All applications such as home,

contact, settings, games, browsers are using android framework that uses android runtime and

libraries. Android runtime and native libraries are using linux kernal.

An Android component is simply a piece of code that has a well-defined life cycle e.g. Activity,

Receiver, Service etc.

Page 40: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

4

0

The core building blocks or fundamental components of android are activities, views, intents,

services, content providers, fragments and AndroidManifest.xml.

Activity

An activity is a class that represents a single screen. It is like a Frame in AWT.

View

A view is the UI element such as button, label, text field etc. Anything that you see is a view.

Intent

Intent is used to invoke components. It is mainly used to:

o Start the service

o Launch an activity

o Display a web page

o Display a list of contacts

o Broadcast a message

o Dial a phone call etc.

For example, you may write the following code to view the webpage.

1. Intent intent=new Intent(Intent.ACTION_VIEW);

2. intent.setData(Uri.parse("http://www.javatpoint.com"));

3. startActivity(intent);

Service

Service is a background process that can run for a long time. There are two types of services

local and remote. Local service is accessed from within the application whereas remote service

is accessed remotely from other applications running on the same device.

Content Provider

Content Providers are used to share data between the applications.

Fragment

Fragments are like parts of activity. An activity can display one or more fragments on the

screen at the same time.

Page 41: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

4

1

AndroidManifest.xml

It contains informations about activities, content providers, permissions etc. It is like the

web.xml file in Java EE.

Android Virtual Device (AVD)

It is used to test the android application without the need for mobile or tablet etc. It can

be created in different configurations to emulate different types of real devices.

Android Emulator is used to run, debug and test the android application. If you don't have the

real device, it can be the best way to run, debug and test the application.

It uses an open source processor emulator technology called QEMU.

The emulator tool enables you to start the emulator from the command line. You need to

write: emulator -avd <AVD NAME>

In case of Eclipse IDE, you can create AVD by Window menu > AVD Manager > New.

In the given image, you can see the android emulator, it displays the output of the hello android example.

Dalvik Virtual Machine | DVM

As we know the modern JVM is high performance and provides excellent memory

management. But it needs to be optimized for low-powered handheld devices as well.

The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices. It

optimizes the virtual machine for memory, battery life and performance.

Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.

The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple class

files are converted into one dex file.

Let's see the compiling and packaging process from the source file:

Page 42: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

4

2

The javac tool compiles the java source file into the class file.

The dx tool takes all the class files of your application and generates a single .dex file. It is a

platform- specific tool.

The Android Assets Packaging Tool (aapt) handles the packaging process.

Internal details or working of hello android example.

Page 43: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

4

3

Android Studio is the premier tool produced by Google for creating Android apps and it more than

matches that other IDE used by Microsoft developers for creating Windows phone apps.

Step-1

Download And Install Android Studio

The first tool you need to download is of course Android Studio. You can download Android Studio

from the following website: https://developer.android.com/studio/index.html

A green download button will appear and it will automatically detect that you are using

Linux. A terms and conditions window will appear and you need to accept the agreement.

The file will now start to download.

When the file has completely downloaded open a terminal window.

Now type the following command to get the name of the file that was downloaded:

ls ~/Downloads

A file should appear with a name which looks something like

this: android-studio-ide-143.2915827-linux.zip

Extract the zip file by running the following command:

sudo unzip android-studio-ide-143.2915827-linux.zip -d /opt

Replace the android filename with the one listed by the ls

command.

Page 44: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory [SD Module-01]

4

4

Step-2

Run Android Studio

To run Android Studio navigate to the /opt/android-studio/bin folder using the cd command:

cd /opt/android-studio/bin

Then run the following command:

sh studio.sh

A screen will appear asking whether you want to import settings. Choose the second option

which reads as "I do not have a previous version of Studio or I do not want to import my

settings".

This will be followed by a Welcome screen.

Click "Next" to continue

Step-4

Choose an Installation Type

Screen will appear with options for choosing standard settings or custom settings.

Choose the standard settings option and click "Next".

The next screen shows a list of components which will be downloaded.

Page 45: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

The download size is quite large and is over 600 megabytes.

Click "Next" to continue.

Now, click "Finish".

Step-5

Creating Your First Project

A screen will appear with options for creating a new project and opening

existing projects. Choose the start a new project link.

A screen will appear with the following

fields:

Application name

Company

domain Project

location

For this example change the application name to "HelloWorld" and leave the rest as the

defaults. Click "Next"

Step-6

Choose Which Android Devices To Target

You can now choose which type of Android device you

wish to target.

The options are as follows:

Phone/Tablet

Page 46: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Wear

TV

Android

Auto Glass

For each option, you can choose the version of Android to target.

If you choose "Phone and Tablet" and then look at the minimum SDK options you will see

that for each option you choose it will show you how many devices will be able to run your

app.

I chose 4.1 Jellybean as it covers over 90% of the market but isn't too far behind.

Click "Next"

Step-7

Choose An Activity

A screen will appear asking for you to choose an activity.

An activity in its simplest form is a screen and the one you choose here will act as your

main activity.

Choose "Basic Activity" and click "Next".

You can now give the activity a name and a title.

For this example leave them as they are and click "Finish".

Page 47: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Step-8

How to Run Project

Android Studio will now load and you can run the default project that has been set up by

pressing shift and F10.

You will be asked to select a deployment target.

The first time you run Android Studio there won't be a target.

Click the "Create New Emulator" button.

Page 48: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Step-9

Choose A Device To Emulate

A list of devices will appear and you can choose one to use as a test device.

Don't worry you don't need the actual device as the phone or tablet will be emulated by

your computer.

When you have chosen a device click "Next".

A screen will appear with recommended download options. Click the download link next

to one of the options for a version of Android at the same SDK as your project target or

higher.

This causes a new download to occur.

Click "Next".

You will now be back at the choose a deployment target screen. Select the phone or tablet

you downloaded and click OK.

1.8 Assignment Question?

1. Explain Android ActivityLifecycle?

2. Explain Android Fragment?

3. Explain Android Application Architecture?

4. What are the code names of android?

5. Explain Android Widget?

Page 49: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

1.9 Oral Question?

1. What is current version of Android ?

2. What is difference between Android and ios ?

3. Who is founder of Android ?

4. Does android support other language than java?

5. What is Activity?

Page 50: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Experiment No: 06

Title:

Roll No:________ Class:_____ Batch:_____

Date of Performance: ___ /___/_____

Date of Assessment: ___ /___/_____

Particulars Marks

Attendance (05)

Journal (05)

Performance (05)

Understanding(05)

Total (20)

Signature of Staff Member

Page 51: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Experiment No: 06

Title:

Design a mobile app for media player.

Problem Definition:

Implementing media player for Audio and Video.

1.1 Prerequisite:

Concepts of MediaPlayer Class.

Basic concepts of Media Player Audio and Video.

1.2 Software Requirements:

Android Studio

1.3 Tools/Framework/Language Used:

Android Studio

1.4 Hardware Requirement:

PIV, 4GB RAM, 500 GB HDD, Lenovo A13-4089 Model

1.5 Learning Objectives:

Implementing arrayadapter and mediaplayer class.

1.6 Outcomes:

After completion of this assignment student are able to Implement Media player.

1.7 Theory Concepts:

Android Media Player Example

We can play and control the audio files in android by the help of MediaPlayer class.

Simple example to play the audio file. In the next page, control the audio playback like start,

stop, pause etc.

MediaPlayer class

The android.media.MediaPlayer class is used to control the audio or video files.

Methods of MediaPlayer class

There are many methods of MediaPlayer class. Some of them are as follows:

Page 52: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Method Description

public void setDataSource(String

path)

Sets the data source (file path or http

url) to use.

public void prepare() Prepares the player for playback

synchronously.

public void start() It starts or resumes the playback.

public void stop() It stops the playback.

public void pause() It pauses the playback.

public boolean isPlaying() Checks if media player is playing.

public void seekTo(int millis) Seeks to specified time in milliseconds.

public void setLooping(boolean

looping)

Sets the player for looping or non-

looping.

public boolean isLooping() Checks if the player is looping or non-

looping.

public void selectTrack(int index) It selects a track for the specified index.

public int getCurrentPosition() Returns the current playback position.

public int getDuration() Returns duration of the file.

public void setVolume(float

leftVolume,float rightVolume)

Sets the volume on this player.

Android Video Player Example

By the help of MediaController and VideoView classes, we can play the video files in android.

MediaController class

The android.widget.MediaController is a view that contains media controls like play/pause,

previous, next, fast-forward, rewind etc.

VideoView class

The android.widget.VideoView class provides methods to play and control the video player.

The commonly used methods of VideoView class are as follows:

Page 53: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Method Description

Public void

setMediaController(MediaContro

ller controller)

Sets the media controller to the video view.

public void setVideoURI (Uri uri) Sets the URI of the video file.

public void start() Starts the video view.

public void stopPlayback() Stops the playback.

public void pause() Pauses the playback.

public void suspend() Suspends the playback.

public void resume() Resumes the playback.

public void seekTo(int millis) Seeks to specified time in milliseconds.

1.8 Assignment Question?

1. Explain ArrayAdapter Class?

2. Explain MediaPlayer Class?

3. Explain VideoView Class?

4. Explain ListView Class?

5. Explain MediaRecorder Class?

Page 54: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Experiment No: 07

Title:

Roll No: ________ Class: _____ Batch: _____

Date of Performance: ___ /___/_____

Date of Assessment: ___ /___/_____

Particulars Marks

Attendance (05)

Journal (05)

Performance (05)

Understanding(05)

Total (20)

Signature of Staff Member

Page 55: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Experiment No: 07

Title:

Design a mobile app to store data using internal or external storage.

Problem Definition:

Implement app to store data using internal or external storage.

1.1 Prerequisite:

Basic concepts of internal or external storage.

Basic Concept of Internal and External Memory.

1.2 Software Requirements:

Android Studio

1.3 Tools/Framework/Language Used:

Android Studio

1.4 Hardware Requirement:

PIV, 4GB RAM, 500 GB HDD, Lenovo A13-4089 Model

1.5 Learning Objectives:

Implement app to store data using internal or external storage.

1.6 Outcomes:

After completion of this assignment student are able to Implement App to store data using

internal or external storage.

1.7 Theory Concepts:

Android Preferences Example

Android shared preference is used to store and retrieve primitive information. In android,

string, integer, long, number etc. are considered as primitive data type.

Android Shared preferences are used to store data in key and value pair so that we can retrieve the

value on the basis of key.

Android provides many kinds of storage for applications to store their data. These storage places

are shared preferences, internal and external storage, SQLite storage, and storage via network

connection.

It is widely used to get information from user such as in settings.

Page 56: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

FileOutputStream fOut = openFileOutput("file name here",MODE_WORLD_READABLE);

Android Internal Storage Example

We are able to save or read data from the device internal memory. FileInputStream and

FileOutputStream classes are used to read and write data into the file.

Here, we are going to read and write data to the internal storage of the device.

In order to use internal storage to write some data in the file, call the openFileOutput() method

with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is given

below –

Reading file

In order to read from the file you just created , call the openFileInput() method with the

name of the file. It returns an instance of FileInputStream. Its syntax is given below −

Methods of write and close, there are other methods provided by the FileOutputStream class for

better writing files. These methods are listed below −

Sr.No Method & description

1 FileOutputStream(File file, boolean append)

This method constructs a new FileOutputStream that writes to file.

2 getChannel()

This method returns a write-only FileChannel that shares its

position with this stream

3 getFD()

This method returns the underlying file descriptor

4 write(byte[] buffer, int byteOffset, int byteCount)

This method Writes count bytes from the byte array buffer starting

at position offset to this stream

Apart from the the methods of read and close, there are other methods provided

by the FileInputStream class for better reading files. These methods are listed below –

Page 57: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Sr.No Method & description

1 available()

This method returns an estimated number of bytes that can be

read or skipped without blocking for more input

2 getChannel()

This method returns a read-only FileChannel that shares its

position with this stream

3 getFD()

This method returns the underlying file descriptor

4 read(byte[] buffer, int byteOffset, int byteCount)

This method reads at most length bytes from this stream and

stores them in the byte array b starting at offset

Android External Storage Example

Like internal storage, we are able to save or read data from the device external memory such

as sdcard. The FileInputStream and FileOutputStream classes are used to read and write data into

the file.

1.8 Assignment Question?

1. Explain getExternalstorageDirectory()?

2. What is difference between Internal and External memory?

3. What is the use of shared preference in Android and where are they stored?

4. What do you mean content provider?

5. Explain getPath method?

Page 58: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Experiment No: 08

Title:

Roll No:________ Class:_____ Batch:_____

Date of Performance: ___ /___/_____

Date of Assessment: ___ /___/_____

Particulars Marks

Attendance (05)

Journal (05)

Performance (05)

Understanding(05)

Total (20)

Signature of Staff Member

Page 59: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Experiment No: 08

Title:

Design a mobile app using Google Map and GPS to trace the location.

Problem Definition:

Implement app to using Google Map and GPS to trace the location.

1.1 Prerequisite:

Basic concepts of Google Map.

Basic Concept of GPS for trace location.

1.2 Software Requirements:

Android Studio

1.3 Tools/Framework/Language Used:

Android Studio

1.4 Hardware Requirement:

PIV, 4GB RAM, 500 GB HDD, Lenovo A13-4089 Model

1.5 Learning Objectives:

Implement app to using Google Map and GPS to trace the location.

1.6 Outcomes:

After completion of this assignment student are able to Implement App to using Google Map and

GPS to trace the location

1.7 Theory Concepts

Android application which will display latitude and longitude of the current location in a text

view and corresponding location in the Google Map. The current location will be retrieved using GPS

and LocationManager API of the Android.

Location

public class Location

extends Object implements Parcelable

java.lang.Object

↳ android.location.Location

Page 60: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

LocationManager

public class LocationManager

extends Object java.lang.Object

↳ android.location.LocationManager

This class provides access to the system location services. These services allow applications to

obtain periodic updates of the device's geographical location, or to fire an application-specified Intent

when the device enters the proximity of a given geographical location.

Unless noted, all Location API methods require

The ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATIONpermissions. If your application only has

the coarse permission then it will not have access to the GPS or passive location providers. Other

providers will still return location results, but the update rate will be throttled and the exact location

will be obfuscated to a coarse level of accuracy.

Instances of this class must be obtained using Context.getSystemService(Class) with

the argumentLocationManager.class or Context.getSystemService(String) with the

argument Context.LOCATION_SERVICE.

LocationProvider

public class LocationProvider

extends Object java.lang.Object

↳ android.location.LocationProvider

An abstract superclass for location providers. A location provider provides periodic reports on

the geographical location of the device.

Each provider has a set of criteria under which it may be used; for example, some providers

require GPS hardware and visibility to a number of satellites; others require the use of the cellular

radio, or access to a specific carrier's network, or to the internet. They may also have different battery

consumption characteristics or monetary costs to the user. The Criteria class allows providers to be

selected based on user-specified criteria.

Page 61: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

LocationManager Methods:-

Public methods

boolean addGpsStatusListener(GpsStatus.Listener listener)

This method was deprecated in API

useregisterGnssStatusCallback(GnssStatus.Callback)

instead.

level

24.

boolean addNmeaListener(OnNmeaMessageListener listener, Handler handler)

Adds an NMEA listener.

boolean addNmeaListener(OnNmeaMessageListener listener)

Adds an NMEA listener.

boolean addNmeaListener(GpsStatus.NmeaListener listener)

This method was deprecated in API

useaddNmeaListener(OnNmeaMessageListener)

instead.

level

24.

void addProximityAlert(double latitude, double longitude, float radius, long

expiration, PendingIntent intent)

Set a proximity alert for the location given by the position (latitude,

longitude) and the given radius.

void addTestProvider(String name, boolean requiresNetwork, boolean

requiresSatellite, boolean requiresCell, boolean hasMonetaryCost,

boolean supportsAltitude, boolean supportsSpeed, boolean

supportsBearing, int powerRequirement, int accuracy)

Creates a mock location provider and adds it to the set of active

providers.

void clearTestProviderEnabled(String provider)

Removes any mock enabled value associated with the given provider.

void clearTestProviderLocation(String provider)

Removes any mock location associated with the given provider.

void clearTestProviderStatus(String provider)

Removes any mock status values associated with the given provider.

Page 62: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

List<String> getAllProviders()

Returns a list of the names of all known location providers.

String getBestProvider(Criteria criteria, boolean enabledOnly)

Returns the name of the provider that best meets the given criteria.

GpsStatus getGpsStatus(GpsStatus status)

Retrieves information about the current status of the GPS engine.

Location getLastKnownLocation(String provider)

Returns a Location indicating the data from the last known location fix

obtained from the given provider.

LocationProvi getProvider(String name)

der Returns the information associated with the location provider of the

given name, or null if no provider exists by that name.

List<String> getProviders(Criteria criteria, boolean enabledOnly)

Returns a list of the names of LocationProviders that satisfy the given

criteria, or null if none do.

List<String> getProviders(boolean enabledOnly)

Returns a list of the names of location providers.

boolean isProviderEnabled(String provider)

Returns the current enabled/disabled status of the given provider.

boolean registerGnssMeasurementsCallback(GnssMeasurementsEvent.Callback

cal lback,Handler handler)

Registers a GPS Measurement callback.

boolean registerGnssMeasurementsCallback(GnssMeasurementsEvent.Callback

cal lback)

Registers a GPS Measurement callback.

boolean registerGnssNavigationMessageCallback(GnssNavigationMessage.Callb

ac k callback,Handler handler)

Registers a GNSS Navigation Message callback.

boolean registerGnssNavigationMessageCallback(GnssNavigationMessage.Callb

ac k callback)

Page 63: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

Registers a GNSS Navigation Message callback.

boolean registerGnssStatusCallback(GnssStatus.Callback callback)

Registers a GNSS status callback.

boolean registerGnssStatusCallback(GnssStatus.Callback callback, Handler

handle r)

Registers a GNSS status callback.

void removeGpsStatusListener(GpsStatus.Listener listener)

This method was deprecated in API level 24.

useunregisterGnssStatusCallback(GnssStatus.Callback) instead.

void removeNmeaListener(OnNmeaMessageListener listener)

Removes an NMEA listener.

void removeNmeaListener(GpsStatus.NmeaListener listener)

This method was deprecated in API level 24.

useremoveNmeaListener(OnNmeaMessageListener) instead.

void removeProximityAlert(PendingIntent intent)

Removes the proximity alert with the given PendingIntent.

void removeTestProvider(String provider)

Removes the mock location provider with the given name.

void removeUpdates(LocationListener listener)

Removes all location updates for the specified LocationListener.

void removeUpdates(PendingIntent intent)

Removes all location updates for the specified pending intent.

void requestLocationUpdates(String provider, long minTime,

float

minDistance,LocationListener listener)

Register for location updates using the named provider, and a pending

intent.

Page 64: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Skill Development Laboratory

void requestLocationUpdates(long minTime,

float minDistance, Criteria

criteria,LocationListener listener, Looper looper) Register for location

updates using a Criteria, and a callback on the specified looper thread.

void requestLocationUpdates(long minTime,

float minDistance, Criteria

criteria,PendingIntent intent)

Register for location updates using a Criteria and pending intent.

void requestLocationUpdates(String provider, long minTime,

float

minDistance,LocationListener listener, Looper looper)

Register for location updates using the named provider, and a callback

on the specified looper thread.

void requestLocationUpdates(String provider, long minTime,

float

minDistance,PendingIntent intent)

Register for location updates using the named provider, and a pending

intent.

void requestSingleUpdate(String provider, PendingIntent intent)

Register for a single location update using a named provider and pending

intent.

void requestSingleUpdate(String provider, LocationListener listener, Looper

loo per)

Register for a single location update using the named provider and a

callback.

void requestSingleUpdate(Criteria criteria, LocationListener listener,

Looperloo per)

Register for a single location update using a Criteria and a callback.

void requestSingleUpdate(Criteria criteria, PendingIntent intent)

Register for a single location update using a Criteria and pending intent.

boolean sendExtraCommand(String provider, String command, Bundle extras)

Page 65: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

Sends additional commands to a location provider.

void setTestProviderEnabled(String provider, boolean

enabled) Sets a mock enabled value for the given

provider.

void setTestProviderLocation(String provider, Location

loc) Sets a mock location for the given provider.

void setTestProviderStatus(String provider, int status, Bundle extras,

long updateTime)

Sets mock status values for the given provider.

void unregisterGnssMeasurementsCallback(GnssMeasurementsEvent.Callba

ck callback)

Unregisters a GPS Measurement callback.

void unregisterGnssNavigationMessageCallback(GnssNavigationMessage.Callb

ackcallback)

Unregisters a GNSS Navigation Message callback.

void unregisterGnssStatusCallback(GnssStatus.Callback callback)

Removes a GNSS status callback.

Permission Required for GPS Tracking

Only fine location will allow you access to gps data, and allows you access to

everything else coarse location gives. You can use the methods of the

LocationManager to acquire location data from gps and cell tower sources already,

you do not have to work out this information yourself.

The main permissions you need are

android.permission.ACCESS_COARSE_LOCATION or

android.permission.ACCESS_FINE_LOCAT ION.

This permission should allow your app to use location services through the devices

GPS, wifi, and cell towers. Just plop it in your manifest wherever you put your

Page 66: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

permissions, and it should do the trick. You can find all the other permissions here:

(http://developer.android.com/reference/android/Manifest.permission.html)

Here is the code:

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

LocationListener

public interface

LocationListener

android.location.LocationList

ener

Used for receiving notifications from the LocationManager when the location

has changed. These methods are called if the LocationListener has been registered

with the location manager service using the requestLocationUpdates(String, long,

float, LocationListener) method.

Public methods

abstract void onLocationChanged(Location location)

Called when the location has changed.

abstract void onProviderDisabled(String provider)

Called when the provider is disabled by the user.

abstract void onProviderEnabled(String provider)

Called when the provider is enabled by the user.

abstract void onStatusChanged(String provider,

in

t status, Bundle extras)

Called when the provider status changes.

onLocationChanged

void onLocationChanged

Page 67: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

(Location location) Called

when the location has

changed.

There are no restrictions on the use of the supplied Location object.

Parameters

location Location: The new location, as a Location object.

onProviderDisabled

void onProviderDisabled (String provider)

Called when the provider is disabled by the user. If requestLocationUpdates is called

on an already disabled provider, this method is called immediately.

Parameters

provider String: the name of the location provider associated with this update.

onProviderEnabled

void onProviderEnabled

(String provider) Called when

the provider is enabled by

the user.

Parameters

provider String: the name of the location provider associated with this update.

onStatusChanged

void onStatusChanged (String provider, int status,Bundle extras)

Called when the provider status changes. This method is called when a provider is

unable to fetch a location or if the provider has recently become available after a

period of unavailability.

Parameters

providerString: the name of the location provider associated with this update.

Page 68: Skill Development Laboratory · 2018-07-16 · Skill Development Laboratory [SD Module-I] TE Computer Engineering Page 7 Introduction to Generics The Java Generics programming is

statusint: OUT_OF_SERVICE if the provider is out of service, and this is not expected

to change in the near future; TEMPORARILY_UNAVAILABLE if the provider is

temporarily unavailable but is expected to be available shortly; and AVAILABLE if the

provider is currently available.

extrasBundle: an optional Bundle which will contain provider specific status variables.

A number of common key/value pairs for the extras Bundle are listed below.

Providers that use any of the keys on this list must provide the corresponding value

as described below.

satellites - the number of satellites used to derive the fix

1.8 Assignment Question?

1. Explain important steps for Trace the location using Google Map?

2. Explain important steps for Trace the location using GPS?

3. What are different types of sensors available in mobile device?

4. Explain onProviderDisabled and onProviderEnabled method?

5. Explain location.getLatitude() and location.getLongitude()?