Sie sind auf Seite 1von 42

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

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
yout public class practt8 extends AppCompatActivity
xmlns:android="http://schemas.android.com/apk {
/res/android" String[] language ={"Mobile Application
Development","Programming in
xmlns:app="http://schemas.android.com/apk/res Python","Entrepreneurship
-auto" Development","ETI","Management"};
@Override
xmlns:tools="http://schemas.android.com/tools" protected void onCreate(Bundle
android:layout_width="match_parent" savedInstanceState) {
android:layout_height="match_parent" super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practt8);
app:layout_behavior="@string/appbar_scrolling Toolbar toolbar =
_view_behavior" findViewById(R.id.toolbar);
tools:context=".practt8" setSupportActionBar(toolbar);
android:padding="30dp" ArrayAdapter<String> adapter = new
tools:showIn="@layout/activity_practt8"> ArrayAdapter<String>
<TextView
(this,android.R.layout.select_dialog_item,langua
android:layout_width="wrap_content"
android:layout_height="wrap_content" ge);
//Getting the instance of
android:text=" Practical 8 \nSixth Sem
Subjects" AutoCompleteTextView
android:textSize="30dp" AutoCompleteTextView actv =
app:layout_constraintBottom_toBottomOf="par (AutoCompleteTextView)findViewById(R.id.au
ent" toCompleteTextView);
app:layout_constraintLeft_toLeftOf="parent" actv.setThreshold(1);//will start working
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 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"> "
<ProgressBar android:layout_height="wrap_conten
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

activity_main.xml ArrayAdapter<String> arr;


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

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
ols" imagev.setImageResource(R.drawable.smile
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

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


<?xml version= "1.0" encoding= "utf-8" ?> setContentView(R.layout.activity_main);
<GridView gridview = findViewById(R.id.gridview);
xmlns:android="http://schemas.android.com for (int i = 0; i < 15; i++) { arr[i] =
/apk/res/android" Integer.toString(i + 1); }
xmlns:tools="http://schemas.android.com/ ArrayAdapter<String> ad = new
tools" ArrayAdapter<String>(this,
android:id="@+id/gridview" R.layout.activity_listview, R.id.btn, arr);
android:layout_width="fill_parent" gridview.setAdapter(ad); } }
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

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


scrolltexts or scrollers, played an important part in
<?xml version= "1.0" encoding= "utf-8" ?> the birth of 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
<ScrollView to 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
android:layout_marginTop="30dp"> bars.
Sometimes it makes the text nearly
<TextView unreadable.
android:id="@+id/textView" " />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" </ScrollView>
android:text="Vertical ScrollView example In
computer displays, filmmaking, television
production, and other kinetic \n </RelativeLayout>
displays, scrolling is sliding text, images
or video across a monitor or display, vertically or Output :
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

Q1 activity_main.xml Toast.makeText( MainActivity.thi


s,"Message For You:\nyou have got
<?xml version="1.0" encoding="utf-8"?>
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

" 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( MainActivity.t
android:layout_marginTop="8dp" his,"Selected Items:\n"+Forder+"Total :
android:text="Burger" "+finalBill,Toast.LENGTH_LONG ).show();
app:layout_constraintStart_toStartOf="@+id/ Forder="";
btn" finalBill=0;
app:layout_constraintTop_toBottomOf="@+i }
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

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,
new DatePickerDialog.OnDateSetListener() { Output :
@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
yout public class practt8 extends AppCompatActivity
xmlns:android="http://schemas.android.com/apk {
/res/android" String[] language ={"Mobile Application
Development","Programming in
xmlns:app="http://schemas.android.com/apk/res Python","Entrepreneurship
-auto" Development","ETI","Management"};
@Override
xmlns:tools="http://schemas.android.com/tools" protected void onCreate(Bundle
android:layout_width="match_parent" savedInstanceState) {
android:layout_height="match_parent" super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practt8);
app:layout_behavior="@string/appbar_scrolling Toolbar toolbar =
_view_behavior" findViewById(R.id.toolbar);
tools:context=".practt8" setSupportActionBar(toolbar);
android:padding="30dp" ArrayAdapter<String> adapter = new
tools:showIn="@layout/activity_practt8"> ArrayAdapter<String>
<TextView
(this,android.R.layout.select_dialog_item,langua
android:layout_width="wrap_content"
android:layout_height="wrap_content" ge);
//Getting the instance of
android:text=" Practical 8 \nSixth Sem
Subjects" AutoCompleteTextView
android:textSize="30dp" AutoCompleteTextView actv =
app:layout_constraintBottom_toBottomOf="par (AutoCompleteTextView)findViewById(R.id.au
ent" toCompleteTextView);
app:layout_constraintLeft_toLeftOf="parent" actv.setThreshold(1);//will start working
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

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

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

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( StudentsProvider
selection, selectionArgs); break; case .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( StudentsProvider
"; /** * Get a particular student */ case .GRADE)), Toast.LENGTH_SHORT).show(); }
STUDENT_ID: return while (c.moveToNext()); } } }
"vnd.android.cursor.item/vnd.example.studen
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

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

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


<RelativeLayout { // TODO Auto-generated method stub
xmlns:android="http://schemas.android.com/ Toast.makeText(context.getApplicationContex
apk/res/android" t(), "Intent Detected.",
xmlns:tools="http://schemas.android.com/to Toast.LENGTH_LONG).show(); } }
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

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


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

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

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


<?xml version="1.0" encoding="utf-8"?> requestCode, int resultCode, Intent data) {
<RelativeLayout super.onActivityResult(requestCode,
xmlns:android="http://schemas.android.com/ resultCode, data); if (requestCode == pic_id) {
apk/res/android" Bitmap photo = (Bitmap) data.getExtras()
android:orientation="vertical" .get("data");
android:layout_width="match_parent" click_image_id.setImageBitmap(photo); } } }
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

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


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

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

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

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

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


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

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

MapsActivity.java Obtain the SupportMapFragment and get


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

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


markerOptions.position(latLng); " />
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory. Output :
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

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
}
Practical
}
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

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
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
// 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
@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

// 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 :

Das könnte Ihnen auch gefallen