Mad Output 9all
Mad Output 9all
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;
@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.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
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 :
<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
Subject : MAD
Practical : 06
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
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 buons are without
using radio group and next two radio buons are using radio group. Note the changes
between these two. Also toast which radio buon has been selected.
XML CODE:-
<?xml version="1.0" encoding="u-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="hp://schemas.android.com/apk/res/android"
xmlns:app="hp://schemas.android.com/apk/res-auto"
xmlns:tools="hp://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainAcvity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Single Radio buons"
android:textColor="@color/black"
android:textSize="25dp"
app:layout_constraintBoom_toBoomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVercal_bias="0.074" />
<RadioBuon
android:id="@+id/rb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioBuon"
android:textSize="20dp"
app:layout_constraintBoom_toBoomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.192"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVercal_bias="0.291" />
<RadioBuon
android:id="@+id/rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioBuon"
android:textSize="20dp"
app:layout_constraintBoom_toBoomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.192"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVercal_bias="0.202" />
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_marginTop="20dp"
android:background="#B8B894"
app:layout_constraintBoom_toBoomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVercal_bias="0.384" />
<!-- Customized RadioBuons -->
<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 buon inside RadioGroup"
android:textSize="25dp"
app:layout_constraintBoom_toBoomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVercal_bias="0.43" />
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBoom_toBoomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVercal_bias="0.62"
app:layout_constraintHorizontal_bias="0.20">
<RadioBuon
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" />
<RadioBuon
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>
<Buon
android:id="@+id/buon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="onclickbuonMethod"
android:text="Show Selected"
android:backgroundTint="#60BFBF"
app:layout_constraintBoom_toBoomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVercal_bias="0.786" />
</androidx.constraintlayout.widget.ConstraintLayout>
Acvity_main.java :-
package com.example.p_12;
import androidx.appcompat.app.AppCompatAcvity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioBuon;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainAcvity extends AppCompatAcvity {
TextView t1,t2;
RadioBuon rgb;
RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acvity_main);
rg =(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuonMethod(View v) {
int selectedId = rg.getCheckedRadioBuonId();
rgb = (RadioBuon) findViewById(selectedId);
if (selectedId == -1) {
Toast.makeText(MainAcvity.this, "Nothing selected",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainAcvity.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
<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();
<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;
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();
}
});
}
}
<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;
@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;
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;
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;
@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;
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);
}
<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" />
</manifest>
<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;
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;
@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");
}
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;
btnlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
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);
}
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
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 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@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">
<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;
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;
@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;
/**
* Receives a JSONObject and returns a list of lists containing
latitude and longitude
*/
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
try {
jRoutes = jObject.getJSONArray("routes");
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
/**
* Method to decode polyline points
*/
private List decodePoly(String encoded) {
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;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.addMarker(origin);
mMap.addMarker(destination);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin.getPosition(),
10));
}
@Override
protected String doInBackground(String... url) {
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>>>> {
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();
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
// Origin of route
String str_origin = "origin=" + origin.latitude + "," +
origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," +
dest.longitude;
// Output format
String output = "json";
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.connect();
iStream = urlConnection.getInputStream();
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
Output: