0% found this document useful (0 votes)
200 views117 pages

Mad Output 9all

The document describes an Android application that allows selecting multiple checkboxes for different soccer players (Cristiano Ronaldo, Lionel Messi, etc.) and displays a toast message with the name of the player when each checkbox is clicked. It includes the MainActivity Java code to initialize and add click listeners to each checkbox as well as call a method to handle the button click. The activity_main XML layout contains the checkboxes and button.

Uploaded by

vaibhav
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)
200 views117 pages

Mad Output 9all

The document describes an Android application that allows selecting multiple checkboxes for different soccer players (Cristiano Ronaldo, Lionel Messi, etc.) and displays a toast message with the name of the player when each checkbox is clicked. It includes the MainActivity Java code to initialize and add click listeners to each checkbox as well as call a method to handle the button click. The activity_main XML layout contains the checkboxes and button.

Uploaded by

vaibhav
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/ 117

Practical No 10:

Exercise Q1:
MainActivity.java
package com.example.kaifqureshi10;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {


EditText uName, pName;
Button loginBtn;

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

uName = findViewById(R.id.username_input);
pName = findViewById(R.id.password_input);
loginBtn = findViewById(R.id.login_button);
loginBtn.setOnClickListener(new
View.OnClickListener(){
@Override
public void onClick(View v){
if
(uName.getText().toString().equals("[email protected]")&&

pName.getText().toString().equals("Kaif")){
Toast.makeText(MainActivity.this, "Login
Successfully", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this, "Login
failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="10dp"
android:textSize="30dp"
android:textColor="@color/black"
/>

<ImageView
android:layout_width="160dp"
android:layout_height="150dp"
android:scaleType="centerCrop"
android:src="@drawable/google"/>

<EditText
android:id="@+id/username_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="UserName"
android:layout_margin="15dp"
android:inputType="textEmailAddress"
android:padding="16dp"/>

<EditText
android:id="@+id/password_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:hint="Password"
android:padding="16dp"
android:inputType="textPassword"/>

<Button
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="Login"
android:background="@color/white"/>

</LinearLayout>

Output:

Exercise Q2:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:padding="50dp"
android:layout_marginTop="30dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login Form"
android:textSize="30sp"/>
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username: "
android:textSize="20sp"/>
<EditText
android:id="@+id/e1"
android:layout_width="150dp"
android:layout_height="wrap_content"/>
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password: "
android:textSize="20sp"/>
<EditText
android:id="@+id/e2"
android:layout_width="150dp"
android:layout_height="wrap_content"/>
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_marginTop="50dp">
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"/>
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Reset"/>
</LinearLayout>

</LinearLayout>

MainActivity.java
package com.example.practical10;

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;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn1,btn2;
private EditText e1,e2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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


btn2 = (Button) findViewById(R.id.b2);
e1 = (EditText) findViewById(R.id.e1);
e2 = (EditText) findViewById(R.id.e2);

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(e1.getText().toString().equals("Kaif") &&

e2.getText().toString().equals("Qureshi")){
Toast.makeText(MainActivity.this,"Login
Successfully", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Invalid
id or password.", Toast.LENGTH_SHORT).show();
}
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
e1.setText("");
e2.setText("");
}
});
}
}

OUTPUT:
SJ H
PRACTICAL NO 11:

MainActivity.java
package com.example.practical11;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private CheckBox CristianoRonaldo, LionelMessi, Pele,
Neymarjr, ZlatanIbrahimović;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnChkCristianoRonaldo();
addListenerOnChkLionelMessi();
addListenerOnChkPele();
addListenerOnChkNeymarjr();
addListenerOnChkZlatanIbrahimović();
addListenerOnButton();
}
public void addListenerOnChkCristianoRonaldo() {
CristianoRonaldo = (CheckBox)
findViewById(R.id.chkCristianoRonaldo);
CristianoRonaldo.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(MainActivity.this,
"CristianoRonaldo",
Toast.LENGTH_LONG).show();
}
}
});
}
public void addListenerOnChkLionelMessi() {
LionelMessi = (CheckBox)
findViewById(R.id.chkLionelMessi);
LionelMessi.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(MainActivity.this,
"LionelMessi",
Toast.LENGTH_LONG).show();
}
}
});
}
public void addListenerOnChkPele() {
Pele = (CheckBox) findViewById(R.id.chkPele);
Pele.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(MainActivity.this,
"Pele", Toast.LENGTH_LONG).show();
}
}
});
}
public void addListenerOnChkNeymarjr() {
Neymarjr = (CheckBox) findViewById(R.id.chkNeymarjr);
Neymarjr.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(MainActivity.this,
"Neymarjr",
Toast.LENGTH_LONG).show();
}
}
});
}
public void addListenerOnChkZlatanIbrahimović() {
ZlatanIbrahimović = (CheckBox)
findViewById(R.id.chkZlatanIbrahimović);
ZlatanIbrahimović.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(MainActivity.this,
"ZlatanIbrahimović",
Toast.LENGTH_LONG).show();
}
}
});
}
public void addListenerOnButton() {
CristianoRonaldo = (CheckBox)
findViewById(R.id.chkCristianoRonaldo);
LionelMessi = (CheckBox)
findViewById(R.id.chkLionelMessi);
Pele = (CheckBox) findViewById(R.id.chkPele);
Neymarjr = (CheckBox) findViewById(R.id.chkNeymarjr);
ZlatanIbrahimović = (CheckBox)
findViewById(R.id.chkZlatanIbrahimović);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
if (CristianoRonaldo.isChecked()){
result.append("CristianoRonaldo"); }
if (LionelMessi.isChecked()){
result.append("\nLionelMessi"); }
if (Pele.isChecked()){
result.append("\nPele"); }
if (Neymarjr.isChecked()){
result.append("\nNeymarjr"); }
if (ZlatanIbrahimović.isChecked()){
result.append("\nZlatanIbrahimović"); }
Toast.makeText(MainActivity.this,
result.toString(),
Toast.LENGTH_LONG).show();
}
});
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="30dp"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Select Your Favourite Football Player "
android:textSize="20sp"
android:textStyle="bold" />

<CheckBox
android:id="@+id/chkCristianoRonaldo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="CristianoRonaldo" />

<CheckBox
android:id="@+id/chkLionelMessi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LionelMessi" />

<CheckBox
android:id="@+id/chkPele"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pele" />

<CheckBox
android:id="@+id/chkNeymarjr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Neymarjr" />
<CheckBox
android:id="@+id/chkZlatanIbrahimović"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ZlatanIbrahimović" />
<Button
android:id="@+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Show" />
</LinearLayout>

Output:
Name : Vaibhav Walanju Enrollment : 2005690074
Subject : MAD

Practical : 04

1. Write a program to display HelloWorld.

Code :
<TextView android:id="t1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Hello World"
android:textSize="32dp" android:textStyle="bold"
tools:layout_editor_absoluteX="122dp" tools:layout_editor_absoluteY="424dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

Output :

2. Write a program to display student names and marks.

Code : <TextView android:id="@+id/Text1"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Names"
android:textSize="25dp"
android:textStyle="bold"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="54dp"
tools:layout_editor_absoluteY="147dp" />
<TextView android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Akshay"
android:textSize="20dp"
tools:layout_editor_absoluteX="54dp"
tools:layout_editor_absoluteY="226dp" />

<TextView android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rahul"
android:textSize="20dp"
tools:layout_editor_absoluteX="54dp"
tools:layout_editor_absoluteY="296dp" />

<TextView android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Virat"
android:textSize="20dp"
tools:layout_editor_absoluteX="54dp"
tools:layout_editor_absoluteY="372dp" />
<TextView android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jay"
android:textSize="20dp"
tools:layout_editor_absoluteX="54dp"
tools:layout_editor_absoluteY="452dp" />

<TextView android:id="@+id/Text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Marks"
android:textSize="25dp"
android:textStyle="bold"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="274dp"
tools:layout_editor_absoluteY="147dp" />

<TextView android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30/50"
android:textSize="20dp"
tools:layout_editor_absoluteX="274dp"
tools:layout_editor_absoluteY="226dp" />

<TextView android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="40/50"
android:textSize="20dp"
tools:layout_editor_absoluteX="274dp"
tools:layout_editor_absoluteY="296dp" />

<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content
"
android:layout_height="wrap_conte
nt" android:text="25/50"
android:textSize="20dp"
tools:layout_editor_absoluteX="274
dp"
tools:layout_editor_absoluteY="372
dp" />

<TextView android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="48/50" android:textSize="20dp"
tools:layout_editor_absoluteX="274dp"
tools:layout_editor_absoluteY="452dp" />
</androidx.constraintlayout.widget.ConstraintLayout
>
Output :
Name : Vaibhav Walanju Enrollment : 2005690074

Subject : MAD

Practical : 05

1. Write a program to place Name, Age and mobile number linearly


(Vertical) on the display screen using Linear layout.
Code : <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="ExtraText">
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name :" />
<EditText
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Age :" />
<EditText
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Number :" />
</LinearLayout>
Output :
2. Write a program to place Name, Age and mobile number centrally on
the display screen using Absolute layout.
Code : <?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
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:ignore="ExtraText"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_x="1dp"
android:layout_y="201dp"
android:text="Name :" />
<EditText
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_x="1dp"
android:layout_y="300dp"
android:text="Age :" />
<EditText
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_x="1dp"
android:layout_y="400dp"
android:text="Number :" />
</AbsoluteLayout>
Output :

Name : Vaibhav Walanju Enrollment : 2005690074

Subject : MAD

Practical : 06

1. Write a program to display 10 students basic information in a table form using


Table layout.
Code : <?xml version="1.0"
encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com
/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="@color/black"
android:text="SR.No" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="@color/black"
android:text="Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Marks"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Roll No."
android:textColor="@color/black" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="1"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Sanskar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="88" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="01" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="2"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Ibrahim" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="76" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="02" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="3"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Himayun" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="99" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="03" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="4"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Aman" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="99" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="04" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="5"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Tabish" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="78" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="05" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="6"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Yahya" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="87" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="06" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="7"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Shadan" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="73" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="07" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="8"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Juned" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="67" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="08" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="9"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Naif" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="87" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="09" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="10"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Wajeed" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="86" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="10" />
</TableRow>
</TableLayout>

Output :
2. Write a program to display all the data types in object-oriented programming
using Frame layout.
Code :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com
/apk/res/android"
xmlns:tools="http://schemas.android.com/to
ols"
android:layout_width="wrap_content"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="66dp"
android:text="Data Types in Object Oriented
Programming"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|left|fill_vertical"
android:layout_marginTop="80dp"
android:text="Primitive"
android:textSize="20dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="110dp"
android:foregroundGravity="fill_horizontal|to
p"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1) Integer" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2) Float" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3) Characters" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4) Boolean" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|fill_vertical"
android:layout_marginTop="80dp"
android:text="Non-Primitive"
android:textSize="20dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="110dp"
android:layout_marginRight="20dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1) Class" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2) Array" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3) Interface" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4) Object" />
</LinearLayout>
</FrameLayout>

Output :
Name : Vaibhav Walanju
Enrollment : 2005690074
Subject : MAD

Practical : 07

1. Write a program to accept username and password from the end


user using TextView and Edit Text.
XML Code :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.Const
raintLayout
xmlns:android="http://schemas.android.
com/apk/res/android"
xmlns:app="http://schemas.android.com
/apk/res-auto"
xmlns:tools="http://schemas.android.co
m/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="370sp"
android:ems="10"
android:inputType="textPersonName"
android:padding="10sp"
android:text="Name: "
android:textSize="20sp"
app:layout_constraintBottom_toBottom
Of="parent"
app:layout_constraintEnd_toEndOf="par
ent"
app:layout_constraintHorizontal_bias="0
.512"
app:layout_constraintStart_toStartOf="p
arent"
app:layout_constraintTop_toTopOf="par
ent"
app:layout_constraintVertical_bias="0.0
68" />
<EditText
android:id="@+id/enrollment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="370sp"
android:ems="10"
android:inputType="textPersonName"
android:padding="10sp"
android:text="Enrollment: "
android:textSize="20sp"
app:layout_constraintBottom_toBottom
Of="parent"
app:layout_constraintEnd_toEndOf="par
ent"
app:layout_constraintHorizontal_bias="0
.512"
app:layout_constraintStart_toStartOf="p
arent"
app:layout_constraintTop_toTopOf="par
ent"
app:layout_constraintVertical_bias="0.1
84" />
<EditText
android:id="@+id/batch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="370sp"
android:ems="10"
android:inputType="textPersonName"
android:padding="10sp"
android:text="Branch: "
android:textSize="20sp"
app:layout_constraintBottom_toBottom
Of="parent"
app:layout_constraintEnd_toEndOf="par
ent"
app:layout_constraintHorizontal_bias="0
.512"
app:layout_constraintStart_toStartOf="p
arent"
app:layout_constraintTop_toTopOf="par
ent"
app:layout_constraintVertical_bias="0.2
99" />
<Button
android:id="@+id/supabutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="14sp"
android:text="Continue"
android:textSize="24sp"
app:layout_constraintBottom_toBottom
Of="parent"
app:layout_constraintEnd_toEndOf="par
ent"
app:layout_constraintHorizontal_bias="0
.497"
app:layout_constraintStart_toStartOf="p
arent"
app:layout_constraintTop_toTopOf="par
ent"
app:layout_constraintVertical_bias="0.4
64" />
<TextView
android:id="@+id/getname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="14sp"
android:text="Name: "
android:textSize="18sp"
android:textColor="@color/black"
app:layout_constraintBottom_toBottom
Of="parent"
app:layout_constraintEnd_toEndOf="par
ent"
app:layout_constraintHorizontal_bias="0
.065
app:layout_constraintStart_toStartOf="p
arent"
app:layout_constraintTop_toTopOf="par
ent"
app:layout_constraintVertical_bias="0.6
58" />
<TextView
android:id="@+id/getenrollment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="14sp"
android:text="Enrollment: "
android:textColor="@color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottom
Of="parent"
app:layout_constraintEnd_toEndOf="par
ent"
app:layout_constraintHorizontal_bias="0
.071"
app:layout_constraintStart_toStartOf="p
arent"
app:layout_constraintTop_toTopOf="par
ent"
app:layout_constraintVertical_bias="0.7
94" />
<TextView
android:id="@+id/getbranch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="14sp"
android:text="Branch: "
android:textColor="@color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottom
Of="parent"
app:layout_constraintEnd_toEndOf="par
ent"
app:layout_constraintHorizontal_bias="0
.066"
app:layout_constraintStart_toStartOf="p
arent"
app:layout_constraintTop_toTopOf="par
ent"
app:layout_constraintVertical_bias="0.9
13" />
</androidx.constraintlayout.widget.Cons
traintLayout>
Java Code :
package com.example.frame;
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 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.supabutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText name = (EditText) findViewById(R.id.name);
EditText enrollment = (EditText) findViewById(R.id.enrollment);
EditText batch = (EditText) findViewById(R.id.batch);
TextView getname = (TextView) findViewById(R.id.getname);
TextView getenrollment = (TextView) findViewById(R.id.getenrollment);
TextView getbranch = (TextView) findViewById(R.id.getbranch);
getname.setText(name.getText());
getenrollment.setText(enrollment.getText());
getbranch.setText(batch.getText());
}
});
}
}

Output :
2. Write a program to accept and display personal information of the
student.
XML Code :
<?xml version="1.0"
encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.andro
id.com/apk/res/android"
xmlns:app="http://schemas.android.c
om/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:layout_width="wrap_content"
android:layout_height="wrap_content
"
android:text="Login Form"
android:textStyle="bold"
android:textSize="50sp"
android:layout_gravity="center_horiz
ontal"
android:textColor="@color/black"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content
"
android:hint="Enter Username"
android:textSize="35sp"
android:fontFamily="sans-serif-conde
nsed-medium"
android:paddingRight="150sp"
android:paddingTop="40sp"
android:layout_gravity="center_horiz
ontal"
android:layout_marginTop="150sp"
/> <EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content
"
android:layout_gravity="center_horiz
ontal"
android:layout_marginTop="330sp"
android:fontFamily="sans-serif-conde
nsed-medium"
android:hint="Password "
android:inputType="textPassword"
android:paddingTop="40sp"
android:paddingRight="150sp"
android:textSize="35sp"
android:layout_marginLeft="1dp"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content
"
android:text="Remember Me"
android:textSize="25sp"
android:fontFamily="sans-serif-conde
nsed-medium"
android:layout_marginLeft="20sp"
android:layout_marginTop="500sp"
/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content
"
android:text="Log In"
android:layout_gravity="center_horiz
ontal"
android:layout_marginTop="480sp"
android:layout_marginLeft="110sp"
android:paddingTop="20sp"
android:paddingBottom="20sp"
android:paddingRight="50sp"
android:paddingLeft="50sp"
android:textStyle="bold"
android:textSize="20sp"
android:textAlignment="center" />
</FrameLayout>

JAVA Code :
package com.example.login_form1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Output :
Practicle- 12
Name- Vaibhav Walanju

Q1- Write a program to show the following output. First two radio bu􀆩ons are without
using radio group and next two radio bu􀆩ons are using radio group. Note the changes
between these two. Also toast which radio bu􀆩on has been selected.
XML CODE:-
<?xml version="1.0" encoding="u􀆩-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="h􀆩p://schemas.android.com/apk/res/android"
xmlns:app="h􀆩p://schemas.android.com/apk/res-auto"
xmlns:tools="h􀆩p://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainAc􀆩vity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Single Radio bu􀆩ons"
android:textColor="@color/black"
android:textSize="25dp"
app:layout_constraintBo􀆩om_toBo􀆩omOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVer􀆩cal_bias="0.074" />
<RadioBu􀆩on
android:id="@+id/rb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioBu􀆩on"
android:textSize="20dp"
app:layout_constraintBo􀆩om_toBo􀆩omOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.192"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVer􀆩cal_bias="0.291" />
<RadioBu􀆩on
android:id="@+id/rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioBu􀆩on"
android:textSize="20dp"
app:layout_constraintBo􀆩om_toBo􀆩omOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.192"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVer􀆩cal_bias="0.202" />
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_marginTop="20dp"
android:background="#B8B894"
app:layout_constraintBo􀆩om_toBo􀆩omOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVer􀆩cal_bias="0.384" />
<!-- Customized RadioBu􀆩ons -->
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:textColor="@color/black"
android:text="Radio bu􀆩on inside RadioGroup"
android:textSize="25dp"
app:layout_constraintBo􀆩om_toBo􀆩omOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVer􀆩cal_bias="0.43" />
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBo􀆩om_toBo􀆩omOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVer􀆩cal_bias="0.62"
app:layout_constraintHorizontal_bias="0.20">
<RadioBu􀆩on
android:id="@+id/radioMale"
android:layout_width="104dp"
android:layout_height="48dp"
android:checked="false"
android:text=" Male"
android:textSize="20dp"
tools:layout_editor_absoluteX="35dp"
tools:layout_editor_absoluteY="412dp" />
<RadioBu􀆩on
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:checked="false"
android:text=" Female"
android:textSize="20dp"
/>
</RadioGroup>
<Bu􀆩on
android:id="@+id/bu􀆩on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="onclickbu􀆩onMethod"
android:text="Show Selected"
android:backgroundTint="#60BFBF"
app:layout_constraintBo􀆩om_toBo􀆩omOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVer􀆩cal_bias="0.786" />
</androidx.constraintlayout.widget.ConstraintLayout>
Ac􀆩vity_main.java :-
package com.example.p_12;
import androidx.appcompat.app.AppCompatAc􀆩vity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioBu􀆩on;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainAc􀆩vity extends AppCompatAc􀆩vity {
TextView t1,t2;
RadioBu􀆩on rgb;
RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac􀆩vity_main);
rg =(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbu􀆩onMethod(View v) {
int selectedId = rg.getCheckedRadioBu􀆩onId();
rgb = (RadioBu􀆩on) findViewById(selectedId);
if (selectedId == -1) {
Toast.makeText(MainAc􀆩vity.this, "Nothing selected",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainAc􀆩vity.this, rgb.getText(),
Toast.LENGTH_SHORT).show();
}
}
}
PRACTICLE- 13

NAME-Vaibhav Walanju

PRACTICAL NO 13
Develop a program to implement Progress Bar.
Q1 – Write a program to display circular progress bar
XML CODE:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Circular Progress Bar"
android:textSize="30dp"
android:layout_gravity="center"
android:layout_marginTop="30dp"
/>
<ProgressBar
android:indeterminate="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading.."
android:textSize="20dp"
android:layout_gravity="center"
android:layout_marginTop="30dp"
/>
OUTPUT:
Q2 – Write a program to show the following output
XML CODE:
<?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">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="116dp"
android:text="download file"
android:textSize="25dp"
/>
</Relative layout>
JAVA CODE:
package com.example.rectangular_pbar_pr13;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private long fileSize = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick() {
btnStartProgress = findViewById(R.id.button1);
btnStartProgress.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// creating progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar and filesize status
progressBarStatus = 0;
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// performing operation
progressBarStatus = doOperation();
try {
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
// Updating the progress bar
progressBarHandler.post(new Runnable()
{
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// performing operation if file is downloaded,
if (progressBarStatus >= 100) {
// sleeping for 1 second after operation completed
try {
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}//end of onClick method
});
}
// checking how much file is downloaded and updating the filesize
public int doOperation() {
//The range of ProgressDialog starts from 0 to 10000
while (fileSize <= 10000) {
fileSize++;
if (fileSize == 1000) {
return 10;
} else if (fileSize == 2000)
{
return 20;
} else if (fileSize == 3000)
{
return 30;
} else if (fileSize == 4000) {
return 40; // you can add more else if
}
}
//end of while
return 100;
}//end of doOperation
}
OUTPUT:
Practicle-14
Name – Vaibhav Walanju

Develop a program to implement List View, Grid View, Image


View and Scroll View.

Q1 – Write a program to show the following output. Use appropriate


view for the same
XML CODE:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listv1"/>
</LinearLayout>
JAVA CODE:
package com.example.view_wala2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
String str[] = {"Android","Python","Css","Flutter","Php","JavaScript","Html","Java","Perl","Xml"};
ListView l1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1 = findViewById(R.id.listv1);
ArrayAdapter<String> a = new ArrayAdapter<String>
(this, android.R.layout.simple_expandable_list_item_1,str);
l1.setAdapter(a);
l1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id)
{
Toast.makeText(MainActivity.this, str[i], Toast.LENGTH_SHORT).show();
}
});
}
}
OUTPUT:
Q2 – Write a program to display an image using Image View and a
button named as ‘Changed Image’. Once you click on button another
image should get displayed
Q4 – Write a program to display a text view using vertical scroll view
XML CODE:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/I1"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_marginTop="40dp"
android:layout_marginBottom="28dp"
android:src="@drawable/android" />
<Button
android:id="@+id/B1"
android:layout_width="366dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:onClick="I1"
android:text="Next"
android:textColor="@color/black"
android:translationZ="1dp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
JAVA CODE:
package com.example.view_wala1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView i;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.B1);
i=findViewById(R.id.I1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i.setImageResource(R.drawable.cicon);
}
});
}
}
OUTPUT:
Q3 – Write a program to display 15 buttons using grid view
XML CODE:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView1"
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="50dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</GridView>
JAVA CODE:
package com.example.gridview;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
GridView gridView;
static final String[] numbers = new String[] {
"1", "2", "3", "4", "5",
"6", "7", "8", "9", "10"
"11", "12", "13", "14", "15"
,};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getApplicationContext(),((TextView) view).getText(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
OUTPUT:
X. Exercise:
1)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World, Toast Example"/>

<Button
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast"/>

</LinearLayout>

my_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_dark"
android:padding="16dp"
android:id="@+id/toast_root_view" >

<TextView
android:id="@+id/toast_header"
android:textSize="20dp"
android:textColor="@android:color/primary_text_dark"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<TextView
android:id="@+id/toast_body"
android:textColor="@android:color/primary_text_dark"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>

MainActivity.java
package com.example.toast_ex;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

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

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

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LayoutInflater inflater = getLayoutInflater();

View toastLayout = inflater.inflate(R.layout.my_toast,


(ViewGroup) findViewById(R.id.toast_root_view));

TextView header = (TextView)


toastLayout.findViewById(R.id.toast_header);
header.setText("Message for you:");

TextView body = (TextView)


toastLayout.findViewById(R.id.toast_body);
body.setText("You have got mail!");

Toast toast = new Toast(getApplicationContext());


toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastLayout);
toast.show();
}
});
}
}

Output (On Android Emulator):


2) Write a program to display three checkboxes and one button named "Order" as shown
below. Once you click on button it should toast different selected checkboxes along with
items individual and total price.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="68dp"
android:text="Pizza" />

<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Coffee" />

<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Burger" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="184dp"
android:text="Order" />

</LinearLayout>

MainActivity.java
package com.example.toast_ex;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

CheckBox pizza,coffe,burger;
Button buttonOrder;

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

pizza=(CheckBox)findViewById(R.id.checkBox);
coffe=(CheckBox)findViewById(R.id.checkBox2);
burger=(CheckBox)findViewById(R.id.checkBox3);
buttonOrder=(Button)findViewById(R.id.button);

buttonOrder.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View view) {
int totalamount=0;
StringBuilder result=new StringBuilder();
result.append("Selected Items:");
if(pizza.isChecked()){
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked()){
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120;
}
result.append("\nTotal: "+totalamount+"Rs");
Toast.makeText(getApplicationContext(), result.toString(),
Toast.LENGTH_LONG).show();
}
});
}
}

Output (On Android Emulator):


X. Exercise:
1) Write a program to display TimePicker with Spinnermode
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<TimePicker
android:layout_marginTop="130dp"
android:layout_gravity="center"
android:timePickerMode="spinner"
android:id="@+id/tp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:id="@+id/btn"
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:text="Show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_marginTop="30dp"
android:layout_gravity="center"
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>

MainActivity.java
package com.example.linear_layout;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
TimePicker tp;
TextView tv;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tp = (TimePicker) findViewById(R.id.tp);
tv = (TextView) findViewById(R.id.tv);
b = (Button) findViewById(R.id.btn);
tp.setIs24HourView(true);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tv.setText(getCurrentTime());
}
});
}
public String getCurrentTime(){
String currentTime="Current Time:
"+tp.getCurrentHour()+":"+tp.getCurrentMinute();
return currentTime;
}
}

Output:

2) Write a program to display following output. Select and display date and time on click of
“select date”, “select time” buttons respectively.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:padding="25dp"
android:layout_marginLeft="15dp">

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_date"
android:layout_marginTop="82dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT DATE"
android:id="@+id/btn_date"
android:layout_alignBottom="@+id/in_date"
android:layout_toRightOf="@+id/in_date"
android:layout_toEndOf="@+id/in_date" />

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_time"
android:layout_below="@+id/in_date"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT TIME"
android:id="@+id/btn_time"
android:layout_below="@+id/btn_date"
android:layout_alignLeft="@+id/btn_date"
android:layout_alignStart="@+id/btn_date" />

<TextView
android:id="@+id/d"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/in_time"
android:text="Date : "
android:textSize="30sp"/>

<TextView
android:id="@+id/t"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/d"
android:textSize="30sp"
android:text="Time : "/>

</RelativeLayout>

MainActivity.java
package com.example.linear_layout;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
Button btnDatePicker, btnTimePicker;
EditText txtDate, txtTime;
TextView t,d;
private int mYear, mMonth, mDay, mHour, mMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.t);
d = (TextView) findViewById(R.id.d);
btnDatePicker=(Button)findViewById(R.id.btn_date);
btnTimePicker=(Button)findViewById(R.id.btn_time);
txtDate=(EditText)findViewById(R.id.in_date);
txtTime=(EditText)findViewById(R.id.in_time);
btnDatePicker.setOnClickListener(this);
btnTimePicker.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == btnDatePicker) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,int
monthOfYear, int dayOfMonth) {
txtDate.setText(dayOfMonth + "-" + (monthOfYear
+ 1) + "-" + year);
d.setText("Date : "+dayOfMonth + "-" +
(monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
if (v == btnTimePicker) {
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int
hourOfDay,int minute) {
txtTime.setText(hourOfDay + ":" + minute);
t.setText("Time : "+hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
}
}
Output:
X. Exercise:
1) Write a program to create a HelloWorld Activity using all lifecycles methods to display
messages using Log.d
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:padding="25dp"
android:layout_marginLeft="15dp">

</RelativeLayout>

MainActivity.java
package com.example.linear_layout;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("lifecycle","onCreate()");
}

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

@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume()");
}

@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause()");
}

@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop()");
}

@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart()");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy()");
}

Output:
X. Exercise:
1) Write a program to create a text field and a button “Navigate”. When you enter
“www.google.com” and press navigate button it should open google page.
activity_main.xml
<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:padding="25dp">

<EditText
android:id="@+id/et"
android:layout_marginTop="150dp"
android:layout_gravity="center"
android:layout_width="250dp"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn"
android:layout_marginTop="90dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"/>
</LinearLayout>

MainActivity.java
package com.example.linear_layout;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button b;
EditText et;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.btn);
et = (EditText) findViewById(R.id.et);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(et.getText().toString()));
startActivity(intent);
}
});
}
}
Output:

2) Write a program to create button “Start Dialer”. When you click on this button it should
open the phone dialer.
activity_main.xml
<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:padding="25dp">

<EditText
android:id="@+id/et"
android:inputType="phone"
android:layout_marginTop="150dp"
android:layout_gravity="center"
android:layout_width="250dp"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn"
android:layout_marginTop="90dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"/>
</LinearLayout>
MainActivity.java
package com.example.linear_layout;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button b;
EditText et;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.btn);
et = (EditText) findViewById(R.id.et);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:" + et.getText().toString()));
startActivity(intent);
}
});
}
}

Output:
3) Write a program to create two screens. First screen will take one number input from user.
After click on Factorial button, second screen will open and it should display factorial of the
same number. Also specify which type of intent you will use in this case.
activity_main.xml
<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:padding="25dp">

<EditText
android:id="@+id/et"
android:inputType="phone"
android:layout_marginTop="150dp"
android:layout_gravity="center"
android:layout_width="250dp"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn"
android:layout_marginTop="90dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"/>
</LinearLayout>

activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity2">

<TextView
android:id="@+id/tv"
android:layout_gravity="center"
android:textSize="20sp"
android:layout_marginTop="200dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.java
package com.example.linear_layout;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button b;
EditText et;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.btn);
et = (EditText) findViewById(R.id.et);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int n = Integer.parseInt(et.getText().toString());
int f = 1;
for(int i = 1;i<=n;i++){
f = f * i;
}
Intent intent = new
Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("Fact","Factorial of "+n+" is "+f);
startActivity(intent);
}
});
}
}

MainActivity2.java
package com.example.linear_layout;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity2 extends AppCompatActivity {


TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv = (TextView) findViewById(R.id.tv);
Intent intent = getIntent();
String f = (String) intent.getSerializableExtra("Fact");
tv.setText(f+"\n Intent used : Explicit Intent");
}
}
Output:
X. Exercise:
1) Write a program to demonstrate all the system broadcast messages.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<Button
android:layout_marginTop="200dp"
android:layout_gravity="center"
android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Broadcast Receiver"/>

</LinearLayout>

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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Brodcasting"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

<receiver android:name=".brod"
android:exported="true">
<intent-filter>
<action android:name="com.example.brodcasting.brod">
</action>
</intent-filter>
</receiver>
</application>
</manifest>

brod.java
package com.example.brodcasting;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class brod extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast Receive !",
Toast.LENGTH_LONG).show();
}}

MainActivity.java
package com.example.brodcasting;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }
public void click(View view){
Intent intent = new Intent();
intent.setAction("com.example.brodcasting.brod");
sendBroadcast(intent); }}

Output:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView1"/>
</LinearLayout>

MainActivity.java
package com.example.hahhaaaa;

import java.util.List;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

SensorManager smm;
List<Sensor> sensor;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
lv = (ListView) findViewById (R.id.listView1);
sensor = smm.getSensorList(Sensor.TYPE_ALL);
lv.setAdapter(new ArrayAdapter<Sensor>(this,
android.R.layout.simple_list_item_1, sensor));
}
}
Output:
X. Exercise:
1) Write a program to capture an image and display it using image view.
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">
<Button
android:id="@+id/camera_button"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginStart="150dp"
android:text="Camera" />
<ImageView
android:id="@+id/click_image"
android:layout_width="350dp"
android:layout_height="450dp"
android:layout_marginStart="30dp"
android:layout_marginTop="70dp"
android:layout_marginBottom="10dp" />
</RelativeLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.pr24">
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Pr24"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>

</manifest>

MainActivity.java
package com.example.pr24;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


private static final int pic_id = 123;
Button camera_open_id;
ImageView click_image_id;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
camera_open_id = findViewById(R.id.camera_button);
click_image_id = findViewById(R.id.click_image);
camera_open_id.setOnClickListener(v -> {
Intent camera_intent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera_intent, pic_id); });}
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == pic_id) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
click_image_id.setImageBitmap(photo); }}}

Output:
X. Exercise:
1) Write a program to turn on, get visible, list devices and turnoff Bluetooth.
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"
android:padding="30dp"
android:transitionGroup="true">

<TextView android:text="Bluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="30dp"
android:layout_alignParentTop="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
android:id="@+id/button1"
android:clickable="true"
android:layout_below="@+id/textview"
android:onClick="on" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get visible"
android:onClick="visible"
android:id="@+id/button2"
android:layout_below="@+id/button1" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List devices"
android:onClick="list"
android:id="@+id/button3"
android:layout_below="@+id/button2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="turn off"
android:onClick="off"
android:id="@+id/button4"
android:layout_below="@+id/button3" />

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_below="@+id/textView2" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView2"
android:textSize="25dp"
android:layout_marginTop="50dp"
android:layout_below="@+id/button4"
android:layout_alignLeft="@+id/listView"
android:layout_alignStart="@+id/listView" />

</RelativeLayout>
MainActivity.java
package com.e.bluetooth_exp;

import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

Button b1,b2,b3,b4;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
ListView lv;

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

b1 = (Button) findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);

BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}

public void on(View view) {


if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on",
Toast.LENGTH_LONG).show();
}
}

public void off(View view) {


BA.disable();
Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
}

public void visible(View view) {


Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}

public void list(View view) {


pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired
Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.e.bluetooth_exp">

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


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

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

Output (On Android Emulator):


a) TURN ON b) GET VISIBLE
c) LIST DEVICES d) TURN OFF
X. Exercise
1. Write a program to insert data in SQLite database using AsyncTask
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">

<EditText
android:layout_marginTop="90dp"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/username"
android:hint="Username"
android:layout_gravity="center"/>

<EditText
android:layout_marginTop="50dp"
android:hint="Password"
android:inputType="textPassword"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/password"
android:layout_gravity="center"/>

<EditText
android:layout_marginTop="50dp"
android:hint="Re Password"
android:inputType="textPassword"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/rpassword"
android:layout_gravity="center"/>

<Button
android:id="@+id/btn"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sig-up"
android:layout_gravity="center"/>

<Button
android:id="@+id/btn2"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:layout_gravity="center"/>

</LinearLayout>
MainActivity.java
package com.example.pr26;

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;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button login,sigup;
EditText username,password,repassword;

DBHelper DB;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button) findViewById(R.id.btn);
sigup = (Button) findViewById(R.id.btn2);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
repassword = (EditText) findViewById(R.id.rpassword);
DB = new DBHelper(this);

login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String user = username.getText().toString();
String pass = password.getText().toString();
String repass = repassword.getText().toString();

if(user.equals("")||pass.equals("")||repass.equals(""))
Toast.makeText(MainActivity.this, "Please enter all the
fields", Toast.LENGTH_SHORT).show();
else{
if(pass.equals(repass)){
Boolean checkuser = DB.checkusername(user);
if(checkuser==false){
Boolean insert = DB.insertData(user, pass);
if(insert==true){
Toast.makeText(MainActivity.this,
"Registered successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this,
"Registration failed", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(MainActivity.this, "User already
exists! please sign in", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Passwords not
matching", Toast.LENGTH_SHORT).show();
}
} }
});

sigup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new
Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
}
}

DBHelper.java
package com.example.pr26;

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

import androidx.annotation.Nullable;

public class DBHelper extends SQLiteOpenHelper {

public static final String DBNAME = "Login.db";

public DBHelper(Context context) {


super(context, "Login.db", null, 1);
}

@Override
public void onCreate(SQLiteDatabase MyDB) {
MyDB.execSQL("create Table users(username TEXT primary key,password
TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) {
MyDB.execSQL("drop Table if exists users");
}

public Boolean insertData(String username,String password){


SQLiteDatabase MyDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username",username);
contentValues.put("password",password);
long result = MyDB.insert("users",null,contentValues);
if(result==-1)return false;
else
return true;
}

public Boolean checkusername(String username){


SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("select * from users where username =
? ",new String[] {username});
if(cursor.getCount()>0)
return true;
else
return false;
}

public Boolean checkusernamepassword(String username,String password){


SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("select * from users where username =
? and password = ?",new String[] {username,password});
if(cursor.getCount()>0)
return true;
else
return false;
}
}

activity_main2.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">

<EditText
android:layout_marginTop="90dp"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/username1"
android:hint="Username"
android:layout_gravity="center"/>

<EditText
android:layout_marginTop="50dp"
android:hint="Password"
android:inputType="textPassword"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/password1"
android:layout_gravity="center"/>

<Button
android:id="@+id/btnsignin1"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:layout_gravity="center"/>

</LinearLayout>

MainActivity2.java
package com.example.pr26;
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;
import android.widget.Toast;

public class MainActivity2 extends AppCompatActivity {


EditText username, password;
Button btnlogin;
DBHelper DB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);

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


password = (EditText) findViewById(R.id.password1);
btnlogin = (Button) findViewById(R.id.btnsignin1);
DB = new DBHelper(this);

btnlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

String user = username.getText().toString();


String pass = password.getText().toString();

if(user.equals("")||pass.equals(""))
Toast.makeText(MainActivity2.this, "Please enter all
the fields", Toast.LENGTH_SHORT).show();
else{
Boolean checkuserpass = DB.checkusernamepassword(user,
pass);
if(checkuserpass==true){
Toast.makeText(MainActivity2.this, "Sign in
successfull", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity2.this, "Invalid
Credentials", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}

Output:
X. Exercise:
1) Write a program to create a login form for a E-commerce site
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:padding="50dp"
android:layout_marginTop="30dp">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login Form"
android:textSize="30sp"/>
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username: "
android:textSize="20sp"/>

<EditText
android:id="@+id/e1"
android:layout_width="150dp"
android:layout_height="wrap_content"/>

</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password: "
android:textSize="20sp"/>

<EditText
android:id="@+id/e2"
android:layout_width="150dp"
android:layout_height="wrap_content"/>

</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_marginTop="50dp">

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

<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Reset"/>

</LinearLayout>

</LinearLayout>

MainActivity.java
package com.example.linear_layout;
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;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private Button btn1,btn2;
private EditText e1,e2;

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

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


btn2 = (Button) findViewById(R.id.b2);
e1 = (EditText) findViewById(R.id.e1);
e2 = (EditText) findViewById(R.id.e2);

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(e1.getText().toString().equals("Shaikh") &&
e2.getText().toString().equals("Ibrahim")){
Toast.makeText(MainActivity.this, "Login
Successfully.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Invalid id or
password.", Toast.LENGTH_SHORT).show();
}
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
e1.setText("");
e2.setText("");
}
});
}
}

Output:
X. Exercise:
1) Write a program to create the login form with necessary validations like length of
username and password, empty text fields, count of unsuccessful login attempts. Display
the login successful/Unsuccessful toast message.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<EditText
android:layout_marginTop="180dp"
android:layout_gravity="center"
android:id="@+id/editTextTextPersonName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"/>

<EditText
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:id="@+id/editTextTextPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"/>

<TextView
android:layout_marginTop="40dp"
android:layout_gravity="center"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="30sp"/>

<Button
android:layout_marginTop="40dp"
android:layout_gravity="center"
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clcik"
android:text="Submit"/>

</LinearLayout>

MainActivity.java
package com.example.pr28;

import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

TextView tx1;
Button b;
EditText ed1, ed2;
int counter = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tx1 = findViewById(R.id.textView2);
b = findViewById(R.id.button);
ed1 = findViewById(R.id.editTextTextPersonName);
ed2 = findViewById(R.id.editTextTextPassword);
tx1.setVisibility(View.GONE);
}

public void clcik(View view) {


if(ed1.getText().toString().equals("")){
ed1.setError("Plz Enter Username...");
}
else if(ed2.getText().toString().equals("")){
ed2.setError("Plz Enter Password...");
}
else if(ed2.getText().toString().length() < 8){
ed2.setError("Plz Enter 8 Digits Password...");
}
else if (ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("ibrahim1")) {
Toast.makeText(getApplicationContext(), "Redirecting...",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();

tx1.setVisibility(View.VISIBLE);
counter--;
tx1.setText(Integer.toString(counter));

if (counter == 0) {
b.setEnabled(false);
b.setBackgroundColor(Color.RED);
}
}
}
}
Output:
X. Exercise
1. Write a program to send, make use of following GUI.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Phone Number"/>

<EditText
android:id="@+id/phoneno"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="SMS Message"/>

<EditText
android:id="@+id/msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<Button
android:id="@+id/send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send SMS"/>

</LinearLayout>

MainActivity.java
package com.example.pr29;
import android.os.Bundle;
import android.app.Activity;
import android.telephony.SmsManager;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
String phoneNo;
String message;

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

sendBtn = (Button) findViewById(R.id.send);


txtphoneNo = (EditText) findViewById(R.id.phoneno);
txtMessage = (EditText) findViewById(R.id.msg);

sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}

protected void sendSMSMessage() {


phoneNo = txtphoneNo.getText().toString();
message = txtMessage.getText().toString();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
}
}

Output:
X. Exercise
Receive SMS
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<ImageView
android:layout_marginTop="90dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img"
android:layout_gravity="center"/>

</LinearLayout>

MainActivity.java
package com.example.smsrecive;

import androidx.appcompat.app.AppCompatActivity;

import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {

private static final String SMS_RECEIVED_ACTION =


"android.provider.Telephony.SMS_RECEIVED";

private SmsReceiver smsReceiver;

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

smsReceiver = new SmsReceiver();


IntentFilter filter = new IntentFilter(SMS_RECEIVED_ACTION);
registerReceiver(smsReceiver, filter);
}

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}
}

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

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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Smsrecive"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>

</manifest>

SmsReceiver.java
package com.example.smsrecive;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
if
(intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null && pdus.length > 0) {
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])
pdus[i]);
}
String sender = messages[0].getOriginatingAddress();
String messageBody = messages[0].getMessageBody();
Toast.makeText(context, "SMS received from " + sender +
": " + messageBody, Toast.LENGTH_LONG).show();
}}}}}
Output:
X. Exercise:
1) Write a program to send email.
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">
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginTop="18dp"
android:layout_marginRight="22dp" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_alignLeft="@+id/editText1"
android:layout_marginTop="20dp" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2"
android:layout_marginTop="30dp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="Send To:"
android:textColor="#0F9D58" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Email Subject:"
android:textColor="#0F9D58" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText3"
android:layout_alignBottom="@+id/editText3"
android:text="Email Body:"
android:textColor="#0F9D58" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:layout_alignLeft="@+id/editText3"
android:layout_marginLeft="76dp"
android:layout_marginTop="20dp"
android:text="Send email!!" />
</RelativeLayout>

MainActivity.java
package com.example.pr30;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

// define objects for edit text and button


Button button;
EditText sendto, subject, body;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendto = findViewById(R.id.editText1);
subject = findViewById(R.id.editText2);
body = findViewById(R.id.editText3);
button = findViewById(R.id.button);
button.setOnClickListener(view -> {
String emailsend = sendto.getText().toString();
String emailsubject = subject.getText().toString();
String emailbody = body.getText().toString();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailsend});
intent.putExtra(Intent.EXTRA_SUBJECT, emailsubject);
intent.putExtra(Intent.EXTRA_TEXT, emailbody);
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent, "Choose an Email
client :"));
});
}
}
Output:
X. Exercise
1. Write a program to locate user’s current location.
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get Current Location and City Name"
android:textAlignment="center"
android:layout_centerHorizontal="true"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold"/>
</RelativeLayout>

MainActivity.java
package com.example.pr30;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient fusedLocationClient;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 2;
private LocationAddressResultReceiver addressResultReceiver;
private TextView currentAddTv;
private Location currentLocation;
private LocationCallback locationCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addressResultReceiver = new LocationAddressResultReceiver(new
Handler());
currentAddTv = findViewById(R.id.textView);
fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
currentLocation = locationResult.getLocations().get(0);
getAddress();
}
};
startLocationUpdates();
}
@SuppressWarnings("MissingPermission")
private void startLocationUpdates() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new

String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
else {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(2000);
locationRequest.setFastestInterval(1000);

locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback, null);
}
}
@SuppressWarnings("MissingPermission")
private void getAddress() {
if (!Geocoder.isPresent()) {
Toast.makeText(MainActivity.this, "Can't find current address,
",
Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(this, GetAddressIntentService.class);
intent.putExtra("add_receiver", addressResultReceiver);
intent.putExtra("add_location", currentLocation);
startService(intent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions, @NonNull
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
startLocationUpdates();
} else {
Toast.makeText(this, "Location permission not granted, " +
"restart the app if you want the feature", Toast.LENGTH_SHORT).show();
}
}
}
private class LocationAddressResultReceiver extends ResultReceiver {
LocationAddressResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == 0) {
Log.d("Address", "Location null retrying");
getAddress();
}
if (resultCode == 1) {
Toast.makeText(MainActivity.this, "Address not found, ",
Toast.LENGTH_SHORT).show();
}
String currentAdd = resultData.getString("address_result");
showResults(currentAdd);
}
}
private void showResults(String currentAdd) {
currentAddTv.setText(currentAdd);
}
@Override
protected void onResume() {
super.onResume();
startLocationUpdates();
}
@Override
protected void onPause() {
super.onPause();
fusedLocationClient.removeLocationUpdates(locationCallback);
}
}

GetAddressIntentService.java
package com.example.pr30;
import android.app.IntentService;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import androidx.annotation.Nullable;
public class GetAddressIntentService extends IntentService {
private static final String IDENTIFIER = "GetAddressIntentService";
private ResultReceiver addressResultReceiver;
public GetAddressIntentService() {
super(IDENTIFIER);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
String msg;
addressResultReceiver =
Objects.requireNonNull(intent).getParcelableExtra("add_receiver");
if (addressResultReceiver == null) {
Log.e("GetAddressIntentService", "No receiver, not processing
the request further");
return;
}
Location location = intent.getParcelableExtra("add_location");
if (location == null) {
msg = "No location, can't go further without location";
sendResultsToReceiver(0, msg);
return;
}
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
}
catch (Exception ioException) {
Log.e("", "Error in getting address for the location");
}
if (addresses == null || addresses.size() == 0) {
msg = "No address found for the location";
sendResultsToReceiver(1, msg);
}
else {
Address address = addresses.get(0);
String addressDetails = address.getFeatureName() + " " +
address.getThoroughfare() + " " + "Locality: " + address.getLocality() + "
" + "County: " + address.getSubAdminArea() + " " + "State: " +
address.getAdminArea() + " " + "Country: " + address.getCountryName() + " "
+ "Postal Code: " + address.getPostalCode() + " ";
sendResultsToReceiver(2, addressDetails);
}
}
private void sendResultsToReceiver(int resultCode, String message) {
Bundle bundle = new Bundle();
bundle.putString("address_result", message);
addressResultReceiver.send(resultCode, bundle);
}
}

Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.pr30">

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Pr30"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
<service android:name=".GetAddressIntentService" />
</application>

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

</manifest>

Output:
X. Exercise
Write a program to draw a route between two locations.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />

build.gradle
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'

//Google Maps
implementation 'com.google.android.gms:play-services-maps:16.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

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

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

<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
</application>
</manifest>

DataParser.Java
package com.example.mapdirectiondemo;

import com.google.android.gms.maps.model.LatLng;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class DataParser {

/**
* Receives a JSONObject and returns a list of lists containing
latitude and longitude
*/
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

List<List<HashMap<String, String>>> routes = new


ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;

try {

jRoutes = jObject.getJSONArray("routes");

/** Traversing all routes */


for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();

/** Traversing all legs */


for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject)
jLegs.get(j)).getJSONArray("steps");

/** Traversing all steps */


for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject)
jSteps.get(k)).get("polyline")).get("points");
List list = decodePoly(polyline);

/** Traversing all points */


for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new
HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)
list.get(l)).latitude));
hm.put("lng", Double.toString(((LatLng)
list.get(l)).longitude));
path.add(hm);
}
}
routes.add(path);
}
}

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

return routes;
}

/**
* Method to decode polyline points
*/
private List decodePoly(String encoded) {

List poly = new ArrayList();


int index = 0, len = encoded.length();
int lat = 0, lng = 0;

while (index < len) {


int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >>
1));
lat += dlat;

shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >>
1));
lng += dlng;

LatLng p = new LatLng((((double) lat / 1E5)),


(((double) lng / 1E5)));
poly.add(p);
}

return poly;
}
}

MainActivity.Java
package com.example.mapdirectiondemo;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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.PolylineOptions;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.fragment.app.FragmentActivity;

public class MapsActivity extends FragmentActivity implements


OnMapReadyCallback {

private GoogleMap mMap;

MarkerOptions origin, destination;

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

// Obtain the SupportMapFragment and get notified when the map is


ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

//Setting marker to draw route between these two points


origin = new MarkerOptions().position(new LatLng(12.9121,
77.6446)).title("HSR Layout").snippet("origin");
destination = new MarkerOptions().position(new LatLng(12.9304,
77.6784)).title("Bellandur").snippet("destination");

// Getting URL to the Google Directions API


String url = getDirectionsUrl(origin.getPosition(),
destination.getPosition());

DownloadTask downloadTask = new DownloadTask();

// Start downloading json data from Google Directions API


downloadTask.execute(url);

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.addMarker(origin);
mMap.addMarker(destination);

mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin.getPosition(),
10));
}

private class DownloadTask extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... url) {

String data = "";

try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}

/**
* A class to parse the JSON format
*/
private class ParserTask extends AsyncTask<String, Integer,
List<List<HashMap<String, String>>>> {

// Parsing the data in non-ui thread


@Override
protected List<List<HashMap<String, String>>>
doInBackground(String... jsonData) {

JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;

try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();

routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}

@Override
protected void onPostExecute(List<List<HashMap<String, String>>>
result) {
ArrayList points = new ArrayList();
PolylineOptions lineOptions = new PolylineOptions();

for (int i = 0; i < result.size(); i++) {


List<HashMap<String, String>> path = result.get(i);

for (int j = 0; j < path.size(); j++) {


HashMap<String, String> point = path.get(j);

double lat = Double.parseDouble(point.get("lat"));


double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);

points.add(position);
}

lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);

// Drawing polyline in the Google Map


if (points.size() != 0)
mMap.addPolyline(lineOptions);
}
}

private String getDirectionsUrl(LatLng origin, LatLng dest) {

// Origin of route
String str_origin = "origin=" + origin.latitude + "," +
origin.longitude;

// Destination of route
String str_dest = "destination=" + dest.latitude + "," +
dest.longitude;

//setting transportation mode


String mode = "mode=driving";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor +
"&" + mode;

// Output format
String output = "json";

// Building the url to the web service


String url = "https://maps.googleapis.com/maps/api/directions/" +
output + "?" + parameters + "&key=" +
"AIzaSyD_L8g3AcwXBKnEjhvLJwBXwI3L51LjQUU";

return url;
}

/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);

urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.connect();

iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new


InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";


while ((line = br.readLine()) != null) {
sb.append(line);
}

data = sb.toString();

br.close();

} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}

Output:

You might also like