0% found this document useful (0 votes)
102 views42 pages

3161612-Mad Index Practical File

The document describes creating an Android calculator application. It includes the layout file activity_main.xml which contains two EditText fields for user input, a TextView to display the answer, and four buttons for the operations - add, subtract, multiply and divide. The MainActivity.java file finds the views by id, sets onClickListeners for the buttons, parses the EditText values to integers, performs the selected operation on the values, and sets the result to the TextView. OnClick methods for add, subtract and multiply operations are included to demonstrate the logic. The application allows users to enter two numbers in EditText fields, select an operation button, and displays the result of that operation

Uploaded by

Krupa Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views42 pages

3161612-Mad Index Practical File

The document describes creating an Android calculator application. It includes the layout file activity_main.xml which contains two EditText fields for user input, a TextView to display the answer, and four buttons for the operations - add, subtract, multiply and divide. The MainActivity.java file finds the views by id, sets onClickListeners for the buttons, parses the EditText values to integers, performs the selected operation on the values, and sets the result to the TextView. OnClick methods for add, subtract and multiply operations are included to demonstrate the logic. The application allows users to enter two numbers in EditText fields, select an operation button, and displays the result of that operation

Uploaded by

Krupa Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

M A D HU B EN & B HA NU BH A I PA TEL I NS T ITUT E OF TE C HN OL O G Y

D E P A R T M E N T O F INFORMATION TECHNOLOGY

V ISIO N
To impart quality education through state-of-the-art technologies to achieve academic
excellence for transforming students into innovators.

MISSION

To impart quality education through state-of-the-art technologies to achieve academic


excellence for transforming students into innovators.

Creating a teaching-learning environment to produce industry ready and self-confident


graduates. Motivate students to engage in creative projects throughout graduation.

To produce competitive graduates having creative skills and ethical values to succeed in their
fields as well as the foundation for life-long learning.

P RO G R A M E D U C A T I O N AL O B J EC T IV ES ( P EO )
1. To provide students with strong basic and advanced programming concepts so that they can
build solutions or systems for complex problems.
2. The program provides the fundamental and perspective to attain life-long learning in the
thrust areas of Computer Programming.
3. To produce graduates who have ability to pursue research or have a successful career in
academia or industries or as entrepreneurs.
4. The aim is inculcating technical knowledge of the programme and imbibe ethics with moral
behaviour in the graduates.

P RO G RAM S P EC IF IC O BJ EC TI V ES (P S O )
1. To understand, analyze and develop computer programs in the areas related to algorithms,
system software, multimedia, web design, DBMS, and networking for efficient design of
computer-based systems.
2. To provide solutions for real world problems with a wide range of programming languages
and open-source platforms in various computing domains.
3. To develop an ability to be an entrepreneur.

COU RSE OU TCO M ES (CO )


1. Understand Android architecture, activities, and their life cycle.
2. Use View Groups comprising layouts and Views in application.
3. Manage data binding, user interface events, maps.
4. Work with graphics, animation, still images and video.
5. Publish and distribute Android Application.
DEPARTMENT OF INFORMATION TECHNOLOGY
A . Y . 2 0 2 1 - 2 2 , Even T E R M
MA D H U B EN & BH A N U B H A I P A TE L S U B J E C T C O D E : 3161612
INSTITUTE OF TECHNOLOGY S U B J E CT N A ME :
Mobile Application Development

Name: Enrolment No: Semester:

Sr. DEFINITION Page


No. Date No. Signature Remarks
Download and Install Android Studio with all 1
01
Requirements of SDK Manager.
02 Write an Android application for calculator 4

Write an Android application to convert into


03 7
different currencies for example, Rupees to dollar
Write an Android application to send a data from
one activity another activity. Show data transferred
04 10
from first activity and provide button to go back to
first activity using Intents.
Write an Android application to show use of
05 Fragments in activity by loading another activity in 14
fragment.
Write an Android application to show Layout
06 18
Managers and Event Listeners.
Write an Android application to Draw Basic 22
07
Graphical Primitives.
Write an Android application to Mark a daily route
08 24
on google Map.
Write an Android application that create, sav,
09 update and delete data from Database (using 29
SQLite)
Write an Android Application to Record and Save
10 34
Video.
Date::
Practical – 1
Download and Install Android Studio with all Requirements of SDK
Manager.

Download and Install Android Studio

Go for https://developer.android.com/studio , by accepting agreement Download Link is Enabled.

After the downloading has finished, open the file from downloads and run it to complete Installation.

Then Click on Finish, and Ask for Import Old / available setting.

3161612 – MOBILE APPLICATION DEVELOPMENT 1


Click Ok and Then ANDROID STUDIO will Start with Loading full APP and Also Download required SDK components.

After SDK Components, Redirect to Welcome Dialog box, Click on Next and Ask for Type of Installation
(Standard, Custom)

Choose on Option and click on Next Button and Select Theme and Click Next.

3161612 – MOBILE APPLICATION DEVELOPMENT 2


Now Next Download SDK Components

After Download Completed, Android Studio is ready to build an app.

3161612 – MOBILE APPLICATION DEVELOPMENT 3


Date::
Practical – 2
Write an Android application for calculator

activity_main.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"
tools:context=".MainActivity">

<EditText
android:id="@+id/et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="no1" />

<EditText
android:id="@+id/et2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_below="@id/et1"
android:inputType="textPersonName"
android:text="no2" />

<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/et2"
android:text="Answer" />

<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv1"
android:text="add" />

<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/b1"
android:text="sub" />

<Button
android:id="@+id/b3"
android:layout_width="wrap_content"

3161612 – MOBILE APPLICATION DEVELOPMENT 4


android:layout_height="wrap_content"
android:layout_below="@id/b2"
android:text="mult" />

<Button
android:id="@+id/b4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/b3"
android:text="div" />

</RelativeLayout>

MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

EditText et_1,et_2;
TextView tv_1;
Button b_1,b_2,b_3,b_4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

et_1 = (EditText) findViewById(R.id.et1);


et_2 = (EditText) findViewById(R.id.et2);
tv_1 = (TextView) findViewById(R.id.tv1);
b_1 = (Button) findViewById(R.id.b1);
b_2 = (Button) findViewById(R.id.b2);
b_3 = (Button) findViewById(R.id.b3);
b_4 = (Button) findViewById(R.id.b4);

// add logic
b_1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
int a,b,ans;
a = Integer.parseInt(et_1.getText().toString());
b = Integer.parseInt(et_2.getText().toString());
ans = a+b;
tv_1.setText(ans);
}
});

// sub logic
b_2.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {

3161612 – MOBILE APPLICATION DEVELOPMENT 5


int a,b,ans;
a = Integer.parseInt(et_1.getText().toString());
b = Integer.parseInt(et_2.getText().toString());
ans = a-b;
tv_1.setText(ans);
}
});
// multiplication logic
b_3.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
int a,b,ans;
a = Integer.parseInt(et_1.getText().toString());
b = Integer.parseInt(et_2.getText().toString());
ans = a*b;
tv_1.setText(ans);
}
});
// division logic
b_4.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
int a,b,ans;
a = Integer.parseInt(et_1.getText().toString());
b = Integer.parseInt(et_2.getText().toString());
ans = a/b;
tv_1.setText(ans);
}
});
}
}

Output

3161612 – MOBILE APPLICATION DEVELOPMENT 6


Date::
Practical – 3
Write an Android application to convert into different currencies for
example, Rupees to dollar

activity_main.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"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter Currency in rupees"
android:textSize="20sp"/>
<EditText
android:id="@+id/et1"
android:layout_below="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Enter rs"/>
<Button
android:id="@+id/b1"
android:layout_below="@+id/et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerHorizontal="true"
android:text="CONVERT to Dollars"
android:textSize="20sp" />

<TextView
android:id="@+id/tv2"
android:layout_below="@+id/b1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="20sp"/>

<Button
android:id="@+id/b2"
android:layout_below="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerHorizontal="true"
android:text="CONVERT to POUND"
android:textSize="20sp" />

3161612 – MOBILE APPLICATION DEVELOPMENT 7


<TextView
android:id="@+id/tv3"
android:layout_below="@+id/b2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="20sp"/>
</RelativeLayout>

MainActivity.java
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


EditText et_1;
TextView tv_1,tv_2,tv_3;
Button b_1,b_2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

et_1 = (EditText) findViewById(R.id.et1);


tv_1 = (TextView) findViewById(R.id.tv1);
tv_2 = (TextView) findViewById(R.id.tv2);
b_1 = (Button) findViewById(R.id.b1);
b_2 = (Button) findViewById(R.id.b2);

b_1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
Double a,ans;
a = Double.parseDouble(et_1.getText().toString());
ans = a/76.50;
tv_1.setText(ans.toString());
}
});

// sub logic
b_2.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
Double a,ans;
a = Double.parseDouble(et_1.getText().toString());
ans = a/95;
tv_1.setText(ans.toString());
}
});

}
}

3161612 – MOBILE APPLICATION DEVELOPMENT 8


Output

3161612 – MOBILE APPLICATION DEVELOPMENT 9


Date::
Practical – 4
Write an Android application to send a data from one activity another
activity using Intents. Show data transferred from first activity and
provide button to go back to first activity using Intents. (Send Data using
different Intent and without Intent approaches)

activity_main.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"
tools:context=".MainActivity">
<EditText
android:id="@+id/et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Enter Text" />
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:layout_below="@id/et1"/>
</RelativeLayout>

activity_act2.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"
tools:context=".act2">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
tools:layout_editor_absoluteX="112dp"
tools:layout_editor_absoluteY="44dp" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv1"
android:text="TextView" />

3161612 – MOBILE APPLICATION DEVELOPMENT 10


<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv2"
android:text="TextView" />
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:layout_below="@id/tv3"
tools:layout_editor_absoluteX="163dp"
tools:layout_editor_absoluteY="131dp" />
</RelativeLayout>

MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

EditText et_1;
Button b_1;
private static String s;

public static String getValue() {


return s;
} // type 3 to send
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

et_1 = (EditText) findViewById(R.id.et1);


b_1 = (Button) findViewById(R.id.b1);

b_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
s = et_1.getText().toString();
Intent i = new Intent(MainActivity.this, act2.class);
i.putExtra("s1",s); // type 1 to send
Bundle b = new Bundle(); // type 2 to send
b.putString("s2",s);
i.putExtras(b);
startActivity(i);
}
});
}

3161612 – MOBILE APPLICATION DEVELOPMENT 11


act2.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class act2 extends AppCompatActivity {


TextView tv_1,tv_2,tv_3;
Button b_1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act2);
tv_1 = (TextView) findViewById(R.id.tv1);
tv_2 = (TextView) findViewById(R.id.tv2);
tv_3 = (TextView) findViewById(R.id.tv3);
b_1 = (Button) findViewById(R.id.b1);

Intent i1 = getIntent();
String s1 = i1.getStringExtra("s1");
tv_1.setText(s1); // tv_1 set

Bundle b = i1.getExtras();
if(b != null)
{
String s2 = b.getString("s2");
tv_2.setText(s2); // tv_2 set
}

tv_3.setText(MainActivity.getValue()); //tv_3 set

b_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(act2.this,MainActivity.class);
startActivity(i);
}
});
}
}

3161612 – MOBILE APPLICATION DEVELOPMENT 12


Output

Figure 1- Input String Figure 2- second activity Figure 3- Back to MainActivity

3161612 – MOBILE APPLICATION DEVELOPMENT 13


Date::
Practical – 5
Write an Android application to show use of Fragments in activity by
loading another activity in fragment.

activity_main.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"
tools:context=".MainActivity">

<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="600dp"/>

<Button
android:id="@+id/b1"
android:layout_width="150dp"
android:layout_height="60dp"
android:text="Fragment 1"
android:layout_alignParentBottom="true"/>
<Button
android:id="@+id/b2"
android:layout_width="150dp"
android:layout_height="60dp"
android:text="Fragment 2"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />
</RelativeLayout>

fragment_fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to FRAGMENT1"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"

3161612 – MOBILE APPLICATION DEVELOPMENT 14


android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="MBIT"
android:textAllCaps="true" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="INFORMATION TECHNOLOGY"
android:textStyle="bold"
android:textColor="#fff"
android:background="#7F3AB5"
android:layout_marginBottom="15dp"/>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="email|web"
android:text="6thSem - 3161612" />
</LinearLayout>

fragment_fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to FRAGMENT2"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="MBIT"
android:textAllCaps="true" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="COMPUTER ENGINEERING"
android:textStyle="bold"
android:textColor="#fff"
android:background="#7F3AB5"
android:layout_marginBottom="15dp"/>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="email|web"

3161612 – MOBILE APPLICATION DEVELOPMENT 15


android:text="6thSem " />
</LinearLayout>

MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

b_1 = (Button) findViewById(R.id.b1);


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

b_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fragment1 f1 = new fragment1();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frameLayout,f1);
ft.commit();
}
});
b_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fragment2 f2 = new fragment2();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frameLayout,f2);
ft.commit();
}
});
}
}

fragment1.java
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class fragment1 extends Fragment {

3161612 – MOBILE APPLICATION DEVELOPMENT 16


View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_fragment1, container, false);
return view;
}
}

fragment2.java
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class fragment2 extends Fragment {
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_fragment2, container, false);
return view;
}
}

Output

3161612 – MOBILE APPLICATION DEVELOPMENT 17


Date::
Practical – 6
Write an Android application to show Layout Managers and Event
Listeners.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:text="Details Form"
android:textSize="25sp"
android:gravity="center"/>
</LinearLayout>
<GridLayout
android:id="@+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:layout_marginBottom="200dp"
android:columnCount="2"
android:rowCount="3">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="0"
android:text="Name"
android:textSize="20sp"
android:gravity="center"/>
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="1"
android:ems="10"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"

3161612 – MOBILE APPLICATION DEVELOPMENT 18


android:layout_row="1"
android:layout_column="0"
android:text="Reg.No"
android:textSize="20sp"
android:gravity="center"/>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="1"
android:inputType="number"
android:ems="10"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="0"
android:text="Dept"
android:textSize="20sp"
android:gravity="center"/>
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="1"
android:spinnerMode="dropdown"/>
</GridLayout>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginBottom="150dp"
android:text="Submit"/>
</RelativeLayout>

activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView2"

3161612 – MOBILE APPLICATION DEVELOPMENT 19


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
</LinearLayout>

MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.os.Bundle;
import android.content.Intent;

public class MainActivity extends AppCompatActivity {


EditText e1,e2;
Button bt;
Spinner s;
String [] dept_array={"CSE","ECE","IT","Mech","Civil"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);

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


e2= (EditText) findViewById(R.id.editText2);
bt= (Button) findViewById(R.id.button);
s= (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter= new
ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item,dept_arra
s.setAdapter(adapter);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Getting the Values from Views(Edittext & Spinner)
name=e1.getText().toString();
reg=e2.getText().toString();
dept=s.getSelectedItem().toString();
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("name_key", name);
i.putExtra("reg_key",reg);
i.putExtra("dept_key", dept);
startActivity(i);
}
});
}
}

3161612 – MOBILE APPLICATION DEVELOPMENT 20


activity_second.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.os.Bundle;

public class activity_second extends AppCompatActivity {


TextView t1,t2,t3;
String name,reg,dept;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
t1= (TextView) findViewById(R.id.textView1);
t2= (TextView) findViewById(R.id.textView2);
t3= (TextView) findViewById(R.id.textView3);
Intent i = getIntent();
name=i.getStringExtra("name_key");
reg=i.getStringExtra("reg_key");
dept=i.getStringExtra("dept_key");
//Setting the Values to Intent
t1.setText(name);
t2.setText(reg);
t3.setText(dept);
}
}

Output

3161612 – MOBILE APPLICATION DEVELOPMENT 21


Date::
Practical – 7
Write an Android application to Draw Basic Graphical Primitives.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="@+id/imageView_graphics"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="13dp" />
</LinearLayout>

MainActivity.java
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
import android.graphics.drawable.BitmapDrawable;

public class MainActivity extends AppCompatActivity {


TextView t1,t2,t3;
String name,reg,dept;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);

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

//Setting the Bitmap as background for the ImageView


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

//Creating the Canvas Object


Canvas canvas = new Canvas(bg);

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

3161612 – MOBILE APPLICATION DEVELOPMENT 22


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

//To draw a Circle


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

//To draw a Square


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

//To draw a Line


canvas.drawText("Line", 480, 800, paint);
canvas.drawLine(520, 850, 520, 1150, paint);
}
}

Output

3161612 – MOBILE APPLICATION DEVELOPMENT 23


Date::
Practical – 8
Write an Android application to Mark a daily route on google Map.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.students.ameer.findroutes">

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


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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyD4uStbluZBnwKADWRtCPalZoddDXdNQbs" />
<!-- Don't use my api key, it will not work for you.-->

<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

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

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


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

</manifest>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".MainActivity">

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

3161612 – MOBILE APPLICATION DEVELOPMENT 24


android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".MainActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.directions.route.AbstractRouting;
import com.directions.route.Route;
import com.directions.route.RouteException;
import com.directions.route.Routing;
import com.directions.route.RoutingListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;
import java.util.List;

public class MainActivity2 extends AppCompatActivity,FragmentActivity implements


OnMapReadyCallback,
GoogleApiClient.OnConnectionFailedListener, RoutingListener {
//google map object
private GoogleMap mMap;

//current and destination location objects


Location myLocation=null;
Location destinationLocation=null;
protected LatLng start=null;
protected LatLng end=null;

//to get location permissions.


private final static int LOCATION_REQUEST_CODE = 23;
boolean locationPermission=false;

//polyline object

3161612 – MOBILE APPLICATION DEVELOPMENT 25


private List<Polyline> polylines=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//request location permission.
requestPermision();

//init google map fragment to show map.


SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

private void requestPermision()


{
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
LOCATION_REQUEST_CODE);
}
else{
locationPermission=true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
switch (requestCode) {
case LOCATION_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//if permission granted.
locationPermission=true;
getMyLocation();

} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}

//to get user location


private void getMyLocation(){
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {

myLocation=location;
LatLng ltlng=new LatLng(location.getLatitude(),location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
ltlng, 16f);
mMap.animateCamera(cameraUpdate);

3161612 – MOBILE APPLICATION DEVELOPMENT 26


}
});

//get destination location when user click on map


mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
end=latLng;
mMap.clear();
start=new LatLng(myLocation.getLatitude(),myLocation.getLongitude());
//start route finding
Findroutes(start,end);
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

if(locationPermission) {
getMyLocation();
}
}

// function to find Routes.


public void Findroutes(LatLng Start, LatLng End)
{
if(Start==null || End==null) {
Toast.makeText(MainActivity.this,"Unable to get location",
Toast.LENGTH_LONG).show();
}
else
{

Routing routing = new Routing.Builder()


.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(true)
.waypoints(Start, End)
.key("AIzaSyD4uStbluZBnwKADWRtCPalZoddDXdNQbs") //also define your api
key here.
.build();
routing.execute();
}
}

//Routing call back functions.


@Override
public void onRoutingFailure(RouteException e) {
View parentLayout = findViewById(android.R.id.content);
Snackbar snackbar= Snackbar.make(parentLayout, e.toString(), Snackbar.LENGTH_LONG);
snackbar.show();
// Findroutes(start,end);
}

@Override
public void onRoutingStart() {
Toast.makeText(MainActivity.this,"Finding Route...",Toast.LENGTH_LONG).show();
}

//If Route finding success..

3161612 – MOBILE APPLICATION DEVELOPMENT 27


@Override
public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {

CameraUpdate center = CameraUpdateFactory.newLatLng(start);


CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
if(polylines!=null) {
polylines.clear();
}
PolylineOptions polyOptions = new PolylineOptions();
LatLng polylineStartLatLng=null;
LatLng polylineEndLatLng=null;

polylines = new ArrayList<>();


//add route(s) to the map using polyline
for (int i = 0; i <route.size(); i++) {
if(i==shortestRouteIndex)
{
polyOptions.color(getResources().getColor(R.color.colorPrimary));
polyOptions.width(7);
polyOptions.addAll(route.get(shortestRouteIndex).getPoints());
Polyline polyline = mMap.addPolyline(polyOptions);
polylineStartLatLng=polyline.getPoints().get(0);
int k=polyline.getPoints().size();
polylineEndLatLng=polyline.getPoints().get(k-1);
polylines.add(polyline);
}
else {
}

//Add Marker on route starting position


MarkerOptions startMarker = new MarkerOptions();
startMarker.position(polylineStartLatLng);
startMarker.title("My Location");
mMap.addMarker(startMarker);
//Add Marker on route ending position
MarkerOptions endMarker = new MarkerOptions();
endMarker.position(polylineEndLatLng);
endMarker.title("Destination");
mMap.addMarker(endMarker);
}
@Override
public void onRoutingCancelled() {
Findroutes(start,end);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Findroutes(start,end);

}
}

3161612 – MOBILE APPLICATION DEVELOPMENT 28


Date::
Practical – 9
Write an Android application that create, save, update and delete data
from Database (using SQLite)

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50dp"
android:layout_y="20dp"
android:text="Student Details"
android:textSize="30sp" />
<TextView
android:id="@+id/tv2"
android:layout_below="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="110dp"
android:text="Enter Rollno:"
android:textSize="20sp" />
<EditText
android:id="@+id/Rollno"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="100dp"
android:inputType="number"
android:textSize="20sp" />
<TextView
android:id="@+id/tv3"
android:layout_below="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="160dp"
android:text="Enter Name:"
android:textSize="20sp" />
<EditText
android:id="@+id/Name"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="150dp"
android:inputType="text"
android:textSize="20sp" />
<TextView
android:id="@+id/tv4"

3161612 – MOBILE APPLICATION DEVELOPMENT 29


android:layout_below="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="210dp"
android:text="Enter Marks:"
android:textSize="20sp" />
<EditText
android:id="@+id/Marks"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="200dp"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="@+id/Insert"
android:layout_below="@+id/tv4"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="300dp"
android:text="Insert"
android:textSize="30dp" />

<Button
android:id="@+id/Delete"
android:layout_below="@+id/tv4"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/Insert"
android:layout_x="200dp"
android:layout_y="300dp"
android:text="Delete"
android:textSize="30dp" />
<Button
android:id="@+id/Update"
android:layout_below="@+id/Insert"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="400dp"
android:text="Update"
android:textSize="30dp" />
<Button
android:id="@+id/View"
android:layout_below="@+id/Insert"
android:layout_toEndOf="@id/Update"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="400dp"
android:text="View"
android:textSize="30dp" />
<Button
android:id="@+id/ViewAll"
android:layout_below="@+id/Update"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_x="100dp"
android:layout_y="500dp"

3161612 – MOBILE APPLICATION DEVELOPMENT 30


android:text="View All"
android:textSize="30dp" />
</RelativeLayout>

MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


EditText Rollno,Name,Marks;
Button Insert,Delete,Update,View,ViewAll;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);

Rollno=(EditText)findViewById(R.id.Rollno);
Name=(EditText)findViewById(R.id.Name);
Marks=(EditText)findViewById(R.id.Marks);
Insert=(Button)findViewById(R.id.Insert);
Delete=(Button)findViewById(R.id.Delete);
Update=(Button)findViewById(R.id.Update);
View=(Button)findViewById(R.id.View);
ViewAll=(Button)findViewById(R.id.ViewAll);
Insert.setOnClickListener(this);
Delete.setOnClickListener(this);
Update.setOnClickListener(this);
View.setOnClickListener(this);
ViewAll.setOnClickListener(this);
db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR," + "marks
VARCHAR);");
}
public void onClick(View view)
{
if(view==Insert)
{
if(Rollno.getText().toString().trim().length()==0||
Name.getText().toString().trim().length()==0|| Marks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values"); return;
}
db.execSQL("INSERT INTO student VALUES('"+Rollno.getText()+"','"+Name.getText()+
"','"+Marks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
if(view==Delete)
{
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno"); return;
}

3161612 – MOBILE APPLICATION DEVELOPMENT 31


Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'",
null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
if(view==Update)
{
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'",
null);
if(c.moveToFirst()) {
db.execSQL("UPDATE student SET name='" + Name.getText() + "',marks='" +
Marks.getText() +
"' WHERE rollno='"+Rollno.getText()+"'"); showMessage("Success",
"Record Modified");
}
else {
showMessage("Error", "Invalid Rollno");
}
clearText();
}
if(view==View)
{
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno"); return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'",
null);
if(c.moveToFirst())
{
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
if(view==ViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();

3161612 – MOBILE APPLICATION DEVELOPMENT 32


while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
}
public void showMessage(String title,String message)
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
Rollno.setText("");
Name.setText("");
Marks.setText("");
Rollno.requestFocus();
}
}

Output

3161612 – MOBILE APPLICATION DEVELOPMENT 33


Date::
Practical – 10
Write an Android application to Record and save video using camera

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<ImageButton android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_below="@id/camera_preview"
android:layout_alignRight="@id/camera_preview"
android:layout_alignTop="@id/camera_preview"
android:src="@drawable/ic_videocam_grey600_48dp"/>

</RelativeLayout>

MainActivity.java
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends Activity


{
// Instance fields.
private CameraSurfaceView mCameraSurfaceView;
private Camera mCamera;

3161612 – MOBILE APPLICATION DEVELOPMENT 34


private ImageButton mImageButton;
private MediaRecorder mMediaRecorder;
private Boolean mIsRecording = false;
private static File mVideoDir;

// Static fields.
private final static String TAG = VideoRecordActivity.class.getSimpleName();
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

@Override
public void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "+++ onCreate() +++");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.camera_surface_view);

// Create an instance of Camera


mCamera = getCameraInstance();

// Create our Preview view and set it as the content of our activity.
mCameraSurfaceView = new CameraSurfaceView(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraSurfaceView);

// Get Record Button and set icon.


mImageButton = (ImageButton) findViewById(R.id.button);
mImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImageButton imgButton = (ImageButton) v;
if (mIsRecording) {
runOnUiThread(new Runnable() {
@Override
public void run() {
ImageButton imgButton = (ImageButton)
(findViewById(R.id.button));
imgButton.setImageResource(R.drawable.ic_videocam_grey600_48dp);
mVideoDir = new
File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "RecordVideo");
Toast.makeText(getApplicationContext(),
getText(R.string.stop_rec) + mVideoDir.toString(),
Toast.LENGTH_LONG).show();
}
});
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mCamera.lock(); // take camera access back from MediaRecorder

// inform the user that recording has stopped


mIsRecording = false;
} else {
runOnUiThread(new Runnable() {
@Override

3161612 – MOBILE APPLICATION DEVELOPMENT 35


public void run() {
ImageButton imgButton = (ImageButton)
(findViewById(R.id.button));

imgButton.setImageResource(R.drawable.ic_videocam_off_grey600_48dp);
Toast.makeText(getApplicationContext(),
getText(R.string.start_rec),
Toast.LENGTH_SHORT).show();
}
});
// initialize video camera
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
mMediaRecorder.start();

// inform the user that recording has started


mIsRecording = true;
} else {
// prepare didn't work, release the camera
releaseMediaRecorder();
// inform user
}
}
}
});
}

@Override
protected void onStart()
{
Log.d(TAG, "++ onStart() ++");
super.onStart();
}

@Override
protected void onResume()
{
Log.i(TAG, "+ onResume() +");
super.onResume();
}

@Override
protected void onPause()
{
Log.i(TAG, "- onPause() -");
super.onPause();
releaseMediaRecorder();
releaseCamera();
}

@Override
protected void onStop()
{
Log.i(TAG, "-- onStop() --");
super.onStop();
}

@Override
protected void onDestroy()
{

3161612 – MOBILE APPLICATION DEVELOPMENT 36


Log.i(TAG, "--- onDestroy() ---");
super.onDestroy();
}

/*
* Helper methods from https://developer.android.com/guide/topics/media/camera.html
* */

/** Check if this device has a camera */


private boolean checkCameraHardware(Context context) {
if
(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
Log.d(TAG, "Device has camera");
return true;
} else {
// no camera on this device
Log.d(TAG, "Device does NOT have camera");
return false;
}
}

/** A safe way to get an instance of the Camera object. */


public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
Log.e(TAG, "Camera not available!");
e.printStackTrace();
}
return c; // returns null if camera is unavailable
}

private boolean prepareVideoRecorder(){

if (mCamera == null) {
mCamera = getCameraInstance();
}
mMediaRecorder = new MediaRecorder();

// Step 1: Unlock and set camera to MediaRecorder


mCamera.unlock();

mMediaRecorder.setCamera(mCamera);

// Step 2: Set sources


mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)


mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

// Step 4: Set output file


mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());

// Step 5: Set the preview output


mMediaRecorder.setPreviewDisplay(mCameraSurfaceView.getHolder().getSurface());

3161612 – MOBILE APPLICATION DEVELOPMENT 37


// Step 6: Prepare configured MediaRecorder
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException preparing MediaRecorder: " +
e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}

private void releaseMediaRecorder(){


if (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration
mMediaRecorder.release(); // release the recorder object
mMediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}

private void releaseCamera(){


if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}

/** Create a file Uri for saving an image or video */


private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}

/** Create a File for saving an image or video */


private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.

mVideoDir = new File(Environment.getExternalStoragePublicDirectory(


Environment.DIRECTORY_PICTURES), "RecordVideo");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.

// Create the storage directory if it does not exist


if (!mVideoDir.exists()) {
if (!mVideoDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}

// Create a media file name


String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mVideoDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");

3161612 – MOBILE APPLICATION DEVELOPMENT 38


} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mVideoDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
} else {
return null;
}

return mediaFile;
}
}

CameraSurfaceView.java

import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

public class CameraSurfaceView extends SurfaceView implements


SurfaceHolder.Callback
{
// Instance fields.
private SurfaceHolder mHolder;
private Camera mCamera;

// Static fields.
private static final String TAG = CameraSurfaceView.class.getSimpleName();

// Mandatory constructors, they do not do much


public CameraSurfaceView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}

public CameraSurfaceView(Context context, AttributeSet attrs)


{
super(context, attrs);
}

public CameraSurfaceView(Context context)


{
super(context);
}

public CameraSurfaceView(Context context, Camera camera)


{
super(context);
mCamera = camera;

// Install a SurfaceHolder.Callback so we get notified when the


// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

3161612 – MOBILE APPLICATION DEVELOPMENT 39


}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
Log.d(TAG, "surfaceChanged()");
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.

if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}

// stop preview before making changes


try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}

// set preview size and make any resize, rotate or


// reformatting changes here

// start preview with new settings


try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();

} catch (Exception e){


Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}

@Override
public void surfaceCreated(SurfaceHolder holder)
{
Log.d(TAG, "surfaceCreated()");
try
{
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
catch (IOException e)
{
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}

@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
Log.d(TAG, "surfaceDestroyed()");

3161612 – MOBILE APPLICATION DEVELOPMENT 40

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy