Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Practical 5 Q1.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> Output:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/r
es/android"
xmlns:app="http://schemas.android.com/apk/re
s-auto"
xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingLeft="16dp"

android:paddingRight="16dp"

android:paddingTop="16dp"

android:orientation="vertical"

tools:context=".MainActivity">

<TextView

android:id="@+id/student_name"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Name:" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Age:" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Mobile Number:" />

</LinearLayout>
Practical 6 Q2.

activity_main.xml </FrameLayout>
<FrameLayout
<TableLayout android:layout_width="match_parent"
android:layout_width="match_parent" android:layout_height="match_parent"
android:layout_height="500dp" android:layout_column="1"
android:padding="20dp" > android:padding="10dp"
<TextView android:layout_marginLeft="30dp"
android:layout_width="match_parent" android:background="@drawable/boarder">
android:layout_height="85dp" <TextView
android:text="Data Types in Object Oriented android:layout_width="wrap_content"
Programming" android:layout_height="wrap_content"
android:textAlignment="center" android:text="Non-Primitive"
android:textSize="25dp" android:textSize="25dp" />
android:textStyle="bold" <TextView
android:background="@drawable/boarder"/> android:layout_width="wrap_content"
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:layout_marginTop="40dp"
android:background="@drawable/boarder"> android:text="1) Class" />
<FrameLayout <TextView
android:layout_height="match_parent" android:layout_width="wrap_content"
android:layout_width="150dp" android:layout_height="wrap_content"
android:layout_column="1" android:layout_marginTop="60dp"
android:padding="10dp" android:text="2) Array" />
android:background="@drawable/boarder" > <TextView
<TextView android:layout_width="wrap_content"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:layout_marginTop="80dp"
android:text="Primitive" android:text="3) Interface" />
android:textSize="25dp" /> <TextView
<TextView android:layout_width="wrap_content"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:layout_marginTop="100dp"
android:layout_marginTop="40dp" android:text="4) Object" />
android:text="1) Integer" /> </FrameLayout>
<TextView </TableRow>
android:layout_width="wrap_content" </TableLayout>
android:layout_height="wrap_content"
android:layout_marginTop="60dp" Output :
android:text="2) Float" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="3) Characters" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:text="4) Boolean" />
Practical6 Q1

activity_main.xml android:layout_height="wrap_content"
android:layout_column="3" android:text="TYCO"
<?xml version="1.0" encoding="UTF-8"?> android:textColor="#000" /> </TableRow>
<TableLayout <TableRow android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/re android:layout_height="wrap_content">
s/android" <TextView android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res- android:layout_width="125dp" android:text="302 "
auto" android:textColor="#000"
xmlns:tools="http://schemas.android.com/tools" android:layout_column="1" /> <TextView
android:layout_width="match_parent" android:layout_width="125dp"
android:layout_height="match_parent" android:layout_height="wrap_content"
tools:context=".MainActivity" android:layout_column="2" android:text="Soham"
android:padding="20dp" android:textColor="#000" /> <TextView
android:orientation="horizontal"> <TextView android:layout_width="125dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_width="match_parent" android:layout_column="3" android:text="Fyco"
android:text="Student information" android:textColor="#000" /> </TableRow>
android:textSize="30dp" <TableRow android:layout_width="match_parent"
android:textAlignment="center" android:layout_height="wrap_content">
android:background="@drawable/boarder" <TextView android:layout_height="wrap_content"
android:textColor="#000" /> <TableLayout android:layout_width="125dp" android:text="303 "
android:background="@drawable/boarder" android:textColor="#000"
android:layout_width="match_parent" android:layout_column="1" /> <TextView
android:layout_height="wrap_content"> android:layout_width="125dp"
<TableRow android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_height="wrap_content"> android:layout_column="2"
<TextView android:layout_height="wrap_content" android:text="Shaarika" android:textColor="#000"
android:layout_width="125dp" android:text="Roll /> <TextView android:layout_width="125dp"
No " android:textColor="#000" android:layout_height="wrap_content"
android:textSize="20dp" android:textStyle="bold" android:layout_column="3" android:text="Syco"
android:layout_column="1" /> <TextView android:textColor="#000" /> </TableRow>
android:layout_height="wrap_content" <TableRow android:layout_width="match_parent"
android:layout_width="125dp" android:text=" android:layout_height="wrap_content">
Name " android:textColor="#000" <TextView android:layout_height="wrap_content"
android:textSize="20dp" android:textStyle="bold" android:layout_width="125dp" android:text="304 "
android:layout_column="2" /> <TextView android:textColor="#000"
android:layout_width="125dp" android:layout_column="1" /> <TextView
android:layout_height="wrap_content" android:layout_width="125dp"
android:textColor="#000" android:textSize="20dp" android:layout_height="wrap_content"
android:layout_column="3" android:layout_column="2" android:text="Ketan"
android:textStyle="bold" android:text=" Class " /> android:textColor="#000" /> <TextView
</TableRow> <TableRow android:layout_width="125dp"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_height="wrap_content"> android:layout_column="3" android:text="Tyco"
<TextView android:layout_height="wrap_content" android:textColor="#000" /> </TableRow>
android:layout_width="125dp" android:text=" 301 <TableRow android:layout_width="match_parent"
" android:textColor="#000" android:layout_height="wrap_content">
android:layout_column="1" /> <TextView <TextView android:layout_width="125dp"
android:layout_width="125dp" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:layout_column="1" android:text="305"
android:layout_column="2" android:text="Sameer" android:textColor="#000" /> <TextView
android:textColor="#000" /> <TextView android:layout_width="125dp"
android:layout_width="125dp"
Practical6 Q1

android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_column="2" android:text="Tejas" android:layout_column="1" android:text="309"
android:textColor="#000" /> <TextView android:textColor="#000" /> <TextView
android:layout_width="125dp" android:layout_width="125dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_column="3" android:text="TYCO" android:layout_column="2" android:text="rohit"
android:textColor="#000" /> </TableRow> android:textColor="#000" /> <TextView
<TableRow android:layout_width="match_parent" android:layout_width="125dp"
android:layout_height="wrap_content"> android:layout_height="wrap_content"
<TextView android:layout_width="125dp" android:layout_column="3" android:text="TYCO"
android:layout_height="wrap_content" android:textColor="#000" /> </TableRow>
android:layout_column="1" android:text="306" <TableRow android:layout_width="match_parent"
android:textColor="#000" /> <TextView android:layout_height="wrap_content">
android:layout_width="125dp" <TextView android:layout_width="125dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_column="2" android:layout_column="1" android:text="310"
android:text="vaishnavi" android:textColor="#000" android:textColor="#000" /> <TextView
/> <TextView android:layout_width="125dp" android:layout_width="125dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_column="3" android:text="FYCO" android:layout_column="2" android:text="sujit"
android:textColor="#000" /> </TableRow> android:textColor="#000" /> <TextView
<TableRow android:layout_width="match_parent" android:layout_width="125dp"
android:layout_height="wrap_content"> android:layout_height="wrap_content"
<TextView android:layout_width="125dp" android:layout_column="3" android:text="TYCO"
android:layout_height="wrap_content" android:textColor="#000" /> </TableRow>
android:layout_column="1" android:text="307" </TableLayout> </TableLayout>
android:textColor="#000" /> <TextView
Output:
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_column="2" android:text="nikita"
android:textColor="#000" /> <TextView
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_column="3" android:text=" SYCO"
android:textColor="#000" /> </TableRow>
<TableRow android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_column="1" android:text="308"
android:textColor="#000" /> <TextView
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_column="2" android:text="yash"
android:textColor="#000" /> <TextView
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_column="3" android:text="TYCO"
android:textColor="#000" /> </TableRow>
<TableRow android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="125dp"
Practical 7 Q1.

activity_main.xml <TextView
android:layout_height="wrap_content"
<?xml version="1.0" encoding="utf-8"?> android:layout_weight="1"
<TableLayout android:gravity="center"
xmlns:android="http://schemas.android.com/a android:text="Enter Password:" />
pk/res/android"
xmlns:app="http://schemas.android.com/ap
k/res-auto" <EditText
xmlns:tools="http://schemas.android.com/to android:id="@+id/pass"
ols" android:layout_height="wrap_content"
android:layout_width="match_parent" android:layout_weight="1"
android:layout_height="match_parent" android:hint="1234" />
android:padding="50dp" </TableRow>
tools:context=".MainActivity">
<Button
<TextView android:id="@+id/btn1"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:gravity="center" android:layout_marginBottom="172dp"
android:textSize="25dp" android:text="Login" />
android:text="Login Page" />
</TableLayout>
<TableRow
android:layout_width="match_parent" Output:
android:layout_height="wrap_content"
android:gravity="center_horizontal">

<TextView
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Enter UserName:" />

<EditText
android:id="@+id/user"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="abc@gmail.com" />
</TableRow>

<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
Practical 8 Q2.

activity_main.xml MainActivity.java

<androidx.constraintlayout.widget.ConstraintLa public class practt8 extends AppCompatActivity


yout {
xmlns:android="http://schemas.android.com/apk String[] language ={"Mobile Application
/res/android" Development","Programming in
Python","Entrepreneurship
xmlns:app="http://schemas.android.com/apk/res Development","ETI","Management"};
-auto" @Override
protected void onCreate(Bundle
xmlns:tools="http://schemas.android.com/tools" savedInstanceState) {
android:layout_width="match_parent" super.onCreate(savedInstanceState);
android:layout_height="match_parent" setContentView(R.layout.activity_practt8);
Toolbar toolbar =
app:layout_behavior="@string/appbar_scrolling findViewById(R.id.toolbar);
_view_behavior" setSupportActionBar(toolbar);
tools:context=".practt8" ArrayAdapter<String> adapter = new
android:padding="30dp" ArrayAdapter<String>
tools:showIn="@layout/activity_practt8">
<TextView (this,android.R.layout.select_dialog_item,langua
android:layout_width="wrap_content" ge);
android:layout_height="wrap_content" //Getting the instance of
android:text=" Practical 8 \nSixth Sem AutoCompleteTextView
Subjects" AutoCompleteTextView actv =
android:textSize="30dp" (AutoCompleteTextView)findViewById(R.id.au
app:layout_constraintBottom_toBottomOf="par toCompleteTextView);
ent" actv.setThreshold(1);//will start working
app:layout_constraintLeft_toLeftOf="parent" from first character
app:layout_constraintRight_toRightOf="parent" actv.setAdapter(adapter);
app:layout_constraintTop_toTopOf="parent" }}
app:layout_constraintVertical_bias="0.032" Output :
/>
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="244dp"
android:text=" Subject name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLa
yout>
01234532689
 
2345544846958 6 4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5'
4%,!$#,;<#%5&'."!%4 '
!"#$%&'()*'%+$,#%-&'./012'3 4==;46$75@+$%"5!4#%5E$55$@5$E$55$LK&'=4!%5
4%,!$#,)+$%"5!4#%546$75)8#,-5)9$%"5!4#%5:46$7 '4==;46$75@+$%"5!4#%5M%,@5$M%,LK&'=4!%5'
5 4==;46$75@+$%"5!4#%5H54!5@5$H54!5LK&'=4!%5'
%";4%,!$#,&'<55=;>>"+<4")4%,!$#,)+$>4=?>! 4==;46$75@+$%"5!4#%5/$=@5$/$=LK&'=4!%5'3
">4%,!$#,' +$)-$$-)4%,!$#,)45!#4)55K#,)/5O%=75M
%";4==&'<55=;>>"+<4")4%,!$#,)+$>4=?>!"1 ,#5/54%,!$#,;46$75@8#,5<&'45+<@=4!%5'
475$' 4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5'
%";5$$"&'<55=;>>"+<4")4%,!$#,)+$>5$$"' 4%,!$#,;#%=75/6=&'55'
4%,!$#,;46$75@8#,5<&'45+<@=4!%5' 4%,!$#,;#,&'BD#,>5K@"57,@7"!%4 '
4%,!$#,;46$75@<#-<5&'45+<@=4!%5' 4%,!$#,;,!484AH54!5&'B,!484A>#+@=!"$%'
4%,!$#,;A4+?-!$7%,&'B,!484A>$-#%4,#%@A4+ 4%,!$#,;,!484AT4,,#%-&'(*,='>3
?-!$7%,'3/5C#8 >+$)-$$-)4%,!$#,)45!#4)55K#,)/5O%=75:
4%,!$#,;#,&'BD#,>55C#8' 46$753>:#%4!:46$753:#%4!:46$75
4%,!$#,;46$75@8#,5<&'8!4=@+$%5%5' 4%,!$#,;46$75@8#,5<&'45+<@=4!%5'
4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5' 4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5'
4%,!$#,;46$75@4!-#%E$55$&'FG2,=' 4%,!$#,;46$75@4!-#%&'G*,='
4%,!$#,;55&'H57,%5:$-#%' 4%,!$#,;$!#%545#$%&'<$!#I$%54'
4%,!$#,;559$$!&'B4%,!$#,;+$$!>8<#5' 4%,!$#,;=4,,#%-&'F,='
4%,!$#,;55H#I&'J*,='4%,!$#,;55H56&'A$,' 5$$";#-%$!&'R#""#%-9$%"5!4#%5"'3
4%,!$#,;K$%504#6&'"4%"1"!#K1"4+4="' +$)-$$-)4%,!$#,)45!#4)55K#,)/5O%=75:
4==;46$75@+$%"5!4#%5E$55$@5$E$55$LK&'=4!%5 46$75
'4==;46$75@+$%"5!4#%5M%,@5$M%,LK&'=4!%5' "56&'B"56>S#,-5)R45!#49$=$%%5")/5O%
4==;46$75@+$%"5!4#%5H54!5@5$H54!5LK&'=4!%5' =75:46$75)L75#%,E$'
4==;46$75@+$%"5!4#%5/$=@5$/$=LK&'=4!%5' 4%,!$#,;46$75@8#,5<&'45+<@=4!%5'
4==;46$75@+$%"5!4#%5C !5#+4@A#4"&'*)FNJ'>3 4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5'
:#%4!:46$75 4%,!$#,;<#%5&'T4""8$!,'
4%,!$#,;46$75@8#,5<&'45+<@=4!%5' 4==;=4""8$!,/$--M%4A,&'5!7'
4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5' 4==;46$75@+$%"5!4#%5E$55$@5$E$55$LK&'=4!%5
4%,!$#,;46$75@4!-#%&'G*,=' '4==;46$75@+$%"5!4#%5M%,@5$M%,LK&'=4!%5'
4%,!$#,;A4+?-!$7%,&'B,!484A>A$!,!@+4!,' 4==;46$75@+$%"5!4#%5H54!5@5$H54!5LK&'=4!%5'
4%,!$#,;$!#%545#$%&'!5#+4' 4==;46$75@+$%"5!4#%5/$=@5$/$=LK&'=4!%5'3
4%,!$#,;=4,,#%-&'(*,=' +$)-$$-)4%,!$#,)45!#4)55K#,)/5O%=75M
4==;46$75@+$%"5!4#%5M%,@5$H54!5LK&'=4!%5' ,#5/54%,!$#,;46$75@8#,5<&'45+<@=4!%5'
4==;46$75@+$%"5!4#%5H54!5@5$M%,LK&'=4!%5' 4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5'
4==;46$75@+$%"5!4#%5/$=@5$E$55$LK&'BD#,>55 4%,!$#,;,!484AH54!5&'B,!484A>#+@$+?'
C#8'3O4-C#8 4%,!$#,;,!484AT4,,#%-&'(*,='
4%,!$#,;46$75@8#,5<&'P*,=' 4%,!$#,;#%=75/6=&'%7A!T4""8$!,'
4%,!$#,;46$75@<#-<5&'P*,=' 4%,!$#,;#,&'BD#,>5K@"57,@=4""8$!,'>3
4%,!$#,;46$75@-!4#56&'+%5!' >+$)-$$-)4%,!$#,)45!#4)55K#,)/5O%=75:
4%,!$#,;46$75@4!-#%&'(*,=' 46$753>:#%4!:46$753:#%4!:46$75
4%,!$#,;"!+&'B,!484A>4,#%@$-#%@=!$K#'>3 4%,!$#,;46$75@8#,5<&'45+<@=4!%5'
:#%4!:46$75 4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5'
4%,!$#,;46$75@8#,5<&'45+<@=4!%5' 4%,!$#,;46$75@4!-#%:K5&'G*,='
4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5' 4%,!$#,;46$75@4!-#%Q#-<5&'G*,='
4%,!$#,;46$75@4!-#%:K5&'G*,=' 4%,!$#,;$!#%545#$%&'<$!#I$%54'
4%,!$#,;46$75@4!-#%Q#-<5&'G*,=' 4%,!$#,;=4,,#%-&'F,='
4%,!$#,;$!#%545#$%&'!5#+4' 5$$";#-%$!&'R#""#%-9$%"5!4#%5"'
4%,!$#,;=4,,#%-&'F,=' 4%,!$#,;8 #-<5H7&'G'3
5$$";#-%$!&'R#""#%-9$%"5!4#%5"'3 +$)-$$-)4%,!$#,)45!#4)55K#,)/5O%=75:
+$)-$$-)4%,!$#,)45!#4)55K#,)/5O%=75: 46$75
46$75 "56&'B"56>S#,-5)R45!#49$=$%%5")/5O%
"56&'B"56>S#,-5)R45!#49$=$%%5")/5O% =75:46$75)L75#%,E$'
=75:46$75)L75#%,E$' 4%,!$#,;46$75@8#,5<&'J**,='
4%,!$#,;46$75@8#,5<&'45+<@=4!%5' 4%,!$#,;46$75@<#-<5&'8!4=@+$%5%5'
01234532689
 
!"#$%&'$ $
(()*+,-$ (+)$)--$-$/-$
(()./01$ L((@3(L)A$$O$
(()-2323%,( $(A$2$+-K$
$(()-**%,($ $$$$(A$&/7(*&/$,--3K$
(()-44%,($ $$$$(A$&/7(*&/$,-(--K$
(()-&(&(%,(5$ $$$$8%A$
6)3"""3"/,"&/7(* $$$$()$A$@P2$
&/$3)($ -A7-)4Q$O$
()$ $$$$$$$$-("@P-A7-)4QK$$$$$$
+48+9)+-- -@MPN"")A-QK$
:1$+';!($ $$$$$$$$4((L)2PQ"PQK$$$
(&(3+'--$ ,-(--,M27PN"",-(--
3/01$ QK$$$$$
8<9,-($95$ ,--3,M27PN"",--
69)3"""3"/,"&/7(0 3QK$
5$62$8<9+-($ +-,M27PN""+-
3)($ QK$
3&(=($ $$$$$$$+-"-%@)?0-P$
30,=($ M"%@)?0-PQ$O$
=!($ $$$$$$$$$$$8%A$
;">$ $$$$$$$$$$$(+)$A$@)?PM$AQ$O$
+)?8+9)-3+$ $$$$$$$$$$$$$$$
/-$($ ,P,--3"&/PQ"4PQ"3PQ"R
/@8)9$95$ -P3QSS,-(--"&/PQ"4
69005$62$ PQ"3PQ"R-P;:>1QQO$
8<9+-$ $$$$$$$$$$$$$$$$$$$
3)($ &-"3?&/P-"-T0$
=!($ 4))--,$T&-"0*UV&W0%UVQ"-PQK$
A$ $$$$$$$$$$$$$$$X$$-O$
3:!($ $$$$&-"3?&/P-"-T0$Y$
+)?8+9)-3+$ T&-"0*UV&W0%UVQ"-PQK$
/0$ $
/@8)9$ $$X$X$XQKXX$
/4B;=($95$69005$ ZD4[D4\
69/")-""@-0
5$
C4DEF84G69H58 I2J2
()?$)3"(;"(("-K$
3($
/"(()3("(("L((@3(L)AK$
3($"-"2K$
3($"A"MK$
3($""2K$
3($""&-K$
3($
)3"""3"/,"&/7(*
&/K$
3($)3"(;"(("NK$
Practical 13

Q.1:activity_main.xml Q.2 activity_main.xml

<?xml version="1.0" <?xml version="1.0" encoding="UTF-


encoding="UTF-8"?> 8"?> <RelativeLayout
<RelativeLayout xmlns:android="http://schemas.andr
xmlns:android="http://schemas.a oid.com/apk/res/android"
xmlns:app="http://schemas.android.
ndroid.com/apk/res/android"
com/apk/res-auto"
xmlns:app="http://schemas.andro
xmlns:tools="http://schemas.androi
id.com/apk/res-auto" d.com/tools"
xmlns:tools="http://schemas.and android:layout_width="match_parent
roid.com/tools" "
android:layout_width="match_par android:layout_height="match_paren
ent" t" tools:context=".MainActivity">
android:layout_height="match_pa <Button
rent" android:layout_width="wrap_content
tools:context=".MainActivity"> "
android:layout_height="wrap_conten
<ProgressBar
t" android:text="Download File"
android:id="@+id/progressBar"
android:layout_centerInParent="tru
style="?android:attr/progressBa e" android:id="@+id/btn" />
rStyle" </RelativeLayout>
android:layout_width="200dp"
android:layout_height="200dp" MainActivity.java
android:layout_centerInParent=" public class MainActivity extends
true" AppCompatActivity { Button btn;
android:indeterminate="false" ProgressBar pgr;
android:max="100" ProgressDialog progressDialog;
android:progress="65" /> @Override
</RelativeLayout> protected void onCreate(Bundle
savedInstanceState) {
Output : super.onCreate(savedInstanceState
);
setContentView(R.layout.activity_
main);
btn=findViewById(R.id.btn);
btn.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog = new
ProgressDialog(MainActivity.this)
; progressDialog.setTitle("File
downloading....");
progressDialog.setProgressStyle(P
rogressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(fals
e); progressDialog.show();
progressDialog.setProgress(40);
}
});
} }
Practical 14.

activity_main.xml ArrayAdapter<String> arr;


arr = new ArrayAdapter<String>(this,
<?xml version="1.0" encoding="utf-8"?>
androidx.appcompat.R.layout.support_simpl
<RelativeLayout
e_spinner_dropdown_item, Subjectname);
xmlns:android="http://schemas.android.com
Listview.setAdapter(arr);
/apk/res/android"
Listview.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
xmlns:app="http://schemas.android.com/apk
@Override
/res-auto"
public void
onItemClick(AdapterView<?> arg0, View
xmlns:tools="http://schemas.android.com/to
arg1, int position, long arg3) {
ols"
Toast.makeText(MainActivity.this,
android:layout_width="match_parent"
"Subject Name :" + ((TextView
android:layout_height="match_parent"
)arg1).getText().toString(),
tools:context=".MainActivity">
Toast.LENGTH_SHORT).show();
}
<ListView
});
android:padding="40dp"
}
android:layout_width="match_parent"
}
android:layout_height="match_parent"
android:id="@+id/Listview"/>
</RelativeLayout> output :

MainActivity.java

public class MainActivity extends


AppCompatActivity {
ListView Listview;
private String
Subjectname[]={"Android","java","php","ha
doop","sap","python","ajax","cpp","Ruby","
Rails"};

@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Listview=findViewById(R.id.Listview);
Practical 14.

Q.2 activity_main.xml btn=findViewById(R.id.btn);

<RelativeLayout imagev.setImageResource(R.drawable.smile
xmlns:android="http://schemas.android.com y); btn.setOnClickListener(new
/apk/res/android" View.OnClickListener() { @Override public

xmlns:app="http://schemas.android.com/apk void onClick(View view) { if(a==0) {


/res-auto" imagev.setImageResource(R.drawable.smile
ysad); a=1; } else{
xmlns:tools="http://schemas.android.com/to
imagev.setImageResource(R.drawable.smile
ols"
android:layout_width="match_parent" y); a=0; } } }); } }
android:layout_height="match_parent"
tools:context=".MainActivity" output :
android:padding="40dp">

<ImageView
android:id="@+id/imagev"
android:layout_width="match_parent"
android:layout_height="400dp" />

<Button
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_below="@id/imagev"
android:layout_marginTop="110dp"
android:text="Change Image"
android:id="@+id/btn"/>
</RelativeLayout>

MainActivity.xml

public class MainActivity extends


AppCompatActivity { ImageView imagev;
Button btn; int a= 0; @Override protected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagev =findViewById(R.id.imagev);
Practical 14.

Q.3 Activit_main.xml super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);
<?xml version= "1.0" encoding= "utf-8" ?>
gridview = findViewById(R.id.gridview);
<GridView
for (int i = 0; i < 15; i++) { arr[i] =
xmlns:android="http://schemas.android.com
Integer.toString(i + 1); }
/apk/res/android"
ArrayAdapter<String> ad = new
xmlns:tools="http://schemas.android.com/
ArrayAdapter<String>(this,
tools"
R.layout.activity_listview, R.id.btn, arr);
android:id="@+id/gridview"
gridview.setAdapter(ad); } }
android:layout_width="fill_parent"
android:layout_height="fill_parent" output :
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"
tools:context=".MainActivity">

</GridView>

activity_listview.xml :

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


<LinearLayout
xmlns:android="http://schemas.android.com
/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</LinearLayout>

MainActivity.java

public class MainActivity extends


AppCompatActivity { GridView gridview;
String arr[] = new String[15]; @Override
protected void onCreate(Bundle
savedInstanceState) {
Practical 14.

Q.4 activity_main.xml Scrolling texts, also referred to as scrolltexts


or scrollers, played an important part in the birth of
<?xml version= "1.0" encoding= "utf-8" ?> the computer demo culture.
<RelativeLayout The software crackers often used their deep
xmlns:android="http://schemas.android.com/apk/res/ knowledge of computer platforms to transform the
android" information that accompanied their releases
xmlns:tools="http://schemas.android.com/tools" into crack intros. The sole role of these intros
android:layout_width="match_parent" was to scroll the text on the screen in an impressive
android:layout_height="match_parent" way.
tools:context=".MainActivity"> Many scrollers were plain horizontal scrollers,
but demo coders also paid a lot of attention to
<ScrollView creating new and different types of scrolling.
android:id="@+id/scrollView" The characters could, for example,
android:layout_width="fill_parent" continuously alter their shape, take unusual flying
android:layout_height="wrap_content" paths or incorporate color effects such as raster bars.
android:layout_marginTop="30dp"> Sometimes it makes the text nearly
unreadable.
<TextView " />
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" </ScrollView>
android:layout_gravity="center_horizontal"
android:text="Vertical ScrollView example In
computer displays, filmmaking, television </RelativeLayout>
production, and other kinetic \n
displays, scrolling is sliding text, images or Output :
video across a monitor or display, vertically or
horizontally. Scrolling \n,
as such, does not change the layout of the text
or pictures but moves (pans or tilts) the user's view
across what is \n
apparently a larger image that is not wholly
seen.[1] A common television and movie special
effect is to scroll credits, \n
while leaving the background stationary.
Scrolling may take place completely without user
intervention (as in film credits) \n
or, on an interactive device, be triggered by
touchscreen or a keypress and continue without
further intervention until a \n
further user action, or be entirely controlled
by input devices. Scrolling may take place in discrete
increments \n
(perhaps one or a few lines of text at a time),
or continuously (smooth scrolling). Frame rate is the
speed at which an \n
entire image is redisplayed. It is related to
scrolling in that changes to text and image position
can only happen as often \n
as the image can be redisplayed. When frame
rate is a limiting factor, one smooth scrolling
technique is to blur images during \n
movement that would otherwise appear to
jump \b
Practical 15

Q1 activity_main.xml Toast.makeText(
MainActivity.this,"Message For You:\nyou
<?xml version="1.0" encoding="utf-8"?> have got email!"
<RelativeLayout ,Toast.LENGTH_LONG).show();
xmlns:android="http://schemas.android.com/ }
apk/res/android" } );
}
xmlns:app="http://schemas.android.com/apk }
/res-auto" Output:

xmlns:tools="http://schemas.android.com/to
ols"
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:id="@+id/tv1"
android:text="Hello world Toast Example"
android:textColor="#000"
android:textStyle="bold"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast"
android:id="@+id/btn"
android:layout_below="@id/tv1"/>

</RelativeLayout>
Q.2 activity_main.xml
MainActivity.java
import android.os.Bundle; <?xml version="1.0" encoding="utf-8"?>
import android.app.Activity; <androidx.constraintlayout.widget.Constraint
import android.view.View; Layout
import android.view.View.OnClickListener; xmlns:android="http://schemas.android.com/
import android.widget.Button; apk/res/android"
import android.widget.Toast; xmlns:app="http://schemas.android.com/apk
/res-auto"
public class MainActivity extends Activity{ xmlns:tools="http://schemas.android.com/to
Button btn; ols" android:layout_width="match_parent"
@Override android:layout_height="match_parent"
protected void onCreate(Bundle tools:context=".MainActivity"> <TextView
savedInstanceState) { android:id="@+id/textView"
super.onCreate(savedInstanceState); android:layout_width="wrap_content"
setContentView(R.layout.activity_main); android:layout_height="wrap_content"
btn=findViewById( R.id.btn ); android:layout_marginStart="40dp"
btn.setOnClickListener( new android:layout_marginTop="76dp"
OnClickListener() { android:text="This is a 15th practical of MAD"
@Override android:textSize="24sp"
public void onClick(View view) { app:layout_constraintStart_toStartOf="parent
Practical 15

" protected void onCreate(Bundle


app:layout_constraintTop_toTopOf="parent" savedInstanceState) {
/> <Button android:id="@+id/btn" super.onCreate(savedInstanceState);
android:layout_width="wrap_content" setContentView(R.layout.activity_main);
android:layout_height="wrap_content" btn=findViewById( R.id.btn );
android:layout_marginStart="132dp" checkBox=findViewById(R.id.checkBox);
android:layout_marginTop="392dp"
android:text="Order " checkBox2=findViewById(R.id.checkBox2);
app:layout_constraintStart_toStartOf="parent
" checkBox3=findViewById(R.id.checkBox3);
app:layout_constraintTop_toTopOf="parent"
/> <CheckBox android:id="@+id/checkBox" btn.setOnClickListener( new
android:layout_width="89dp" OnClickListener() {
android:layout_height="54dp" @Override
android:layout_marginStart="104dp" public void onClick(View view) {
android:layout_marginTop="108dp" if(checkBox.isChecked())
android:text="Pizza" {
app:layout_constraintStart_toStartOf="@+id/ order="Pizza 100Rs\n";
textView" Forder=Forder+order;
app:layout_constraintTop_toBottomOf="@+i finalBill+=100;
d/textView" /> <CheckBox }
android:id="@+id/checkBox2" if(checkBox2.isChecked())
android:layout_width="98dp" {
android:layout_height="41dp" order="Coffee 50Rs\n";
android:layout_marginTop="8dp" Forder=Forder+order;
android:text="Coffee" finalBill+=50;
app:layout_constraintStart_toStartOf="@+id/ }
checkBox" if(checkBox3.isChecked())
app:layout_constraintTop_toBottomOf="@+i {
d/checkBox" /> <CheckBox order="Burger 120Rs\n";
android:id="@+id/checkBox3" Forder=Forder+order;
android:layout_width="83dp" finalBill+=120;
android:layout_height="46dp" }
android:layout_marginStart="12dp" Toast.makeText(
android:layout_marginTop="8dp" MainActivity.this,"Selected
android:text="Burger" Items:\n"+Forder+"Total :
app:layout_constraintStart_toStartOf="@+id/ "+finalBill,Toast.LENGTH_LONG ).show();
btn" Forder="";
app:layout_constraintTop_toBottomOf="@+i finalBill=0;
d/checkBox2" /> }
</androidx.constraintlayout.widget.Constrain } );
tLayout> }

MainActivity.java }
public class MainActivity extends Activity{
Button btn;
CheckBox checkBox,checkBox2,checkBox3;
String order="" ,Forder="";
private int finalBill=0;

@Override
Practical 16

MainActivity.java:

public class MainActivity extends xmlns:tools="http://schemas.android.com/to


AppCompatActivity { private TextView ols" android:layout_width="match_parent"
tvSelectDate; private EditText etSelectDate; android:layout_height="match_parent"
@Override protected void onCreate(Bundle tools:context=".MainActivity"> <TextView
savedInstanceState) { android:id="@+id/tvSelectDate"
super.onCreate(savedInstanceState); android:layout_width="wrap_content"
setContentView(R.layout.activity_main); android:layout_height="wrap_content"
tvSelectDate = android:text="Abdul select your DOB"
findViewById(R.id.tvSelectDate); etSelectDate android:textColor="@android:color/black"
= findViewById(R.id.etSelectDate); final android:textSize="16sp"
Calendar calendar = Calendar.getInstance(); app:layout_constraintBottom_toBottomOf="p
final int year = calendar.get(Calendar.YEAR); arent"
final int month = app:layout_constraintEnd_toEndOf="parent"
calendar.get(Calendar.MONTH); final int day = app:layout_constraintStart_toStartOf="parent
calendar.get(Calendar.DAY_OF_MONTH); "
tvSelectDate.setOnClickListener(new app:layout_constraintTop_toTopOf="parent"
View.OnClickListener() { @Override public /> <EditText android:id="@+id/etSelectDate"
void onClick(View v) { DatePickerDialog dialog android:layout_width="wrap_content"
= new DatePickerDialog(MainActivity.this, android:layout_height="wrap_content"
new DatePickerDialog.OnDateSetListener() { android:hint="Select Date"
@Override public void onDateSet(DatePicker android:layout_marginTop="16dp"
view, int year, int month, int dayOfMonth) { android:textColor="@android:color/black"
month = month+1; String date = app:layout_constraintStart_toStartOf="parent
dayOfMonth+"/"+month+"/"+year; "
tvSelectDate.setText(date); } },year, app:layout_constraintEnd_toEndOf="parent"
month,day); dialog.show(); } }); app:layout_constraintTop_toBottomOf="@+i
etSelectDate.setOnClickListener(new d/tvSelectDate"/>
View.OnClickListener() { @Override public </androidx.constraintlayout.widget.Constrain
void onClick(View v) { DatePickerDialog dialog tLayout>
= new DatePickerDialog(MainActivity.this,
Output :
new DatePickerDialog.OnDateSetListener() {
@Override public void onDateSet(DatePicker
view, int year, int month, int dayOfMonth) {
month = month+1; String date =
dayOfMonth+"/"+month+"/"+year;
etSelectDate.setText(date); } },year,
month,day); dialog.show(); } }); } }

activity_main.xml

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


<androidx.constraintlayout.widget.Constraint
Layout
xmlns:android="http://schemas.android.com/
apk/res/android"
xmlns:app="http://schemas.android.com/apk
/res-auto"
MAD Practical 17:

MainActivity.java:
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}}
output :
Practical 8 Q2.

activity_main.xml MainActivity.java

<androidx.constraintlayout.widget.ConstraintLa public class practt8 extends AppCompatActivity


yout {
xmlns:android="http://schemas.android.com/apk String[] language ={"Mobile Application
/res/android" Development","Programming in
Python","Entrepreneurship
xmlns:app="http://schemas.android.com/apk/res Development","ETI","Management"};
-auto" @Override
protected void onCreate(Bundle
xmlns:tools="http://schemas.android.com/tools" savedInstanceState) {
android:layout_width="match_parent" super.onCreate(savedInstanceState);
android:layout_height="match_parent" setContentView(R.layout.activity_practt8);
Toolbar toolbar =
app:layout_behavior="@string/appbar_scrolling findViewById(R.id.toolbar);
_view_behavior" setSupportActionBar(toolbar);
tools:context=".practt8" ArrayAdapter<String> adapter = new
android:padding="30dp" ArrayAdapter<String>
tools:showIn="@layout/activity_practt8">
<TextView (this,android.R.layout.select_dialog_item,langua
android:layout_width="wrap_content" ge);
android:layout_height="wrap_content" //Getting the instance of
android:text=" Practical 8 \nSixth Sem AutoCompleteTextView
Subjects" AutoCompleteTextView actv =
android:textSize="30dp" (AutoCompleteTextView)findViewById(R.id.au
app:layout_constraintBottom_toBottomOf="par toCompleteTextView);
ent" actv.setThreshold(1);//will start working
app:layout_constraintLeft_toLeftOf="parent" from first character
app:layout_constraintRight_toRightOf="parent" actv.setAdapter(adapter);
app:layout_constraintTop_toTopOf="parent" }}
app:layout_constraintVertical_bias="0.032" Output :
/>
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="244dp"
android:text=" Subject name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLa
yout>
Practical 19

activity_main.xml n"
android:layout_alignEnd="@+id/imageButton
<?xml version="1.0" encoding="utf-8"?>
" /> <EditText
<RelativeLayout
android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/
android:layout_height="wrap_content"
apk/res/android"
android:id="@+id/editText2"
xmlns:tools="http://schemas.android.com/to
android:layout_alignTop="@+id/editText"
ols" android:layout_width="match_parent"
android:layout_alignLeft="@+id/textView1"
android:layout_height="match_parent"
android:layout_alignStart="@+id/textView1"
android:padding="20dp"> <TextView
android:layout_alignRight="@+id/textView1"
android:layout_marginTop="100dp"
android:layout_alignEnd="@+id/textView1"
android:id="@+id/textView1"
android:hint="Name"
android:layout_width="wrap_content"
android:textColorHint="@android:color/holo_
android:layout_height="wrap_content"
blue_light" /> <EditText
android:text="Content provider"
android:layout_width="wrap_content"
android:layout_alignParentTop="true"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/editText3"
android:textSize="30dp" /> <TextView
android:layout_below="@+id/editText"
android:id="@+id/textView2"
android:layout_alignLeft="@+id/editText2"
android:layout_width="wrap_content"
android:layout_alignStart="@+id/editText2"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText2"
android:layout_below="@+id/textView1"
android:layout_alignEnd="@+id/editText2"
android:layout_centerHorizontal="true"
android:hint="Grade"
android:text="Practical 19 "
android:textColorHint="@android:color/holo_
android:textColor="#ff87ff09"
blue_bright" /> <Button
android:textSize="30dp" /> <ImageView
android:layout_width="wrap_content"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_height="100dp"
android:text="Retrive student"
android:id="@+id/imageButton"
android:id="@+id/button"
android:src="@drawable/ic_baseline_person
android:layout_below="@+id/button2"
_24"
android:layout_alignRight="@+id/editText3"
android:layout_below="@+id/textView2"
android:layout_alignEnd="@+id/editText3"
android:layout_centerHorizontal="true" />
android:layout_alignLeft="@+id/button2"
<Button android:id="@+id/button2"
android:layout_alignStart="@+id/button2"
android:layout_width="wrap_content"
android:onClick="onClickRetrieveStudents"/>
android:layout_height="wrap_content"
</RelativeLayout>
android:layout_below="@+id/editText3"
android:layout_alignStart="@+id/textView2" StudentsProvider.java
android:layout_alignLeft="@+id/textView2"
import java.util.HashMap; import
android:layout_alignEnd="@+id/textView2"
android.content.ContentProvider; import
android:layout_alignRight="@+id/textView2"
android.content.ContentUris; import
android:onClick="onClickAddName"
android.content.ContentValues; import
android:text="Add Name" /> <EditText
android.content.Context; import
android:layout_width="wrap_content"
android.content.UriMatcher; import
android:layout_height="wrap_content"
android.database.Cursor; import
android:id="@+id/editText"
android.database.SQLException; import
android:layout_below="@+id/imageButton"
android.database.sqlite.SQLiteDatabase;
android:layout_alignRight="@+id/imageButto
import
Practical 19

android.database.sqlite.SQLiteOpenHelper; DatabaseHelper(context); /** * Create a write


import able database which will trigger its * creation
android.database.sqlite.SQLiteQueryBuilder; if it doesn't already exist. */ db =
import android.net.Uri; import dbHelper.getWritableDatabase(); return (db
android.text.TextUtils; public class == null)? false:true; } @Override public Uri
StudentsProvider extends ContentProvider { insert(Uri uri, ContentValues values) { /** *
static final String PROVIDER_NAME = Add a new student record */ long rowID =
"com.example.MyApplication.StudentsProvid db.insert( STUDENTS_TABLE_NAME, "",
er"; static final String URL = "content://" + values); /** * If record is added successfully */
PROVIDER_NAME + "/students"; static final if (rowID > 0) { Uri _uri =
Uri CONTENT_URI = Uri.parse(URL); static final ContentUris.withAppendedId(CONTENT_URI,
String _ID = "_id"; static final String NAME = rowID);
"name"; static final String GRADE = "grade"; getContext().getContentResolver().notifyChan
private static HashMap<String, String> ge(_uri, null); return _uri; } throw new
STUDENTS_PROJECTION_MAP; static final int SQLException("Failed to add a record into " +
STUDENTS = 1; static final int STUDENT_ID = 2; uri); } @Override public Cursor query(Uri uri,
static final UriMatcher uriMatcher; static{ String[] projection, String selection,String[]
uriMatcher = new selectionArgs, String sortOrder) {
UriMatcher(UriMatcher.NO_MATCH); SQLiteQueryBuilder qb = new
uriMatcher.addURI(PROVIDER_NAME, SQLiteQueryBuilder();
"students", STUDENTS); qb.setTables(STUDENTS_TABLE_NAME);
uriMatcher.addURI(PROVIDER_NAME, switch (uriMatcher.match(uri)) { case
"students/#", STUDENT_ID); } /** * Database STUDENTS:
specific constant declarations */ private qb.setProjectionMap(STUDENTS_PROJECTION
SQLiteDatabase db; static final String _MAP); break; case STUDENT_ID:
DATABASE_NAME = "College"; static final qb.appendWhere( _ID + "=" +
String STUDENTS_TABLE_NAME = "students"; uri.getPathSegments().get(1)); break; default:
static final int DATABASE_VERSION = 1; static } if (sortOrder == null || sortOrder == ""){ /**
final String CREATE_DB_TABLE = " CREATE * By default sort on student names */
TABLE " + STUDENTS_TABLE_NAME + " (_id sortOrder = NAME; } Cursor c = qb.query(db,
INTEGER PRIMARY KEY AUTOINCREMENT, " + projection, selection,
" name TEXT NOT NULL, " + " grade TEXT NOT selectionArgs,null, null, sortOrder); /** *
NULL);"; /** * Helper class that actually register to watch a content URI for changes */
creates and manages * the provider's c.setNotificationUri(getContext().getContentR
underlying data repository. */ private static esolver(), uri); return c; } @Override public int
class DatabaseHelper extends delete(Uri uri, String selection, String[]
SQLiteOpenHelper { DatabaseHelper(Context selectionArgs) { int count = 0; switch
context){ super(context, DATABASE_NAME, (uriMatcher.match(uri)){ case STUDENTS:
null, DATABASE_VERSION); } @Override count = db.delete(STUDENTS_TABLE_NAME,
public void onCreate(SQLiteDatabase db) { selection, selectionArgs); break; case
db.execSQL(CREATE_DB_TABLE); } @Override STUDENT_ID: String id =
public void onUpgrade(SQLiteDatabase db, int uri.getPathSegments().get(1); count =
oldVersion, int newVersion) { db.delete( STUDENTS_TABLE_NAME, _ID + "
db.execSQL("DROP TABLE IF EXISTS " + = " + id + (!TextUtils.isEmpty(selection) ? "
STUDENTS_TABLE_NAME); onCreate(db); } } AND (" + selection + ')' : ""), selectionArgs);
@Override public boolean onCreate() { break; default: throw new
Context context = getContext(); IllegalArgumentException("Unknown URI " +
DatabaseHelper dbHelper = new uri); }
Practical 19

getContext().getContentResolver().notifyChan values.put(StudentsProvider.NAME,
ge(uri, null); return count; } @Override public ((EditText)findViewById(R.id.editText2)).getTe
int update(Uri uri, ContentValues values, xt().toString());
String selection, String[] selectionArgs) { int values.put(StudentsProvider.GRADE,
count = 0; switch (uriMatcher.match(uri)) { ((EditText)findViewById(R.id.editText3)).getTe
case STUDENTS: count = xt().toString()); Uri uri =
db.update(STUDENTS_TABLE_NAME, values, getContentResolver().insert(
selection, selectionArgs); break; case StudentsProvider.CONTENT_URI, values);
STUDENT_ID: count = Toast.makeText(getBaseContext(),
db.update(STUDENTS_TABLE_NAME, values, uri.toString(), Toast.LENGTH_LONG).show(); }
_ID + " = " + uri.getPathSegments().get(1) + public void onClickRetrieveStudents(View
(!TextUtils.isEmpty(selection) ? " AND (" view) { // Retrieve student records String URL
+selection + ')' : ""), selectionArgs); break; =
default: throw new "content://com.example.MyApplication.Stude
IllegalArgumentException("Unknown URI " + ntsProvider"; Uri students = Uri.parse(URL);
uri ); } Cursor c = managedQuery(students, null, null,
getContext().getContentResolver().notifyChan null, "name"); if (c.moveToFirst()) { do{
ge(uri, null); return count; } @Override public Toast.makeText(this,
String getType(Uri uri) { switch c.getString(c.getColumnIndex(StudentsProvid
(uriMatcher.match(uri)){ /** * Get all student er._ID)) + ", " + c.getString(c.getColumnIndex(
records */ case STUDENTS: return StudentsProvider.NAME)) + ", " +
"vnd.android.cursor.dir/vnd.example.students c.getString(c.getColumnIndex(
"; /** * Get a particular student */ case StudentsProvider.GRADE)),
STUDENT_ID: return Toast.LENGTH_SHORT).show(); } while
"vnd.android.cursor.item/vnd.example.studen (c.moveToNext()); } } }
ts"; default: throw new
Output :
IllegalArgumentException("Unsupported URI:
" + uri); } } }

MainActivity.java

import android.net.Uri; import


android.os.Bundle; import
android.app.Activity; import
android.content.ContentValues; import
android.content.CursorLoader; import
android.database.Cursor; import
android.view.Menu; import
android.view.View; import
android.widget.EditText; import
android.widget.Toast; public class
MainActivity extends Activity { @Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }
public void onClickAddName(View view) { //
Add a new student record ContentValues
values = new ContentValues();
Practical 20

activity_main.xml MainActivity.java

<?xml version="1.0" encoding="utf-8"?> public class MainActivity extends


<androidx.constraintlayout.widget.Constraint AppCompatActivity {
Layout private WifiManager wifiManager;
xmlns:android="http://schemas.android.com/ Button button1,button2;
apk/res/android" TextView textView;
xmlns:app="http://schemas.android.com/apk
/res-auto" @Override
xmlns:tools="http://schemas.android.com/to protected void onCreate(Bundle
ols" android:layout_width="match_parent" savedInstanceState) {
android:layout_height="match_parent" super.onCreate(savedInstanceState);
tools:context=".MainActivity" > <Button setContentView(R.layout.activity_main);
android:id="@+id/button1" button2=findViewById(R.id.button2);
android:layout_width="wrap_content" button1=findViewById(R.id.button1);
android:layout_height="wrap_content" textView=findViewById(R.id.textView);
android:layout_marginStart="121dp" wifiManager=(WifiManager)
android:layout_marginTop="137dp" getApplicationContext().getSystemService(Co
android:onClick="enableWifi" ntext.WIFI_SERVICE);
android:text="enable wifi"
app:layout_constraintStart_toStartOf="parent }
" public void enableWifi(View v){
app:layout_constraintTop_toTopOf="parent" wifiManager.setWifiEnabled(true);
/> <Button android:id="@+id/button2"
android:layout_width="wrap_content" }
android:layout_height="wrap_content" public void disablewifi(View v){
android:layout_marginStart="16dp" wifiManager.setWifiEnabled(false);
android:layout_marginTop="36dp"
android:onClick="disablewifi" }
android:text="Disable wifi"
app:layout_constraintStart_toStartOf="@+id/ }
button1" Output :
app:layout_constraintTop_toBottomOf="@+i
d/button1" /> <TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="41dp"
android:text="This is practical no 20"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent
"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.Constrain
tLayout>
Practical 21

activity_main.xml void onReceive(Context context, Intent intent)


{ // TODO Auto-generated method stub
<RelativeLayout
Toast.makeText(context.getApplicationContex
xmlns:android="http://schemas.android.com/
t(), "Intent Detected.",
apk/res/android"
Toast.LENGTH_LONG).show(); } }
xmlns:tools="http://schemas.android.com/to
ols" android:layout_width="match_parent" Output :
android:layout_height="match_parent"
android:padding="50dp"
tools:context=".MainActivity" > <Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="190dp"
android:text="BroadCast Intent" />
</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {


@Override protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 =
(Button)findViewById(R.id.button1);
b1.setOnClickListener(new
View.OnClickListener() { @Override public
void onClick(View v) { // TODO Auto-
generated method stub broadcastintent(); } });
} @Override public boolean
onCreateOptionsMenu(Menu menu) { //
Inflate the menu; this adds items to the action
bar if it is present.
getMenuInflater().inflate(R.menu.main,
menu); return true; } public void
broadcastintent(){ Intent intent = new
Intent();
intent.setAction("com.prctical.app.MyReceive
r"); sendBroadcast(intent); } }

MyReceiver.java

package com.prctical.app; import


android.content.BroadcastReceiver; import
android.content.Context; import
android.content.Intent; import
android.widget.Toast; public class MyReceiver
extends BroadcastReceiver{ @Override public
Practical 22

Q.1 activity_main.xml onSensorChanged(SensorEvent event) { if


(event.sensor.getType() ==
<?xml version="1.0" encoding="utf-8"?>
Sensor.TYPE_ACCELEROMETER) {
<RelativeLayout
getAccelerometer(event); } } private void
xmlns:android="http://schemas.android.com/
getAccelerometer(SensorEvent event) { float[]
apk/res/android"
values = event.values; float x = values[0]; float
xmlns:app="http://schemas.android.com/apk
y = values[1]; float z = values[2]; float
/res-auto"
accelationSquareRoot = (x * x + y * y + z * z) /
xmlns:tools="http://schemas.android.com/to
(SensorManager.GRAVITY_EARTH *
ols" android:layout_width="match_parent"
SensorManager.GRAVITY_EARTH); long
android:layout_height="match_parent"
actualTime = System.currentTimeMillis();
tools:context=".MainActivity"> <TextView
Toast.makeText(getApplicationContext(),Strin
android:layout_width="wrap_content"
g.valueOf(accelationSquareRoot)+" "+
android:id="@+id/textView"
SensorManager.GRAVITY_EARTH,Toast.LENGT
android:layout_height="wrap_content"
H_SHORT).show(); if (accelationSquareRoot
android:layout_centerInParent="true"
>= 2) { if (actualTime - lastUpdate < 200) {
android:text="Hello"
return; } lastUpdate = actualTime; if (isColor) {
android:textColor="#000"
view.setBackgroundColor(Color.GREEN); } else
android:textSize="40dp"
{ view.setBackgroundColor(Color.RED); }
android:textStyle="bold" /> </RelativeLayout>
isColor = !isColor; } } @Override protected
MainActivity.java void onResume() { super.onResume();
sensorManager.registerListener(this,sensorM
import android.app.Activity; import anager.getDefaultSensor(Sensor.TYPE_ACCEL
android.graphics.Color; import EROMETER),
android.hardware.Sensor; import SensorManager.SENSOR_DELAY_NORMAL); }
android.hardware.SensorEvent; import @Override protected void onPause() {
android.hardware.SensorEventListener; super.onPause();
import android.hardware.SensorManager; sensorManager.unregisterListener(this); } }
import android.os.Bundle; import
android.view.View; import output :
android.widget.Toast; public class
MainActivity extends Activity implements
SensorEventListener{ private SensorManager
sensorManager; private boolean isColor =
false; private View view; private long
lastUpdate; @Override public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); view
= findViewById(R.id.textView);
view.setBackgroundColor(Color.GREEN);
view.setBackgroundColor(Color.YELLOW);
sensorManager = (SensorManager)
getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis(); }
@Override public void
onAccuracyChanged(Sensor sensor, int
accuracy) {} @Override public void
Practical 22

Q.2 activity_main.xml Output :

<?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:paddingLeft="10dp"
android:paddingRight="10dp"> <TextView
android:id="@+id/sensorslist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="Sensors"
android:textSize="20dp"
android:textStyle="bold"
android:layout_gravity="center"
android:visibility="gone"/> </LinearLayout>

MainActivity.java

package com.tutlane.sensorsexample; import


android.content.Context; import
android.hardware.Sensor; import
android.hardware.SensorManager; import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import
android.view.View; import
android.widget.TextView; import java.util.List;
public class MainActivity extends
AppCompatActivity { private SensorManager
mgr; private TextView txtList; @Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mgr
=
(SensorManager)getSystemService(Context.SE
NSOR_SERVICE); txtList =
(TextView)findViewById(R.id.sensorslist);
List<Sensor> sensorList =
mgr.getSensorList(Sensor.TYPE_ALL);
StringBuilder strBuilder = new StringBuilder();
for(Sensor s: sensorList){
strBuilder.append(s.getName()+"\n"); }
txtList.setVisibility(View.VISIBLE);
txtList.setText(strBuilder); } }
Practical 23

Q.1 activity_main.xml } }); } protected void onActivityResult(int


requestCode, int resultCode, Intent data) {
<?xml version="1.0" encoding="utf-8"?> super.onActivityResult(requestCode,
<RelativeLayout resultCode, data); if (requestCode == pic_id) {
xmlns:android="http://schemas.android.com/ Bitmap photo = (Bitmap) data.getExtras()
apk/res/android" .get("data");
android:orientation="vertical" click_image_id.setImageBitmap(photo); } } }
android:layout_width="match_parent"
android:layout_height="match_parent" Output :
android:padding="40dp"> <ImageView
android:layout_width="match_parent"
android:layout_height="400dp"
android:id="@+id/img"/> <Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="@id/img"
android:layout_marginTop="60dp"
android:id="@+id/btn"
android:text="Capture"/> </RelativeLayout>

MainActivity.java
package com.practicalme.a201; import
android.content.Intent; import
android.graphics.Bitmap; import
android.os.Bundle; import
android.provider.MediaStore; import
android.view.View; 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 =
(Button)findViewById(R.id.btn);
click_image_id =
(ImageView)findViewById(R.id.img);
camera_open_id.setOnClickListener(new
View.OnClickListener() { @Override public
void onClick(View v) { Intent camera_intent =
new Intent(MediaStore
.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera_intent, pic_id);
Practical 24

activity_main.xml android:text="off" android:onClick="off"


app:layout_constraintStart_toStartOf="parent
<?xml version="1.0" encoding="utf-8"?>
"
<androidx.constraintlayout.widget.Constraint
app:layout_constraintTop_toTopOf="parent"
Layout
/> <ListView android:id="@+id/listview"
xmlns:android="http://schemas.android.com/
android:layout_width="0dp"
apk/res/android"
android:layout_height="0dp"
xmlns:app="http://schemas.android.com/apk
android:layout_marginStart="1dp"
/res-auto"
android:layout_marginEnd="1dp"
xmlns:tools="http://schemas.android.com/to
android:layout_marginBottom="1dp"
ols" android:layout_width="match_parent"
app:layout_constraintBottom_toBottomOf="p
android:layout_height="match_parent"
arent"
tools:context=".MainActivity"> <Button
app:layout_constraintEnd_toEndOf="parent"
android:id="@+id/b1"
app:layout_constraintStart_toStartOf="parent
android:layout_width="wrap_content"
"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+i
android:layout_marginStart="117dp"
d/b4" />
android:layout_marginTop="180dp"
</androidx.constraintlayout.widget.Constrain
android:text="Turn on" android:onClick="on"
tLayout>
app:layout_constraintStart_toStartOf="parent
" MainAvtivity.java
app:layout_constraintTop_toTopOf="parent"
package com.practicalme.a201; import
/> <Button android:id="@+id/b2"
androidx.appcompat.app.AppCompatActivity;
android:layout_width="wrap_content"
import androidx.core.app.ActivityCompat;
android:layout_height="wrap_content"
import android.Manifest; import
android:layout_marginStart="1dp"
android.bluetooth.BluetoothAdapter; import
android:layout_marginBottom="19dp"
android.bluetooth.BluetoothDevice; import
android:text="get visible"
android.content.Intent; import
android:onClick="visible"
android.content.pm.PackageManager; import
app:layout_constraintBottom_toTopOf="@+i
android.os.Bundle; import android.view.View;
d/b3"
import android.widget.ArrayAdapter; import
app:layout_constraintStart_toStartOf="@+id/
android.widget.Button; import
b3" /> <Button android:id="@+id/b3"
android.widget.ListView; import
android:layout_width="wrap_content"
android.widget.Toast; import
android:layout_height="wrap_content"
java.util.ArrayList; import java.util.Set; public
android:layout_marginStart="2dp"
class MainActivity extends AppCompatActivity
android:layout_marginBottom="22dp"
{ Button b1, b2, b3, b4; ListView listView;
android:text="List devices "
private BluetoothAdapter BA; private
android:onClick="list"
Set<BluetoothDevice> pairedDevices;
app:layout_constraintBottom_toTopOf="@+i
@Override protected void onCreate(Bundle
d/b4"
savedInstanceState) {
app:layout_constraintStart_toStartOf="@+id/
super.onCreate(savedInstanceState);
b4" /> <Button android:id="@+id/b4"
setContentView(R.layout.activity_main);
android:layout_width="wrap_content"
listView = findViewById(R.id.listview); b1 =
android:layout_height="wrap_content"
findViewById(R.id.b1); b2 =
android:layout_marginStart="114dp"
findViewById(R.id.b2); b3 =
android:layout_marginTop="402dp"
findViewById(R.id.b3); b4 =
android:layout_marginBottom="1dp"
findViewById(R.id.b4); BA =
Practical 24

BluetoothAdapter.getDefaultAdapter(); } Output :
public void on(View v) { if (!BA.isEnabled()) {
Intent turnOn = new
Intent(BluetoothAdapter.ACTION_REQUEST_E
NABLE); if
(ActivityCompat.checkSelfPermission(this,
Manifest.permission.BLUETOOTH_CONNECT)
!= PackageManager.PERMISSION_GRANTED) {
return; } 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 v) { if
(ActivityCompat.checkSelfPermission(this,
Manifest.permission.BLUETOOTH_CONNECT)
!= PackageManager.PERMISSION_GRANTED) {
return; } BA.disable();
Toast.makeText(getApplicationContext(),
"Turned off", Toast.LENGTH_LONG).show(); }
public void visible(View v) { Intent getVisible =
new
Intent(BluetoothAdapter.ACTION_REQUEST_
DISCOVERABLE); if
(ActivityCompat.checkSelfPermission(this,
Manifest.permission.BLUETOOTH_ADVERTISE)
!= PackageManager.PERMISSION_GRANTED) {
return; } startActivityForResult(getVisible, 0); }
public void list(View v) { if
(ActivityCompat.checkSelfPermission(this,
Manifest.permission.BLUETOOTH_CONNECT)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling return; }
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);
listView.setAdapter(adapter); } }
Practical 25

MainActivity.java android:fromDegrees="360"
android:toDegrees="0"
package android:pivotX="50%"
com.example.imageanticlockwisepr25 android:pivotY="50%"
; import android:duration="5000" />
androidx.appcompat.app.AppCompatAc
tivity; import android.os.Bundle; </set>
import android.view.View; import
android.view.animation.Animation; ROTATE clockwise XML file Code:
import <?xml version="1.0" encoding="utf-
android.view.animation.AnimationUt 8"?>
ils; import android.widget.Button; <set
import android.widget.ImageView; xmlns:android="http://schemas.andr
public class MainActivity extends oid.com/apk/res/android">
AppCompatActivity { ImageView
imageView; Button button, button2; android:interpolator="@android:ani
@Override protected void m/cycle_interpolator">
onCreate(Bundle <rotate
savedInstanceState) { android:fromDegrees="0"
super.onCreate(savedInstanceState) android:toDegrees="360"
; android:pivotX="50%"
setContentView(R.layout.activity_m android:pivotY="50%"
ain); android:duration="5000" />
button=findViewById(R.id.button);
button2=findViewById(R.id.button2)
; </set>
imageView=findViewById(R.id.imageV
iew); OUTPUT:
button2.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View view) {
Animation animRotateAclk =
AnimationUtils.loadAnimation(getAp
plicationContext(),R.anim.rotate_a
nticlockwise);
imageView.startAnimation(animRotat
eAclk); } });
button.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View view) {
Animation aniRotateClk =
AnimationUtils.loadAnimation(getAp
plicationContext(),R.anim.rotate_c
lockwise);
imageView.startAnimation(aniRotate
Clk); } }); } }

XML code:

Rotate clock wise XML file code:


<?xml version="1.0" encoding="utf-
8"?>
<set
xmlns:android="http://schemas.andr
oid.com/apk/res/android">

android:interpolator="@android:ani
m/cycle_interpolator">
<rotate
Practical 26

activity_main.xml savedInstanceState) {
super.onCreate(savedInstanceState);
<?xml version="1.0" encoding="utf-8"?> setContentView(R.layout.activity_main);
<RelativeLayout EnterData = (Button)findViewById(R.id.button);
xmlns:android="http://schemas.android.com/apk/re editTextName =
s/android" (EditText)findViewById(R.id.editText);
xmlns:tools="http://schemas.android.com/tools" editTextPhoneNumber =
android:id="@+id/activity_main" (EditText)findViewById(R.id.editText2);
android:layout_width="match_parent" EnterData.setOnClickListener(new
android:layout_height="match_parent" View.OnClickListener() { @Override public void
android:padding="40dp"> <TextView onClick(View view) { SQLiteDataBaseBuild();
android:layout_marginTop="100dp" SQLiteTableBuild(); CheckEditTextStatus();
android:text="SQLite Insert Into Database" InsertDataIntoSQLiteDatabase();
android:layout_width="wrap_content" EmptyEditTextAfterDataInsert(); } }); } public
android:layout_height="wrap_content" void SQLiteDataBaseBuild(){ sqLiteDatabaseObj
android:layout_alignParentTop="true" = openOrCreateDatabase("AndroidJSonDataBase",
android:layout_centerHorizontal="true" Context.MODE_PRIVATE, null); } public void
android:id="@+id/textView" SQLiteTableBuild(){
android:gravity="center" android:textSize="20dp" sqLiteDatabaseObj.execSQL("CREATE TABLE
android:textColor="#000000"/> <EditText IF NOT EXISTS AndroidJSonTable(id INTEGER
android:layout_width="fill_parent" PRIMARY KEY AUTOINCREMENT NOT
android:layout_height="wrap_content" NULL, name VARCHAR, phone_number
android:inputType="textPersonName" VARCHAR);"); } public void
android:hint="Enter Name" android:ems="10" CheckEditTextStatus(){ NameHolder =
android:layout_marginTop="27dp" editTextName.getText().toString() ; NumberHolder
android:id="@+id/editText" = editTextPhoneNumber.getText().toString();
android:layout_below="@+id/textView" if(TextUtils.isEmpty(NameHolder) ||
android:layout_centerHorizontal="true" TextUtils.isEmpty(NumberHolder)){
android:gravity="center"/> <EditText EditTextEmptyHold = false ; } else {
android:layout_width="fill_parent" EditTextEmptyHold = true ; } } public void
android:layout_height="wrap_content" InsertDataIntoSQLiteDatabase(){
android:inputType="phone" android:hint="Enter if(EditTextEmptyHold == true) {
Phone Number" android:gravity="center" SQLiteDataBaseQueryHolder = "INSERT INTO
android:ems="10" AndroidJSonTable (name,phone_number)
android:layout_below="@+id/editText" VALUES('"+NameHolder+"',
android:layout_centerHorizontal="true" '"+NumberHolder+"');";
android:layout_marginTop="37dp" sqLiteDatabaseObj.execSQL(SQLiteDataBaseQuer
android:id="@+id/editText2" /> <Button yHolder); Toast.makeText(MainActivity.this,"Data
android:text="Insert Into SQLite Database" Inserted Successfully",
android:layout_width="fill_parent" Toast.LENGTH_LONG).show(); } else {
android:layout_height="wrap_content" Toast.makeText(MainActivity.this,"Please Fill All
android:layout_below="@+id/editText2" The Required Fields.",
android:layout_centerHorizontal="true" Toast.LENGTH_LONG).show(); } } public void
android:layout_marginTop="46dp" EmptyEditTextAfterDataInsert(){
android:id="@+id/button" /> </RelativeLayout> editTextName.getText().clear();
editTextPhoneNumber.get
Text().clear(); } }
MainActivity.java Output :
public class MainActivity extends
AppCompatActivity { SQLiteDatabase
sqLiteDatabaseObj; EditText editTextName,
editTextPhoneNumber; String NameHolder,
NumberHolder, SQLiteDataBaseQueryHolder;
Button EnterData; Boolean EditTextEmptyHold;
@Override protected void onCreate(Bundle
Practical 29

activity_main.xml android.view.Menu; import android.view.View;


import android.view.View.OnClickListener; import
<RelativeLayout android.widget.Button; import
xmlns:androclass="http://schemas.android.com/a android.widget.EditText; import
pk/res/android" android.widget.Toast; public class MainActivity
xmlns:tools="http://schemas.android.com/tools" extends Activity { EditText mobileno,message;
android:layout_width="match_parent" Button sendsms; @Override protected void
android:layout_height="match_parent" onCreate(Bundle savedInstanceState) {
tools:context=".MainActivity" > <EditText super.onCreate(savedInstanceState);
android:id="@+id/editText1" setContentView(R.layout.activity_main);
android:layout_width="wrap_content" mobileno=(EditText)findViewById(R.id.editText1);
android:layout_height="wrap_content" message=(EditText)findViewById(R.id.editText2);
android:layout_alignParentRight="true" sendsms=(Button)findViewById(R.id.button1);
android:layout_alignParentTop="true" //Performing action on button click
android:layout_marginRight="20dp" sendsms.setOnClickListener(new OnClickListener()
android:ems="10" /> <EditText { @Override public void onClick(View arg0) { String
android:id="@+id/editText2" no=mobileno.getText().toString(); String
android:layout_width="wrap_content" msg=message.getText().toString(); //Getting intent
android:layout_height="wrap_content" and PendingIntent instance Intent intent=new
android:layout_alignLeft="@+id/editText1" Intent(getApplicationContext(),MainActivity.class);
android:layout_below="@+id/editText1" PendingIntent
android:layout_marginTop="26dp" pi=PendingIntent.getActivity(getApplicationContex
android:ems="10" t(), 0, intent,0); //Get the SmsManager instance
android:inputType="textMultiLine" /> <TextView and call the sendTextMessage method to send
android:id="@+id/textView1" message SmsManager
android:layout_width="wrap_content" sms=SmsManager.getDefault();
android:layout_height="wrap_content" sms.sendTextMessage(no, null, msg, pi,null);
android:layout_alignBaseline="@+id/editText1" Toast.makeText(getApplicationContext(),
android:layout_alignBottom="@+id/editText1" "Message Sent successfully!",
android:layout_toLeftOf="@+id/editText1" Toast.LENGTH_LONG).show(); } }); } @Override
android:text="Mobile No:" /> <TextView public boolean onCreateOptionsMenu(Menu
android:id="@+id/textView2" menu) { // Inflate the menu; this adds items to the
android:layout_width="wrap_content" action bar if it is present.
android:layout_height="wrap_content" getMenuInflater().inflate(R.menu.activity_main,
android:layout_alignBaseline="@+id/editText2" menu); return true; } }
android:layout_alignBottom="@+id/editText2"
android:layout_alignLeft="@+id/textView1" Output :
android:text="Message:" /> <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginLeft="34dp"
android:layout_marginTop="48dp"
android:text="Send SMS" /> </RelativeLayout>

MainActivity.java
package com.example.sendsms; import
android.os.Bundle; import android.app.Activity;
import android.app.PendingIntent; import
android.content.Intent; import
android.telephony.SmsManager; import
Practical 30

activity_main.xml android:layout_alignParentLeft="true"
android:text="Message:" /> <Button
<?xml version="1.0" encoding="utf-8"?> android:id="@+id/button1"
<RelativeLayout android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/ android:layout_height="wrap_content"
res/android" android:layout_alignLeft="@+id/editText3"
xmlns:tools="http://schemas.android.com/tools" android:layout_below="@+id/editText3"
android:id="@+id/activity_main" android:layout_marginLeft="76dp"
android:layout_width="match_parent" android:layout_marginTop="20dp"
android:layout_height="match_parent" android:text="Send" /> </RelativeLayout>
android:padding="40dp"> <EditText
android:id="@+id/editText1" MainActivity.java
android:layout_width="wrap_content"
public class MainActivity extends Activity { EditText
android:layout_height="wrap_content"
editTextTo,editTextSubject,editTextMessage;
android:layout_alignParentRight="true"
Button send; @Override protected void
android:layout_alignParentTop="true"
onCreate(Bundle savedInstanceState) {
android:layout_marginRight="22dp"
super.onCreate(savedInstanceState);
android:layout_marginTop="16dp"
setContentView(R.layout.activity_main);
android:ems="10" /> <EditText
editTextTo=(EditText)findViewById(R.id.editText1);
android:id="@+id/editText2"
editTextSubject=(EditText)findViewById(R.id.editT
android:layout_width="wrap_content"
ext2);
android:layout_height="wrap_content"
editTextMessage=(EditText)findViewById(R.id.edit
android:layout_alignLeft="@+id/editText1"
Text3); send=(Button)findViewById(R.id.button1);
android:layout_below="@+id/editText1"
send.setOnClickListener(new OnClickListener(){
android:layout_marginTop="18dp"
@Override public void onClick(View arg0) { String
android:ems="10" > <requestFocus /> </EditText>
to=editTextTo.getText().toString(); String
<EditText android:id="@+id/editText3"
subject=editTextSubject.getText().toString(); String
android:layout_width="wrap_content"
message=editTextMessage.getText().toString();
android:layout_height="wrap_content"
Intent email = new Intent(Intent.ACTION_SEND);
android:layout_alignLeft="@+id/editText2"
email.putExtra(Intent.EXTRA_EMAIL, new String[]{
android:layout_below="@+id/editText2"
to}); email.putExtra(Intent.EXTRA_SUBJECT,
android:layout_marginTop="28dp"
subject); email.putExtra(Intent.EXTRA_TEXT,
android:ems="10"
message); //need this to prompts email client only
android:inputType="textMultiLine" /> <TextView
email.setType("message/rfc822");
android:id="@+id/textView1"
startActivity(Intent.createChooser(email, "Choose
android:layout_width="wrap_content"
an Email client :")); } }); } @Override public boolean
android:layout_height="wrap_content"
onCreateOptionsMenu(Menu menu) { // Inflate
android:layout_alignBaseline="@+id/editText1"
the menu; this adds items to the action bar if it is
android:layout_alignBottom="@+id/editText1"
present.
android:layout_alignParentLeft="true"
getMenuInflater().inflate(R.menu.activity_main,
android:text="To:" /> <TextView
menu); return true; } }
android:id="@+id/textView2"
android:layout_width="wrap_content" Output :
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Subject:" /> <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"
Practical 31

MapsActivity.java Obtain the SupportMapFragment and get


notified when the map is ready to be used.
import android.os.Build; import
SupportMapFragment mapFragment =
android.support.v4.app.FragmentActivity;
(SupportMapFragment)
import android.os.Bundle; import
getSupportFragmentManager()
com.google.android.gms.common.api.Google
.findFragmentById(R.id.map);
ApiClient; import
mapFragment.getMapAsync(this); }
com.google.android.gms.maps.CameraUpdate
@Override public void
Factory; import
onMapReady(GoogleMap googleMap) {
com.google.android.gms.maps.GoogleMap;
mMap = googleMap; if
import
(android.os.Build.VERSION.SDK_INT >=
com.google.android.gms.maps.OnMapReadyC
Build.VERSION_CODES.M) { if
allback; import
(ContextCompat.checkSelfPermission(this,
com.google.android.gms.maps.SupportMapFr
Manifest.permission.ACCESS_FINE_LOCATION
agment; import
) == PackageManager.PERMISSION_GRANTED)
com.google.android.gms.maps.model.Bitmap
{ buildGoogleApiClient();
DescriptorFactory; import
mMap.setMyLocationEnabled(true); } } else {
com.google.android.gms.maps.model.LatLng;
buildGoogleApiClient();
import
mMap.setMyLocationEnabled(true); } }
com.google.android.gms.maps.model.Marker;
protected synchronized void
import
buildGoogleApiClient() { mGoogleApiClient =
com.google.android.gms.maps.model.Marker
new GoogleApiClient.Builder(this)
Options; import
.addConnectionCallbacks(this)
com.google.android.gms.location.LocationSer
.addOnConnectionFailedListener(this)
vices; import android.location.Location;
.addApi(LocationServices.API).build();
import android.Manifest; import
mGoogleApiClient.connect(); } @Override
android.content.pm.PackageManager; import
public void onConnected(Bundle bundle) {
android.support.v4.content.ContextCompat;
mLocationRequest = new LocationRequest();
import
mLocationRequest.setInterval(1000);
com.google.android.gms.common.Connection
mLocationRequest.setFastestInterval(1000);
Result; import
mLocationRequest.setPriority(LocationReques
com.google.android.gms.location.LocationList
t.PRIORITY_BALANCED_POWER_ACCURACY);
ener; import
if (ContextCompat.checkSelfPermission(this,
com.google.android.gms.location.LocationReq
Manifest.permission.ACCESS_FINE_LOCATION
uest; public class MapsActivity extends
) == PackageManager.PERMISSION_GRANTED)
FragmentActivity implements
{
OnMapReadyCallback,
LocationServices.FusedLocationApi.requestLo
LocationListener,GoogleApiClient.Connection
cationUpdates(mGoogleApiClient,
Callbacks,
mLocationRequest, this); } } @Override public
GoogleApiClient.OnConnectionFailedListener{
void onConnectionSuspended(int i) { }
private GoogleMap mMap; Location
@Override public void
mLastLocation; Marker mCurrLocationMarker;
onLocationChanged(Location location) {
GoogleApiClient mGoogleApiClient;
mLastLocation = location; if
LocationRequest mLocationRequest;
(mCurrLocationMarker != null) {
@Override protected void onCreate(Bundle
mCurrLocationMarker.remove(); } //Place
savedInstanceState) {
current location marker LatLng latLng = new
super.onCreate(savedInstanceState);
LatLng(location.getLatitude(),
setContentView(R.layout.activity_maps); //
location.getLongitude()); MarkerOptions
Practical 31

markerOptions = new MarkerOptions(); android:name="android.permission.INTERNET


markerOptions.position(latLng); " />
markerOptions.title("Current Position");
Output :
markerOptions.icon(BitmapDescriptorFactory.
defaultMarker(BitmapDescriptorFactory.HUE_
GREEN)); mCurrLocationMarker =
mMap.addMarker(markerOptions); //move
map camera
mMap.moveCamera(CameraUpdateFactory.n
ewLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory
.zoomTo(11)); //stop location updates if
(mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLo
cationUpdates(mGoogleApiClient, this); } }
@Override public void
onConnectionFailed(ConnectionResult
connectionResult) { } }

activity_maps.xml

<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/to
ols" android:id="@+id/map"
android:name="com.google.android.gms.map
s.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.mapexample.Ma
psActivity" />

Dependencies :

1. implementation 'com.google.android.gms:play
-services-maps:11.8.0'
2. compile 'com.google.android.gms:play-
services-location:11.8.0'

Permissions :

<uses-permission
android:name="android.permission.ACCESS_F
INE_LOCATION" /> <uses-permission
android:name="android.permission.ACCESS_C
OARSE_LOCATION" /> <uses-permission
Practical 32

DirectionsJSONParser

package com.wingsquare.routebetweentwolocations;

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 DirectionsJSONParser {


/** 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<>() ;


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("poin
ts");
List<LatLng> 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);
}
Practical 32
}
routes.add(path);
}
}

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

/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-
google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded) {

List<LatLng> poly = new ArrayList<LatLng>();


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 &amp; 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result &amp; 1) != 0 ? ~(result >> 1) : (result >>
1));
lat += dlat;

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

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


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

MapsActivity.java
package com.wingsquare.routebetweentwolocations;

import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import 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;

public class MapsActivity extends FragmentActivity implements


OnMapReadyCallback{

private GoogleMap mMap;


private LatLng mOrigin;
private LatLng mDestination;
private Polyline mPolyline;
ArrayList<LatLng> mMarkerPoints;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
Practical 32
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);

mMarkerPoints = new ArrayList<>();


}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// Already two locations
if(mMarkerPoints.size()>1){
mMarkerPoints.clear();
mMap.clear();
}

// Adding new item to the ArrayList


mMarkerPoints.add(point);

// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();

// Setting the position of the marker


options.position(point);

/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(mMarkerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(Bitm
apDescriptorFactory.HUE_GREEN));
}else if(mMarkerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(Bitm
apDescriptorFactory.HUE_RED));
}

// Add new marker to the Google Map Android API V2


mMap.addMarker(options);

// Checks, whether start and end locations are captured


if(mMarkerPoints.size() >= 2){
mOrigin = mMarkerPoints.get(0);
mDestination = mMarkerPoints.get(1);
drawRoute();
}

}
});
}

private void drawRoute(){


Practical 32
// Getting URL to the Google Directions API
String url = getDirectionsUrl(mOrigin, mDestination);

DownloadTask downloadTask = new DownloadTask();

// Start downloading json data from Google Directions API


downloadTask.execute(url);
}

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;
// Key
String key = "key=" + getString(R.string.google_maps_key);
// Building the parameters to the web service
String parameters = str_origin+"&amp;"+str_dest+"&amp;"+key;
// Output format
String output = "json";
// Building the url to the web service
String url =
"https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

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);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
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 on download", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}

/** A class to download data from Google Directions URL */


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

// Downloading data in non-ui thread


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

// For storing data from web service


String data = "";

try{
// Fetching the data from web service
data = downloadUrl(url[0]);
Log.d("DownloadTask","DownloadTask : " + data);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

ParserTask parserTask = new ParserTask();

// Invokes the thread for parsing the JSON data


parserTask.execute(result);
}
}
/** A class to parse the Google Directions in 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();

// Starts parsing data


routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes }
// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<List<HashMap<String, String>>>
result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;

// Traversing through all the routes


for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();

// Fetching i-th route


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

// Fetching all the points in i-th route


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);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(8);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
if(lineOptions != null) {
if(mPolyline != null){
mPolyline.remove();
}
mPolyline = mMap.addPolyline(lineOptions);
}else
Toast.makeText(getApplicationContext(),"No route is found",
Toast.LENGTH_LONG).show();
}
}

Output :

You might also like