0% found this document useful (0 votes)
8 views101 pages

Mobile App Development: Hello World Guide

The document outlines the steps for developing mobile applications using Android Studio, including creating a 'Hello World' app, demonstrating the activity lifecycle, and building a simple calculator app. It provides detailed instructions on setting up the development environment, coding in XML and Java, and running applications on an Android Virtual Device (AVD). The document also includes code snippets for various functionalities and UI components required for the applications.

Uploaded by

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

Mobile App Development: Hello World Guide

The document outlines the steps for developing mobile applications using Android Studio, including creating a 'Hello World' app, demonstrating the activity lifecycle, and building a simple calculator app. It provides detailed instructions on setting up the development environment, coding in XML and Java, and running applications on an Android Virtual Device (AVD). The document also includes code snippets for various functionalities and UI components required for the applications.

Uploaded by

makwanashruti415
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Course Title: Mobile Application Development

Semester –V (Course Code: 4351604)


ENROLLMENT NO :226480316025

1. Install Android Studio, set up the Android development environment, and create a simple "Hello World"
app.
o Install Android Studio from [Link]
gclid=EAIaIQobChMIlqyAhq6nggMVuKVmAh0LZwGkEAAYAS AAEgIZVfD_BwE&gclsrc=[Link] this link.
o Launch Android Studio if it is not already opened.
o In the main Welcome to Android Studio window, click "Start a new Android Studio project".
o In the New Project window, give your application an Application Name, such as "Hello World".
o Verify the Project location, or choose a different directory for storing your project.
o On the Target Android Devices screen, "Phone and Tablet" should be selected. And you should
ensure that API 15: Android 4.0.3 IceCreamSandwich is set as the Minimum SDK. (Fix this if
necessary.)
 At the writing of this book, choosing this API level makes your "Hello World" app
compatible with 97% of Android devices active on the Google Play Store.
 These are the settings used by the examples in this book.
o Click Next.
o If your project requires additional components for your chosen target SDK, Android Studio will
install them automatically. Click Next.
o Customize the Activity window. Every app needs at least one activity. An activity represents a
single screen with a user interface and Android Studio provides templates to help you get
started. For the Hello World project, choose the simplest template (as of this writing, the "Empty
Activity" project template is the simplest template) available.
o Make sure the Generate Layout file box is checked (if visible).
o Make sure the Backwards Compatibility (App Compat) box is checked.
o Leave the Layout Name as activity_main. It is customary to name layouts after the activity they
belong to. Accept the defaults and click Finish.
o Build your project with Gradle (this may take a few moments). Android Studio uses Gradle as its
build system. See the Your Build Developer page for more information.
o Opens the code editor with your project.
o Below Screen is your android studio project screen after completion above steps.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

o In Above screen left screen is your project structure screen and right-side screen is your coding
and designing screen
o In right screen there are two files are open one is “activity_main.xml” which is use for front end
designing for user representation and second is “[Link]” is use for background
functionality of widget which are used in xml file.
o Below Screen represent your activity_main.xml page designing.

o In Above view in activity_main.xml represent three view “Design”, “Split”, “Code” represents in
right top corner. Above screen represent “Design” screen represent Hello World! In centre of
screen.
o In below screen you can see code view of activity_main.xml page
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

o And if we use “split” its represent both screen design + code which Is represent in below screen

o As per above screen we can see activity_main.xml page coding screen and simultaneously user UI
screen with text “Hello World”.
o In android if we need any text we are using TextView widget for execution and in any widget
there are two properties are by default we have to use one is android:layout_width and second is
android:layout_height as you cant see in TextView coding in above screen.
o So now we just need to run this project on real device or using AVD (Android Virtual device) . Its
provide by android studio development tool itself.

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

o In above figure top right corner one symbol is there for opening Device Manager for creating
AVD. Follow the steps for creating it after completion it run AVD.

o As per above screen when we press on play button AVD is start.

o As per above screen we can see AVD on right side of development tool with the running
application display “Hello World!” on screen.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

2. Develop a simple app that demonstrates the activity lifecycle.


o Same as the First program follow the steps for execution of the new project after it opens the
[Link] file from the project source and right down the following code.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

o Above Coding represent lifecycle of android. You will not see any output on the emulator or
device. You need to open logcat.
o Now see on the logcat: onCreate, onStart and onResume methods are invoked.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

o Now click on Home Button. You will see onPause , onStop method is invoked.

o Now click on the Application clear button its display OnDestroy method is invoked
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

3. Develop a simple calculator app that takes user input and performs basic arithmetic operations like
addition, subtraction, multiplication, and division.
o Create a new project and write down the below code in activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#8BC34A"
android:backgroundTint="@android:color/darker_gray"
tools:context=".MainActivity">

<!-- Text View to display our basic heading of "calculator"-->


<TextView
android:layout_width="194dp"
android:layout_height="43dp"
android:layout_marginStart="114dp"
android:layout_marginLeft="114dp"
android:layout_marginTop="58dp"
android:layout_marginEnd="103dp"
android:layout_marginRight="103dp"
android:layout_marginBottom="502dp"
android:scrollbarSize="30dp"
android:text=" Calculator"
android:textAppearance="@style/[Link].Body1"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Edit Text View to input the values -->


<EditText
android:id="@+id/num1"
android:layout_width="364dp"
android:layout_height="28dp"
android:layout_marginStart="72dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="71dp"
android:layout_marginBottom="416dp"
android:background="@android:color/white"
android:ems="10"
android:onClick="clearTextNum1"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Edit Text View to input 2nd value-->


<EditText
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

android:id="@+id/num2"
android:layout_width="363dp"
android:layout_height="30dp"
android:layout_marginStart="72dp"
android:layout_marginTop="112dp"
android:layout_marginEnd="71dp"
android:layout_marginBottom="374dp"
android:background="@android:color/white"
android:ems="10"
android:onClick="clearTextNum2"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Text View to display result -->


<TextView
android:id="@+id/result"
android:layout_width="356dp"
android:layout_height="71dp"
android:layout_marginStart="41dp"
android:layout_marginTop="151dp"
android:layout_marginEnd="48dp"
android:layout_marginBottom="287dp"
android:background="@android:color/white"
android:text="result"
android:textColorLink="#673AB7"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform 'sum' operation -->


<Button
android:id="@+id/sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doSum"
android:text="+"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform subtraction operation. -->


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

<!-- A button to perform division. -->

<Button
android:id="@+id/sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="210dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="113dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doSub"
android:text="-"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.507" />

<Button
android:id="@+id/div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="307dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doDiv"
android:text="/"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform multiplication. -->


<Button
android:id="@+id/mul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="356dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doMul"
android:text="x"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

<!-- A button to perform a modulus function. -->

<!-- A button to perform a power function. -->

<Button
android:id="@+id/button"
android:layout_width="103dp"
android:layout_height="46dp"
android:layout_marginStart="113dp"
android:layout_marginTop="356dp"
android:layout_marginEnd="206dp"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doMod"
android:text="%(mod)"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.515" />

<Button
android:id="@+id/pow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="113dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="210dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doPow"
android:text="n1^n2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.507" />

</[Link]>
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

o Screen Output display like the below screen:


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

o Below is the code for [Link] file Comments are added inside the code to understand
the code in more detail

o public class MainActivity extends AppCompatActivity {


private EditText opr1;
private EditText opr2;
private Button btnadd;
private Button btnsub;
private Button btnmul;
private Button btndiv;
private Button btnclr;
private TextView txtresult;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
opr1 = (EditText) findViewById([Link].editOp1);
opr2 = (EditText) findViewById([Link].editOp2);
btnadd = (Button) findViewById([Link]);
btnsub = (Button) findViewById([Link]);
btnmul = (Button) findViewById([Link]);
btndiv = (Button) findViewById([Link]);
btnclr = (Button) findViewById([Link]);
txtresult= (TextView) findViewById([Link]);
// Addition
[Link](new [Link]() {
@Override
public void onClick(View v) {
if(([Link]().length()>0) && ([Link]().length()>0))
{
double oper1 = [Link]([Link]().toString());
double oper2 = [Link]([Link]().toString());
double result = oper1 + oper2;
[Link]([Link](result));
}
else{
Toast toast= [Link]([Link],"Enter The Required
Numbers",Toast.LENGTH_LONG);
[Link]();
}
}
});
//Subtraction
[Link](new [Link]() {
@Override
public void onClick(View v) {
if(([Link]().length()>0) && ([Link]().length()>0))
{
double oper1 = [Link]([Link]().toString());
double oper2 = [Link]([Link]().toString());
double result = oper1 - oper2;
[Link]([Link](result));
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
ENROLLMENT NO :226480316025

}
else{
Toast toast= [Link]([Link],"Enter The Required
Numbers",Toast.LENGTH_LONG);
[Link]();
}

}
});
// Multiplication
[Link](new [Link]() {
@Override
public void onClick(View v) {
if(([Link]().length()>0) && ([Link]().length()>0))
{
double oper1 = [Link]([Link]().toString());
double oper2 = [Link]([Link]().toString());
double result = oper1 * oper2;
[Link]([Link](result));
}
else{
Toast toast= [Link]([Link],"Enter The Required
Numbers",Toast.LENGTH_LONG);
[Link]();
}
}
});
// Division
[Link](new [Link]() {
@Override
public void onClick(View v) {
if(([Link]().length()>0) && ([Link]().length()>0))
{
double oper1 = [Link]([Link]().toString());
double oper2 = [Link]([Link]().toString());
double result = oper1 / oper2;
[Link]([Link](result));
}
else{
Toast toast= [Link]([Link],"Enter The Required
Numbers",Toast.LENGTH_LONG);
[Link]();
}
}
});
// Reset Feilds
[Link](new [Link]() {
@Override
public void onClick(View v) {
[Link]("");
[Link]("");
[Link]("0.00");
[Link]();
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

}
});

}
}
o Now run the app and you will see the basic calculator App. Enter any two numbers and do the
operation
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

4. Develop an Android application that uses LinearLayout to arrange UI components vertically or


horizontally.
o There are two types of linear layout orientation:
 Vertical
 Horizontal
o As the name specified these two orientation are used to arrange there child one after the other, in a
line, either vertically or horizontally
o Vertical LinearLayout code in activity_main.xml as per below :

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


<LinearLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Linear Layout (Without Weight)"
android:id="@+id/textView"
android:layout_gravity="center_horizontal" />

<!-- Button Used -->

<[Link]
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300" />

<[Link]
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:background="#e6cf00" />

<[Link]
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3"
android:background="#0472f9" />

<[Link]
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 4"
android:background="#e100d5" />
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

</LinearLayout>
o And the output of this screen as per below of above code:

o And for Horizontal Linear layout code as per below:

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


<LinearLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!-- Button Used -->

<[Link]
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300" />

<[Link]
android:layout_width="wrap_content"
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:layout_height="wrap_content"
android:text="Button 2"
android:background="#e6cf00" />

<[Link]
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
android:background="#0472f9" />

<[Link]
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 4"
android:background="#e100d5" />

</LinearLayout>

o And the output of the code as per below screen


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

5. Develop an Android application that uses RelativeLayout to arrange UI components relative to each other.

o The Relative Layout is very flexible layout used in android for custom layout designing. It gives us the
flexibility to position our component/view based on the relative or sibling component’s position. Just
because it allows us to position the component anywhere we want so it is considered as most
flexible layout.
o Relative layout code is as per below:

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


<RelativeLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- Button Used -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="SIGN IN"
android:id="@+id/textView3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<!--Text View for Displaying Username-->

<TextView
android:id="@+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginTop="110dp"
android:text="UserName:"
android:textColor="#000000"
android:textSize="20sp" />

<!--Text View for Displaying Password-->

<TextView
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/userName"
android:layout_margin="@dimen/activity_horizontal_margin"
android:text="Password:"
android:textColor="#000000"
android:textSize="20sp" />

<!--Edit Text for Filling Username-->

<EditText
android:id="@+id/edt_userName"
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginTop="100dp"
android:layout_toRightOf="@+id/userName"
android:hint="User Name" />

<!--Edit Text for Filling Password-->

<EditText
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_below="@+id/edt_userName"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/password"
android:hint="Password" />

<!--Button for Clicking after filling details-->

<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/password"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#03B424"
android:text="Login"
android:textColor="#ffffff"
android:textStyle="bold" />

</RelativeLayout>

o Screen layout represent as per below screen


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

6. Develop an Android application that uses ScrollView to display a long list of items.
o In android ScrollView can hold only one direct child. This means that, if you have complex layout
with more views(Buttons, TextViews or any other view) then you must enclose them inside another
standard layout like Table Layout, Relative Layout or Linear Layout.
o Scrollview code is as per below:

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


<RelativeLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- Button Used -->
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="20dp"
android:orientation="vertical">

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#f00"
android:text="Button 1"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#0f0"
android:text="Button 2"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#00f"
android:text="Button 3"
android:textColor="#fff"
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#ff0"
android:text="Button 4"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#f0f"
android:text="Button 5"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#f90"
android:text="Button 6"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#f00"
android:text="Button 7"
android:textColor="#ff9"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#444"
android:text="Button 8"
android:textColor="#fff"
android:textSize="20sp" />

<Button
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#ff002211"
android:text="Button 9"
android:textColor="#fff"
android:textSize="20sp" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#0f0"
android:text="Button 10"
android:textColor="#fff"
android:textSize="20sp" />

</LinearLayout>

</ScrollView>
</RelativeLayout>

o Output for above code screen is as per below:


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

7. Develop an Android application that uses ListView and Custom Adapter to display a list of images
with text.
o As the simple ListView, custom ListView also uses Adapter classes which added the content from
data source (such as string array, array, database etc). Adapter bridges data between an
AdapterViews and other Views.
o Write the below code in activity_main.xml file
o <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="[Link]">

<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp">
</ListView>
</RelativeLayout>

o Create an additional [Link] file in layout folder which contains view components displayed
in listview.

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


<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<ImageView
android:id="@+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />

<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
android:id="@+id/title"
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4d4d4d" />
<TextView
android:id="@+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</LinearLayout>

o Now in [Link] file write the below code:

o package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


ListView list;

String[] maintitle ={
"Title 1","Title 2",
"Title 3","Title 4",
"Title 5",
};

String[] subtitle ={
"Sub Title 1","Sub Title 2",
"Sub Title 3","Sub Title 4",
"Sub Title 5",
};

Integer[] imgid={
[Link].download_1,[Link].download_2,
[Link].download_3,[Link].download_4,
[Link].download_5,
};
@Override
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);
setContentView([Link].activity_main);

MyListAdapter adapter=new MyListAdapter(this, maintitle, subtitle,imgid);


list=(ListView)findViewById([Link]);
[Link](adapter);

[Link](new [Link]() {

@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// TODO Auto-generated method stub
if(position == 0) {
//code specific to first list item
[Link](getApplicationContext(),"Place Your First Option
Code",Toast.LENGTH_SHORT).show();
}

else if(position == 1) {
//code specific to 2nd list item
[Link](getApplicationContext(),"Place Your Second Option
Code",Toast.LENGTH_SHORT).show();
}

else if(position == 2) {

[Link](getApplicationContext(),"Place Your Third Option


Code",Toast.LENGTH_SHORT).show();
}
else if(position == 3) {

[Link](getApplicationContext(),"Place Your Forth Option


Code",Toast.LENGTH_SHORT).show();
}
else if(position == 4) {

[Link](getApplicationContext(),"Place Your Fifth Option


Code",Toast.LENGTH_SHORT).show();
}

}
});
}
}
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o Create another java class [Link] which extends ArrayAdapter class. This class customizes
our listview.

o package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MyListAdapter extends ArrayAdapter<String> {

private final Activity context;


private final String[] maintitle;
private final String[] subtitle;
private final Integer[] imgid;

public MyListAdapter(Activity context, String[] maintitle,String[] subtitle, Integer[] imgid) {


super(context, [Link], maintitle);
// TODO Auto-generated constructor stub

[Link]=context;
[Link]=maintitle;
[Link]=subtitle;
[Link]=imgid;

public View getView(int position,View view,ViewGroup parent) {


LayoutInflater inflater=[Link]();
View rowView=[Link]([Link], null,true);

TextView titleText = (TextView) [Link]([Link]);


ImageView imageView = (ImageView) [Link]([Link]);
TextView subtitleText = (TextView) [Link]([Link]);

[Link](maintitle[position]);
[Link](imgid[position]);
[Link](subtitle[position]);

return rowView;

};
}
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o Output of the code as per below screen.

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

8. Develop an Android application that uses the Navigation Drawer to display a side menu.
o Create the menu folder under the res folder. To implement the menu. Refer to the following video
to create the layout to implement the menu.
o Invoke the following code in the navigation_menu.xml

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


<menu xmlns:android="[Link]
xmlns:tools="[Link]
tools:ignore="HardcodedText">

<item
android:id="@+id/nav_account"
android:title="My Account" />

<item
android:id="@+id/nav_settings"
android:title="Settings" />

<item
android:id="@+id/nav_logout"
android:title="Logout" />

</menu>

o Invoke the following code in the activity_main.xml to set up the basic things required for the
Navigation Drawer.

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

<!-- the root view must be the DrawerLayout -->

<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:id="@+id/my_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="128dp"
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:gravity="center"
android:text="GeeksforGeeks"
android:textSize="18sp" />
</LinearLayout>

<!-- this the navigation view which draws and shows the navigation drawer -->
<!-- include the menu created in the menu folder -->
<[Link]
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation_menu" />

</[Link]>

o Invoke the following code in the app/res/values/[Link] file.

o <resources>
<string name="app_name">Navigation Drawer</string>
<!-- to toggle the open close button of the navigation drawer -->
<string name="nav_open">Open</string>
<string name="nav_close">Close</string>
</resources>

o Invoke the following code in the MainActivity file to show the menu icon on the action bar and
implement the open-close functionality of the navigation drawer.

o import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

public DrawerLayout drawerLayout;


public ActionBarDrawerToggle actionBarDrawerToggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// drawer layout instance to toggle the menu icon to open


// drawer and back button to close drawer
drawerLayout = findViewById([Link].my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, [Link].nav_open,
[Link].nav_close);
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
[Link](actionBarDrawerToggle);
[Link]();

// to make the Navigation drawer icon always appear on the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

// override the onOptionsItemSelected()


// function to implement
// the item click listener callback
// to open and close the navigation
// drawer when the icon is clicked
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {

if ([Link](item)) {
return true;
}
return [Link](item);
}
}

o Output for the code as per below screen:

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

9. Develop an Android application that uses the bottom navigation bar to switch between different tabs.
o For this example, create a basic app with a FrameLayout and a Bottom Navigation Bar.
The FrameLayout will contain Fragments which will change as the user click on the items in
the Bottom Navigation Bar. This is how the activity_main.xml looks like:

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<FrameLayout
android:id="@+id/flFragment"
android:layout_width="match_parent" android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<[Link]
android:id="@+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="75dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:menu="@menu/bottom_nav_menu"/>

</[Link]>

o The Navigation Bar needs to have some items which will create using Menu. To create a Menu, first,
create a Menu Directory by clicking on the app -> res(right-click) -> New -> Android Resource
Directory and select Menu in the Resource Type.

o Now add these items in the bottom_nav_menu.xml. This is how the bottom_nav_menu.xml file
looks like after adding the items:

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


<menu xmlns:android="[Link]
<item
android:id="@+id/person"
android:title="Person"
android:icon="@drawable/ic_person_foreground"/>
<item
android:id="@+id/home"
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:title="Home"
android:icon="@drawable/ic_home_foreground"/>
<item
android:id="@+id/settings"
android:title="Settings"
android:icon="@drawable/ic_settings_foreground"/>
</menu>

o To create a Fragment, click on the app(right-click) -> New -> Fragment -> Fragment (Blank). Name
the fragment as FirstFragment and the corresponding XML file as fragment_first. To keep things
simple, all three of the fragments will just contain a TextView. However, we can tweak this as we
want it to be in the app. This is how the fragment_first.xml looks like after adding a TextView

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/firstFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Geeks for Geeks"
android:textColor="#43a047"
android:textSize="40sp" android:textStyle="italic|
bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</[Link]>

o Next, code the FirstFragment to display the fragment_first.xml. For this, delete all the previously
written code in FirstFragment and replace it with the below code. The below code just takes the
layout we created for our fragment and inflates it.

o import [Link].*;
import [Link]

public class FirstFragment extends Fragment {

public FirstFragment(){
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

// require a empty public constructor


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
// Inflate the layout for this fragment
return [Link]([Link].fragment_first, container, false);
}
}

o Below are the fragment_second.xml, SecondFragment, fragment_third.xml,


and ThirdFragment files respectively

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/secondFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Data Structures"
android:textColor="#43a047"
android:textSize="40sp" android:textStyle="italic|
bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</[Link]>

o Now we have everything that we need and lastly, we just need to code the MainActivity to connect
everything to the application. Here, first, create a function called setCurrentFragment() that takes
a Fragment as an argument and sets it in our FrameLayout of activity_main.xml file.

o import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

import [Link];
import [Link].*;

public class MainActivity extends AppCompatActivity


implements BottomNavigationView
.OnNavigationItemSelectedListener {

BottomNavigationView bottomNavigationView;

@Override
protected void onCreate(Bundle savedInstanceState)
{
[Link](savedInstanceState);
setContentView([Link].activity_main);

bottomNavigationView
= findViewById([Link]);

bottomNavigationView
.setOnNavigationItemSelectedListener(this);
[Link]([Link]);
}
FirstFragment firstFragment = new FirstFragment();
SecondFragment secondFragment = new SecondFragment();
ThirdFragment thirdFragment = new ThirdFragment();

@Override
public boolean
onNavigationItemSelected(@NonNull MenuItem item)
{

switch ([Link]()) {
case [Link]:
getSupportFragmentManager()
.beginTransaction()
.replace([Link], firstFragment)
.commit();
return true;

case [Link]:
getSupportFragmentManager()
.beginTransaction()
.replace([Link], secondFragment)
.commit();
return true;

case [Link]:
getSupportFragmentManager()
.beginTransaction()
.replace([Link], thirdFragment)
.commit();
return true;
}
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

return false;
}
}
o Output of the code as per below screen:
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

10. Develop an Android application that uses an Intent to pass data between different activities.

o we have two activities, activity_first which are the source activity, and activity_second which is the
destination activity. We can send the data using the putExtra() method from one activity and get
the data from the second activity using the getStringExtra() method.
o Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for
the activity_main.xml file.
o <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".first_activity">

<EditText
android:id="@+id/send_text_id"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="20dp"
android:hint="Input"
android:textSize="25dp"
android:textStyle="bold" />

<Button
android:id="@+id/send_button_id"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="150dp"
android:text="send"
android:textStyle="bold" />
</RelativeLayout>
o Now below code is for first_activity.java file

o import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class first_activity extends AppCompatActivity {

// define the variable


Button send_button;
EditText send_text;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_first_activity);
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

send_button = findViewById([Link].send_button_id);
send_text = findViewById([Link].send_text_id);

// add the OnClickListener in sender button after clicked this button following Instruction will run
send_button.setOnClickListener(v -> {
// get the value which input by user in EditText and convert it to string
String str = send_text.getText().toString();
// Create the Intent object of this class Context() to Second_activity class
Intent intent = new Intent(getApplicationContext(), Second_activity.class);
// now by putExtra method put the value in key, value pair key is
// message_key by this key we will receive the value, and put the string
[Link]("message_key", str);
// start the Intent
startActivity(intent);
});
}
}

o The steps to create the second activity are as follows:


o android project > File > new > Activity > Empty Activity
o Add TextView to display the received messages. assign an ID to Textview. In second_activity.xml file.

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


<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link].Second_activity">

<TextView
android:id="@+id/received_value_id"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginLeft="40dp"
android:layout_marginTop="20dp"
android:textSize="40sp"
android:textStyle="bold"
android:layout_marginStart="40dp" />
</RelativeLayout>

o Now below code for [Link] file

o import [Link];
import [Link];
import [Link];
import [Link];
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

public class Second_activity extends AppCompatActivity {

TextView receiver_msg;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_second_activity);

receiver_msg = findViewById([Link].received_value_id);
// create the get Intent object
Intent intent = getIntent();
// receive the value by getStringExtra() method and
// key must be same which is send by first activity
String str = [Link]("message_key");
// display the string into textView
receiver_msg.setText(str);
}
}
o And the output for above code is as per below:

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

11. Develop an Android application that uses Services to perform background tasks.
o Add the following code to res/layout/activity_main.xml.

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


<[Link]
xmlns:android = "[Link]
xmlns:app = "[Link]
xmlns:tools = "[Link]
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text" android:layout_width
= "wrap_content" android:layout_height =
"wrap_content" android:text = "Start
Service" android:textSize = "25sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</[Link]>

o Add the following code to src/[Link]

package [Link]; import


[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
final TextView text = findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
if ([Link]().toString().equals("Started")) {
[Link]("Stoped");
stopService(new Intent([Link],[Link]));
} else {
[Link]("Started");
startService(new Intent([Link],[Link]));
}
}
});
}
}
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o In the above code to start and stop service. We have used intent and passed context and service
class. Now create a service class in package folder as [Link] and add the following code –

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class service extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
[Link](this, "Service started by user.", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
[Link]();
[Link](this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
}
}

o Add the following code to [Link]

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


<manifest xmlns:android = "[Link]
package = "[Link]">
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon =
"@mipmap/ic_launcher_round" android:supportsRtl
= "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "[Link]" />
<category android:name = "[Link]" />
</intent-filter>
</activity>
<service android:name = ".service"/>
</application>
</manifest>

o Let's try to run your application. And output is as below Screen:


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
o In the above result is an initial screen, Click on Text view, it will start service as shown below

o In the above result, service is started now click on text view, it will stop service as shown below -
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
12. Develop an Android application that uses Broadcast Receivers to receive and handle system-level
broadcasts.
o Go to the activity_main.xml file and refer to the following code. Below is the code for
the activity_main.xml file.

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


<[Link]
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</[Link]>

o Working with the MainActivity file

import [Link]; import

[Link];
import [Link]; import
[Link];
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

public class MainActivity extends AppCompatActivity {

AirplaneModeChangeReceiver airplaneModeChangeReceiver = new


AirplaneModeChangeReceiver();

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}

@Override
protected void onStart() {
[Link]();
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airplaneModeChangeReceiver, filter);
}

@Override
protected void onStop() {
[Link]();
unregisterReceiver(airplaneModeChangeReceiver);
}
}

o Create a new class


o Go to app > java > your package name(in which the MainActicity is present) > right-click > New >
Kotlin File/Class and name the files as AirplaneModeChangeReceiver. Below is the code for
the AirplaneModeChangeReceiver file. Comments are added inside the code to understand the
code in more detail.

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class AirplaneModeChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

if (isAirplaneModeOn([Link]())) {
[Link](context, "AirPlane mode is on", Toast.LENGTH_SHORT).show();
} else {
[Link](context, "AirPlane mode is off", Toast.LENGTH_SHORT).show();
}
}

private static boolean isAirplaneModeOn(Context context) {


return [Link]([Link](),
[Link].AIRPLANE_MODE_ON, 0) != 0;
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

}
}

o After run this project when we click on Airoplane mode in our application its diplay message
“Airoplane mode enabled” and when click again on Airoplane mode its display “Airoplane mode
desabled”.
13. Develop an Android application that uses Content Providers to share data between different apps and
components.
o Write the below code in activity_main.xml

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


<LinearLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnFetch"
android:layout_marginRight="@dimen/tendp"
android:layout_marginLeft="@dimen/tendp"
android:layout_marginTop="@dimen/fifteendp"
android:text="@string/fetch_contacts"/>

<ListView
android:id="@+id/listContacts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/twelvedp"
android:layout_marginBottom="@dimen/tendp"
android:divider="@color/cardview_dark_background"
android:dividerHeight="@dimen/onedp"
android:listSelector="@color/cardview_light_background"
android:smoothScrollbar="true">

</ListView>
</LinearLayout>

o Create new activity_list_item.xml file in layout and add below code in it.

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


<LinearLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:layout_width="@dimen/seventyfivedp"
android:layout_height="@dimen/seventyfivedp"
android:id="@+id/ivIcon"
android:src="@mipmap/ic_launcher"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/nameText"
android:textColor="@color/textcolor"
android:textStyle="bold"
android:layout_margin="@dimen/fivedp"
android:textSize="@dimen/twentysp"/>
<TextView
android:id="@+id/tvNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/numberText"
android:textColor="@color/textcolor"
android:textStyle="bold"
android:layout_margin="@dimen/fivedp"
android:textSize="@dimen/fifteensp" />
</LinearLayout>
</LinearLayout>

o Add the below code in the [Link] File

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


Button btnFetch;
ListView listContacts;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
btnFetch = (Button) findViewById([Link]);
listContacts = (ListView) findViewById([Link]);
[Link](v - > {
getPhoneContacts();
});
}

private void getPhoneContacts() {


if ([Link](this, [Link].READ_CONTACTS) !=
PackageManager.PERMISSION_GRANTED) {
[Link](this, new String[] {
[Link].READ_CONTACTS
}, 0);
}
ContentResolver contentResolver = getContentResolver();
Uri uri = [Link].CONTENT_URI;
Cursor cursor = [Link](uri, null, null, null, null);
Log.i("CONTACT_PROVIDER", "Total Contacts " + [Link]([Link]()));
String[] contactsName = new String[[Link]()];
String[] contactsNumber = new String[[Link]()];
if ([Link]() > 0) {
int i = 0, j = 0;
while ([Link]()) {
String contactName =
[Link]([Link]([Link].DISPLAY_NAM
E));
String contactNumber =
[Link]([Link]([Link]));
Log.i("CONTACT_PROVIDER", "Contacts Name " + contactName + " Ph: " + contactNumber);
contactsName[i++] = contactName;
contactsNumber[j++] = contactNumber;
}
myAdapter adapter = new myAdapter(this, contactsName, contactsNumber);
[Link](adapter);
}
}
class myAdapter extends ArrayAdapter < String > {
Context context;
String sName[];
String sNumber[];
myAdapter(Context c, String name[], String number[]) {
super(c, [Link].activity_list_item, [Link], name);
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

[Link] = c;
[Link] = name;
[Link] = number;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup
viewgroup) {
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listItem = [Link]([Link].activity_list_item, viewgroup, false);
TextView contactName = [Link]([Link]);
TextView contactNumber = [Link]([Link]);
[Link](sName[position]);
[Link](sNumber[position]);

return listItem;
}
}
}

o After run the application output as per below:


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

14. Develop an Android application that uses Content Providers to read system-level data, such as contacts
and calendar events.
o Write below code in [Link]

package [Link];

import [Link];
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

import [Link]; import


[Link]; import
[Link];
import [Link]; import
[Link];
import [Link]; import
[Link]; import
[Link];

@SuppressLint("NewApi")
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Button qry = (Button) findViewById([Link]);
[Link](new [Link]() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
query();
}
});
}

public void query() {


String[] projection = { [Link]._ID,
[Link] };
// Get a Cursor over the Events Provider.
Cursor cursor = getContentResolver().query(
[Link].CONTENT_URI, projection, null, null,
null);
// Get the index of the columns.
int nameIdx = cursor
.getColumnIndexOrThrow([Link]);
int idIdx = [Link]([Link]._ID);
// Initialize the result set.
String[] result = new String[[Link]()];
// Iterate over the result Cursor.
while ([Link]()) {
// Extract the name.
String name = [Link](nameIdx);
// Extract the unique ID.
String id = [Link](idIdx);
result[[Link]()] = name + "(" + id + ")";
[Link](this, name + "(" + id + ")", Toast.LENGTH_SHORT)
.show();
}
// Close the Cursor.
[Link]();
}
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link], menu);
return true;
}

o Write the below code in acitivity_main.xml file.

<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
android:id="@+id/querybut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="166dp"
android:text="Launch Query" />

</RelativeLayout>

o Add “<uses-permission android:name=”[Link].READ_CALENDAR” />” in


[Link] file.

o Run the code and the output is as below


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
o

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

15. Create an application that creates a database using SQLiteOpenHelper Class and performs Insert and Read
from the SQLite database.
o Navigate to the app > [Link] and add the below code to it.
o <uses-permission android:name="[Link].READ_EXTERNAL_STORAGE" />
o Now write the code into activity_main.xml file

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


<LinearLayout
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<!--Edit text to enter course name-->


<EditText
android:id="@+id/idEdtCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter course Name" />

<!--edit text to enter course duration-->


<EditText
android:id="@+id/idEdtCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Duration" />

<!--edit text to display course tracks-->


<EditText
android:id="@+id/idEdtCourseTracks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Tracks" />

<!--edit text for course description-->


<EditText
android:id="@+id/idEdtCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Description" />

<!--button for adding new course-->


<Button
android:id="@+id/idBtnAddCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Add Course"
android:textAllCaps="false" />

</LinearLayout>

o Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and
name it as DBHandler and add the below code to it. Comments are added inside the code to
understand the code in more detail.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

import [Link];
import [Link];
import [Link]; import
[Link];

public class DBHandler extends SQLiteOpenHelper {

// creating a constant variables for our database.


// below variable is for our database name.
private static final String DB_NAME = "coursedb";

// below int is our database version


private static final int DB_VERSION = 1;

// below variable is for our table name.


private static final String TABLE_NAME = "mycourses";

// below variable is for our id column.


private static final String ID_COL = "id";

// below variable is for our course name column


private static final String NAME_COL = "name";

// below variable id for our course duration column.


private static final String DURATION_COL = "duration";

// below variable for our course description column.


private static final String DESCRIPTION_COL = "description";

// below variable is for our course tracks column.


private static final String TRACKS_COL = "tracks";

// creating a constructor for our database handler.


public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}

// below method is for creating a database by running a sqlite query


@Override
public void onCreate(SQLiteDatabase db) {
// on below line we are creating
// an sqlite query and we are
// setting our column names
// along with their data types.
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COL + " TEXT,"
+ DURATION_COL + " TEXT,"
+ DESCRIPTION_COL + " TEXT,"
+ TRACKS_COL + " TEXT)";

// at last we are calling a exec sql


// method to execute above sql query
[Link](query);
}

// this method is use to add new course to our sqlite database.


public void addNewCourse(String courseName, String courseDuration,
String courseDescription, String courseTracks) {

// on below line we are creating a variable for


// our sqlite database and calling writable method
// as we are writing data in our database.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

SQLiteDatabase db = [Link]();

// on below line we are creating a


// variable for content values.
ContentValues values = new ContentValues();

// on below line we are passing all values


// along with its key and value pair.
[Link](NAME_COL, courseName);
[Link](DURATION_COL, courseDuration);
[Link](DESCRIPTION_COL, courseDescription);
[Link](TRACKS_COL, courseTracks);

// after adding all values we are passing


// content values to our table.
[Link](TABLE_NAME, null, values);

// at last we are closing our


// database after adding database.
[Link]();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// this method is called to check if the table exists already.
[Link]("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}

o Go to the [Link] file and refer to the following code. Below is the code for
the [Link] file. Comments are added inside the code to understand the code in more
detail.

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

public class MainActivity extends AppCompatActivity {

// creating variables for our edittext, button and dbhandler


private EditText courseNameEdt, courseTracksEdt, courseDurationEdt,
courseDescriptionEdt;
private Button addCourseBtn;
private DBHandler dbHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// initializing all our variables.


courseNameEdt = findViewById([Link]);
courseTracksEdt = findViewById([Link]);
courseDurationEdt = findViewById([Link]);
courseDescriptionEdt = findViewById([Link]);
addCourseBtn = findViewById([Link]);
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

// creating a new dbhandler class


// and passing our context to it.
dbHandler = new DBHandler([Link]);

// below line is to add on click listener for our add course


button.
[Link](new [Link]() {
@Override
public void onClick(View v) {

// below line is to get data from all edit text fields.


String courseName = [Link]().toString();
String courseTracks = [Link]().toString();
String courseDuration =
[Link]().toString();
String courseDescription =
[Link]().toString();

// validating if the text fields are empty or not.


if ([Link]() && [Link]() &&
[Link]() && [Link]()) {
[Link]([Link], "Please enter all the
data..", Toast.LENGTH_SHORT).show();
return;
}

// on below line we are calling a method to add new


// course to sqlite data and pass all our values to it.
[Link](courseName, courseDuration,
courseDescription, courseTracks);

// after adding the data we are displaying a toast message.


[Link]([Link], "Course has been added.",
Toast.LENGTH_SHORT).show();
[Link]("");
[Link]("");
[Link]("");
[Link]("");
}
});
}
}

o And the result of this code is as per below:


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o And you can see below this is how the data stored in the SQLite
database.

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

16. Create an application to Update and Delete data from the SQLite database using SQLiteOpenHelper class
o Create One Java File and give name as [Link] and write the code as per below:

import [Link];
import [Link]; import
[Link];

public class DatabaseHelper extends SQLiteOpenHelper {

// Table Name
public static final String TABLE_NAME = "COUNTRIES";

// Table columns
public static final String _ID = "_id";
public static final String SUBJECT = "subject";
public static final String DESC = "description";

// Database Information
static final String DB_NAME = "JOURNALDEV_COUNTRIES.DB";

// database version
static final int DB_VERSION = 1;

// Creating table query


private static final String CREATE_TABLE = "create table " + TABLE_NAME
+ "(" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + SUBJECT + " TEXT NOT
NULL, " + DESC + " TEXT);";

public DatabaseHelper(Context context) {


super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
[Link](CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
[Link]("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}

o Create another Java file [Link] file and code as per below:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link]; public

class DBManager {

private DatabaseHelper dbHelper;

private Context context;

private SQLiteDatabase database;


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

public DBManager(Context c) {
context = c;
}

public DBManager open() throws SQLException {


dbHelper = new DatabaseHelper(context);
database = [Link]();
return this;
}

public void close() {


[Link]();
}

public void insert(String name, String desc) {


ContentValues contentValue = new ContentValues();
[Link]([Link], name);
[Link]([Link], desc);
[Link](DatabaseHelper.TABLE_NAME, null, contentValue);
}

public Cursor fetch() {


String[] columns = new String[] { DatabaseHelper._ID,
[Link], [Link] };
Cursor cursor = [Link](DatabaseHelper.TABLE_NAME, columns,
null, null, null, null, null);
if (cursor != null) {
[Link]();
}
return cursor;
}

public int update(long _id, String name, String desc) {


ContentValues contentValues = new ContentValues();
[Link]([Link], name);
[Link]([Link], desc);
int i = [Link](DatabaseHelper.TABLE_NAME, contentValues,
DatabaseHelper._ID + " = " + _id, null);
return i;
}

public void delete(long _id) {


[Link](DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "="
+ _id, null);
}

o Create fragment_emp_list.xml file and add the below code in it:

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


<RelativeLayout xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
android:padding="10dp" >
</ListView>
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

<TextView
android:id="@+id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/empty_list_text" />

</RelativeLayout>

o Create [Link] file and add below code in it:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class CountryListActivity extends ActionBarActivity {

private DBManager dbManager;

private ListView listView;

private SimpleCursorAdapter adapter;

final String[] from = new String[] { DatabaseHelper._ID,


[Link], [Link] };

final int[] to = new int[] { [Link], [Link], [Link] };

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);

setContentView([Link].fragment_emp_list);

dbManager = new DBManager(this);


[Link]();
Cursor cursor = [Link]();

listView = (ListView) findViewById([Link].list_view);


[Link](findViewById([Link]));

adapter = new SimpleCursorAdapter(this,


[Link].activity_view_record, cursor, from, to, 0);
[Link]();

[Link](adapter);

// OnCLickListiner For List Items


[Link](new
[Link]() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long viewId) {
TextView idTextView = (TextView)
[Link]([Link]);
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

TextView titleTextView = (TextView)


[Link]([Link]);
TextView descTextView = (TextView)
[Link]([Link]);

String id = [Link]().toString();
String title = [Link]().toString();
String desc = [Link]().toString();

Intent modify_intent = new Intent(getApplicationContext(),


[Link]);
modify_intent.putExtra("title", title);
modify_intent.putExtra("desc", desc);
modify_intent.putExtra("id", id);

startActivity(modify_intent);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{ getMenuInflater().inflate([Link],
menu); return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = [Link]();
if (id == [Link].add_record) {

Intent add_mem = new Intent(this, [Link]);


startActivity(add_mem);

}
return [Link](item);
}

o Create [Link] file and as below code in it:

<menu xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
tools:context="[Link]" >

<item
android:id="@+id/add_record"
android:icon="@android:drawable/ic_menu_add"
android:orderInCategory="100"
android:title="@string/add_record"
app:showAsAction="always"/>

</menu>

o Create activity_add_record.xml file and as below code in it:

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


<LinearLayout
xmlns:android="[Link]
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" >

<EditText
android:id="@+id/subject_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_title" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/description_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_desc"
android:inputType="textMultiLine"
android:minLines="5" >
</EditText>

<Button
android:id="@+id/add_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/add_record" />

</LinearLayout>

o Create [Link] file and add below code in it:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class CountryListActivity extends ActionBarActivity {

private DBManager dbManager;

private ListView listView;

private SimpleCursorAdapter adapter;

final String[] from = new String[] { DatabaseHelper._ID,


[Link], [Link] };

final int[] to = new int[] { [Link], [Link], [Link] };

@Override
protected void onCreate(Bundle savedInstanceState) {
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

[Link](savedInstanceState);

setContentView([Link].fragment_emp_list);

dbManager = new DBManager(this);


[Link]();
Cursor cursor = [Link]();

listView = (ListView) findViewById([Link].list_view);


[Link](findViewById([Link]));

adapter = new SimpleCursorAdapter(this,


[Link].activity_view_record, cursor, from, to, 0);
[Link]();

[Link](adapter);

// OnCLickListiner For List Items


[Link](new
[Link]() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long viewId) {
TextView idTextView = (TextView)
[Link]([Link]);
TextView titleTextView = (TextView)
[Link]([Link]);
TextView descTextView = (TextView)
[Link]([Link]);

String id = [Link]().toString();
String title = [Link]().toString();
String desc = [Link]().toString();

Intent modify_intent = new


Intent(getApplicationContext(), [Link]);
modify_intent.putExtra("title", title);
modify_intent.putExtra("desc", desc);
modify_intent.putExtra("id", id);

startActivity(modify_intent);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{ getMenuInflater().inflate([Link],
menu); return true;
}

@import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class AddCountryActivity extends Activity implements


OnClickListener {

private Button addTodoBtn;


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

private EditText subjectEditText;


private EditText descEditText;

private DBManager dbManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);

setTitle("Add Record");

setContentView([Link].activity_add_record);

subjectEditText = (EditText)
findViewById([Link].subject_edittext);
descEditText = (EditText)
findViewById([Link].description_edittext);

addTodoBtn = (Button) findViewById([Link].add_record);

dbManager = new DBManager(this);


[Link]();
[Link](this);
}

@Override
public void onClick(View v) {
switch ([Link]()) {
case [Link].add_record:

final String name =


[Link]().toString();
final String desc =
[Link]().toString();

[Link](name, desc);

Intent main = new Intent([Link],


[Link])
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

startActivity(main);
break;
}
}

}
public boolean onOptionsItemSelected(MenuItem item) {

int id = [Link]();
if (id == [Link].add_record) {

Intent add_mem = new Intent(this,


[Link]);
startActivity(add_mem);

}
return [Link](item);
}

}
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o The CRUD operation performed here is adding a new record to the database. The xml layout and
code of [Link] file are defined below: activity_modify_record.xml

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


<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >

<EditText
android:id="@+id/subject_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:ems="10"
android:hint="@string/enter_title" />

<EditText
android:id="@+id/description_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_desc"
android:inputType="textMultiLine"
android:minLines="5" >
</EditText>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:gravity="center_horizontal"
android:orientation="horizontal" >

<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn_update" />

<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn_delete" />
</LinearLayout>

</LinearLayout>

o It’s similar to the previous layout except that modify and delete buttons are
added. [Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

import [Link];
import [Link];

public class ModifyCountryActivity extends Activity implements


OnClickListener {

private EditText titleText;


private Button updateBtn, deleteBtn;
private EditText descText;

private long _id;

private DBManager dbManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);

setTitle("Modify Record");

setContentView([Link].activity_modify_record);

dbManager = new DBManager(this);


[Link]();

titleText = (EditText) findViewById([Link].subject_edittext);


descText = (EditText)
findViewById([Link].description_edittext);

updateBtn = (Button) findViewById([Link].btn_update);


deleteBtn = (Button) findViewById([Link].btn_delete);

Intent intent = getIntent();


String id = [Link]("id");
String name = [Link]("title");
String desc = [Link]("desc");

_id = [Link](id);

[Link](name);
[Link](desc);

[Link](this);
[Link](this);
}

@Override
public void onClick(View v) {
switch ([Link]()) {
case [Link].btn_update:
String title = [Link]().toString();
String desc = [Link]().toString();

[Link](_id, title, desc);


[Link]();
break;

case [Link].btn_delete:
[Link](_id);
[Link]();
break;
}
}
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

public void returnHome() {


Intent home_intent = new Intent(getApplicationContext(),
[Link])
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}

o The CRUD operations performed here are updating and deleting a record. The below images are the
screenshots of the final output of our project. The first image is the output seen when the
application is launched for the first time.

o The second image is the result of clicking the menu option from the ActionBar to add a new record
as shown below.

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o The third image shows an output when 3 records are added :

o The fourth image shows the output when any list item is clicked to modify or
delete a record :

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

17. Perform Firebase Integration to your Android application and store the data in the Firebase Database.
o Connect your app to Firebase
o After creating a new project navigate to the Tools option on the top bar. Inside that click
on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the
screenshot.

o Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to
see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click
on Connect now and your app will be connected to Firebase. After that click on the second option
and now your App is connected to Firebase.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o After connecting your app to Firebase you will get to see the below screen.

o After that verify that dependency for Firebase Realtime database has been added to our Gradle file.
Now navigate to the app > Gradle Scripts and inside that file check whether the below dependency
is added or not. If the below dependency is not added in your [Link] file. Add the below
dependency in the dependencies section.
o implementation ‘[Link]:firebase-database:19.6.0’
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o After adding this dependency sync your project and now, we are ready to create our app.
o For adding data to Firebase we should have to give permissions for accessing the internet. For
adding these permissions navigate to the app > [Link] and inside that file add the
below permissions to it.
o <uses-permission android:name="[Link]"/>
o <uses-permission android:name="[Link].ACCESS_NETWORK_STATE"/>
o Go to the activity_main.xml file and refer to the following code. Below is the code for
the activity_main.xml file.

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


<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!--EditText for adding employee name-->


<EditText
android:id="@+id/idEdtEmployeeName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:hint="Enter Employee Name"
android:importantForAutofill="no"
android:inputType="textPersonName" />

<!--EditText for adding employee phone-->


<EditText
android:id="@+id/idEdtEmployeePhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeeName"
android:layout_margin="10dp"
android:hint="Enter employee phone number"
android:importantForAutofill="no"
android:inputType="phone" />

<!--EditText for adding employee address-->


<EditText
android:id="@+id/idEdtEmployeeAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeePhoneNumber"
android:layout_margin="10dp"
android:hint="Enter employee address"
android:inputType="textPostalAddress" />

<!--Button for adding data to Firebase-->


<Button
android:id="@+id/idBtnSendData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeeAddress"
android:layout_margin="10dp"
android:text="Add employee details"
android:textAllCaps="false" />

</RelativeLayout>
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o For sending multiple data to the Firebase Realtime database we have to create an Object class and
send that whole object class to Firebase. For creating an object class navigate to the app > java >
your app’s package name > Right-click on it and Click on New > Java Class > Give a name to your
class. In my case, it is EmployeeInfo, and add below code to it.

public class EmployeeInfo {

// string variable for


// storing employee name.
private String employeeName;

// string variable for storing


// employee contact number
private String employeeContactNumber;

// string variable for storing


// employee address.
private String employeeAddress;

// an empty constructor is
// required when using
// Firebase Realtime Database.
public EmployeeInfo() {

// created getter and setter methods


// for all our variables.
public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {


[Link] = employeeName;
}

public String getEmployeeContactNumber() {


return employeeContactNumber;
}

public void setEmployeeContactNumber(String employeeContactNumber) {


[Link] = employeeContactNumber;
}

public String getEmployeeAddress() {


return employeeAddress;
}

public void setEmployeeAddress(String employeeAddress) {


[Link] = employeeAddress;
}
}

o Go to the [Link] file and refer to the following code. Below is the code for
the [Link] file. Comments are added inside the code to understand the code in more
detail.

import [Link];
import [Link];
import [Link];
import [Link];
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

import [Link];
import [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

// creating variables for


// EditText and buttons.
private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt;
private Button sendDatabtn;

// creating a variable for our


// Firebase Database.
FirebaseDatabase firebaseDatabase;

// creating a variable for our Database


// Reference for Firebase.
DatabaseReference databaseReference;

// creating a variable for


// our object class
EmployeeInfo employeeInfo;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// initializing our edittext and button


employeeNameEdt = findViewById([Link]);
employeePhoneEdt = findViewById([Link]);
employeeAddressEdt = findViewById([Link]);

// below line is used to get the


// instance of our FIrebase database.
firebaseDatabase = [Link]();

// below line is used to get reference for our database.


databaseReference = [Link]("EmployeeInfo");

// initializing our object


// class variable.
employeeInfo = new EmployeeInfo();

sendDatabtn = findViewById([Link]);

// adding on click listener for our button.


[Link](new [Link]() {
@Override
public void onClick(View v) {

// getting text from our edittext fields.


String name = [Link]().toString();
String phone = [Link]().toString();
String address = [Link]().toString();
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

// below line is for checking whether the


// edittext fields are empty or not.
if ([Link](name) && [Link](phone) &&
[Link](address)) {
// if the text fields are empty
// then show the below message.
[Link]([Link], "Please add some
data.", Toast.LENGTH_SHORT).show();
} else {
// else call the method to add
// data to our database.
addDatatoFirebase(name, phone, address);
}
}
});
}

private void addDatatoFirebase(String name, String phone, String


address) {
// below 3 lines of code is used to set
// data in our object class.
[Link](name);
[Link](phone);
[Link](address);

// we are use add value event listener method


// which is called with database reference.
[Link](new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
// inside the method of on Data change we are setting
// our object class to our database reference.
// data base reference will sends data to firebase.
[Link](employeeInfo);

// after adding this data we are showing toast message.


[Link]([Link], "data added",
Toast.LENGTH_SHORT).show();
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
// if the data is not added or it is cancelled then
// we are displaying a failure toast message.
[Link]([Link], "Fail to add data " +
error, Toast.LENGTH_SHORT).show();
}
});
}
}

o After adding this code go to this link for Firebase. After clicking on this link you will get to see the
below page and on this page Click on Go to Console option in the top right corner.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
o After clicking on this screen you will get to see the below screen
with your
all project inside that select your project.

o Inside that screen click n Realtime Database in the left window.


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o After clicking on this option you will get to see the screen on the right side.
On this page click on the Rules option which is present in the top bar. You will
get to see the below screen.

o Inside this screen click on the Rules tab you will get to see the above screen and change the rules to
true as shown in the screenshot. The rules are changed to true because we are not providing
authentication inside our app and we have to write data to our database. That’s why we are
specifying it to true. After changing your rules click on the publish rules button. Click on that option
and your rules will be published. Now come back to the Data tab of your database.
o Run the app and make sure to connect your device to the internet. After that add some data in your
text fields and click on the Insert data button. The data will be added to our Firebase Database.
Below is the screenshot we will get to see after adding data to Firebase Database from the app.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

18. Create an application to retrieve data from the Firebase Database and display it in the RecyclerView.
o Create a Firebase Project
o Go to [Link]
o Log in to Firebase with your Google account if are not already logged in.
o Click on create the project.

o Give a name to the project


o Write the name.
o Click on continue.

o
o Disable Google Analytics(There is no need to do this for this project)
o Click on the toggle button.
o Click Continue.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
o Create a Realtime Database:
o Go to Develop Option on Sidebar.
o Click on Database.
o Scroll down in a new screen and click on Create Database on Realtime Database.
o Select Start in Test mode (In order to get read and write access to the database).
o Click enable.

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
o

o
o Add data to the database using the ‘+’ symbol in the database in the same manner as given in the
picture.
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
o Add the following dependency in your app/[Link] file in order to get the FirebaseUI and
Firebase Realtime Database support in the app.

dependencies {

// Dependency FirebaseUI for Firebase Realtime Database

implementation '[Link]:firebase-ui-database:6.2.1'

// Dependency for Firebase REaltime Database

implementation '[Link]:firebase-database:19.3.1'

o First, add Recycler View in the activity_main.xml and name it recycler1 paste the given code in the
activity_main.xml file in order to do so.

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<[Link]
android:id="@+id/recycler1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#65E4A6"/>

</[Link]>
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o Now, let’s create another XML file in the layout directory to store the data from the database of a
particular person. We will name the file as [Link]. Copy the following code in the created file.

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:scrollbars="vertical"
app:cardCornerRadius="20dp">

<[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="First name: "
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/firstname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/textView1"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Last name:"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView1" />

<TextView
android:id="@+id/lastname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:text="TextView"
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/textView2"
app:layout_constraintTop_toBottomOf="@+id/firstname" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:text="Age"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />

<TextView
android:id="@+id/age"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/textView3"
app:layout_constraintTop_toBottomOf="@+id/lastname" />

</[Link]>
</[Link]>

o After this, We have to create a java file to fetch and store data of a particular person from the
database and give it to Recycler View one by one. Create [Link] in the same folder in
which [Link] file is present. Paste the following code in the file.

// Your package name can be different depending


// on your project name
package [Link];

public class person


{
// Variable to store data corresponding
// to firstname keyword in database
private String firstname;

// Variable to store data corresponding


// to lastname keyword in database
private String lastname;

// Variable to store data corresponding


// to age keyword in database
private String age;

// Mandatory empty constructor


// for use of FirebaseUI
public person() {}

// Getter and setter method


public String getFirstname()
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

{
return firstname;
}
public void setFirstname(String firstname)
{
[Link] = firstname;
}
public String getLastname()
{
return lastname;
}
public void setLastname(String lastname)
{
[Link] = lastname;
}
public String getAge()
{
return age;
}
public void setAge(String age)
{
[Link] = age;
}
}

o In order to show the data from [Link] in [Link], we have to create an Adapter class.
Create another java file named [Link] in the same folder as [Link] and
paste the following code.

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

// FirebaseRecyclerAdapter is a class provided by


// FirebaseUI. it provides functions to bind, adapt and show
// database contents in a Recycler View
public class personAdapter extends FirebaseRecyclerAdapter<
person, [Link]> {

public personAdapter(
@NonNull FirebaseRecyclerOptions<person> options)
{
super(options);
}

// Function to bind the view in Card view(here


// "[Link]") iwth data in
// model class(here "[Link]")
@Override
protected void
onBindViewHolder(@NonNull personsViewholder holder,
int position, @NonNull person model)
{

// Add firstname from model class (here


// "[Link]")to appropriate view in Card
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

// view (here "[Link]")


[Link]([Link]());

// Add lastname from model class (here


// "[Link]")to appropriate view in Card
// view (here "[Link]")
[Link]([Link]());

// Add age from model class (here


// "[Link]")to appropriate view in Card
// view (here "[Link]")
[Link]([Link]());
}

// Function to tell the class about the Card view (here


// "[Link]")in
// which the data will be shown
@NonNull
@Override
public personsViewholder
onCreateViewHolder(@NonNull ViewGroup parent,
int viewType)
{
View view
= [Link]([Link]())
.inflate([Link], parent, false);
return new [Link](view);
}

// Sub Class to create references of the views in Crad


// view (here "[Link]")
class personsViewholder
extends [Link] {
TextView firstname, lastname, age;
public personsViewholder(@NonNull View itemView)
{
super(itemView);

firstname
= [Link]([Link]);
lastname = [Link]([Link]);
age = [Link]([Link]);
}
}
}

o Then we have called the database and ask for data from it. This will be done
in [Link] itself.

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;


personAdapter
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

adapter; // Create Object of the Adapter class


DatabaseReference mbase; // Create object of the
// Firebase Realtime Database

@Override
protected void onCreate(Bundle savedInstanceState)
{
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Create a instance of the database and get


// its reference
mbase
= [Link]().getReference();

recyclerView = findViewById([Link].recycler1);

// To display the Recycler view linearly


[Link](
new LinearLayoutManager(this));

// It is a class provide by the FirebaseUI to make a


// query in the database to fetch appropriate data
FirebaseRecyclerOptions<person> options
= new [Link]<person>()
.setQuery(mbase, [Link])
.build();
// Connecting object of required Adapter class to
// the Adapter class itself
adapter = new personAdapter(options);
// Connecting Adapter class with the Recycler view*/
[Link](adapter);
}

// Function to tell the app to start getting


// data from database on starting of the activity
@Override protected void onStart()
{
[Link]();
[Link]();
}

// Function to tell the app to stop getting


// data from database on stopping of the activity
@Override protected void onStop()
{
[Link]();
[Link]();
}
}

o Before running the project In [Link], one needs to include below permission, in
order to access the internet:
o “uses-permission android:name=”[Link]”
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

19. Connect an Android application to the MySQL database using PHP, and insert the data in the database table.
20. Perform insertion of data to MySQL database using PHP from an Android application.
o Use Xampp/Wamp server for create local database as per below:

o Now we will create a script to connect to our database. I have created [Link].

<?php
//Change the values according to your database

define('HOST','[Link]');
define('USER','u502452270_andro');
define('PASS','belal_123');
define('DB','u502452270_andro');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to


Connect');

o Our second script will receive and insert the data to mysql database. I have created [Link].

<?php
//checking if the script received a post request or not
if($_SERVER['REQUEST_METHOD']=='POST'){

//Getting post data


$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];

//checking if the received values are blank


if($name == '' || $username == '' || $password == '' || $email ==
''){
//giving a message to fill all values if the values are blank
echo 'please fill all values';
}else{
//If the values are not blank
//Connecting to our database by calling dbConnect script
require_once('[Link]');

//Creating an SQL Query to insert into database


//Here you may need to change the retrofit_users because it is the
table I created
//if you have a different table write your table's name

//This query is to check whether the username or email is already


registered or not
$sql = "SELECT * FROM retrofit_users WHERE username='$username' OR
email='$email'";
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

//If variable check has some value from mysqli fetch array
//That means username or email already exist
$check = mysqli_fetch_array(mysqli_query($con,$sql));

//Checking check has some values or not


if(isset($check)){
//If check has some value that means username already exist
echo 'username or email already exist';
}else{
//If username is not already exist
//Creating insert query
$sql = "INSERT INTO retrofit_users (name,username,password,email)
VALUES('$name','$username','$password','$email')";

//Trying to insert the values to db


if(mysqli_query($con,$sql)){
//If inserted successfully
echo 'successfully registered';
}else{
//In case any error occured
echo 'oops! Please try again!';
}
}
//Closing the database connection
mysqli_close($con);
}
}else{
echo 'error';
}

o Now Create an Android project and add the following dependency in [Link] file
o Implementation ‘[Link].9.0’
o Add internet permission in to your manifest.
o <uses-permission android:name=“[Link]”/>
o Now add the following code in activity_main.xml

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


<LinearLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:text="name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

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

<TextView
android:text="user name"
android:layout_width="wrap_content"
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

android:layout_height="wrap_content" />

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

<TextView
android:text="password"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/editTextPassword"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<TextView
android:text="email"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/editTextEmail"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/buttonRegister"
android:text="Register"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

o Now add below code in [Link] file

public class MainActivity extends AppCompatActivity implements


[Link] {

//Declaring views
private EditText editTextName;
private EditText editTextUsername;
private EditText editTextPassword;
private EditText editTextEmail;

private Button buttonRegister;

//This is our root url


public static final String ROOT_URL =
"[Link]

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

//Initializing Views
editTextName = (EditText) findViewById([Link]);
editTextUsername = (EditText) findViewById([Link]);
editTextPassword = (EditText) findViewById([Link]);
editTextEmail = (EditText) findViewById([Link]);

buttonRegister = (Button) findViewById([Link]);

//Adding listener to button


[Link](this);
}

private void insertUser(){


//Here we will handle the http request to insert user to mysql db
}

//Overriding onclick method


@Override
public void onClick(View v) {
//Calling insertUser on button click
insertUser();
}
}

o Create Interface name as RegisterAPI and add the following code in it:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

/**
* Created by Belal on 11/5/2015.
*/
public interface RegisterAPI {
@FormUrlEncoded
@POST("/RetrofitExample/[Link]")
public void insertUser(
@Field("name") String name,
@Field("username") String username,
@Field("password") String password,
@Field("email") String email,
Callback<Response> callback);
}

o Now enter below code insertUser() inside [Link] file

private void insertUser(){


//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new [Link]()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter

//Creating object for our interface


RegisterAPI api = [Link]([Link]);

//Defining the method insertuser of our interface


[Link](
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

//Passing the values by getting it from editTexts


[Link]().toString(),
[Link]().toString(),
[Link]().toString(),
[Link]().toString(),

//Creating an anonymous callback


new Callback<Response>() {
@Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;

//An string to store output from the server


String output = "";

try {
//Initializing buffered reader
reader = new BufferedReader(new
InputStreamReader([Link]().in()));

//Reading the output in the string


output = [Link]();
} catch (IOException e) {
[Link]();
}

//Displaying the output as a toast


[Link]([Link], output, Toast.LENGTH_LONG).show();
}

@Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
[Link]([Link],
[Link](),Toast.LENGTH_LONG).show();
}
}
);
}

o Now Run the code and output is as per below:


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
o And after getting message successfully registered as per above check your database as per below:

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

21. Perform reading of the data from the MySQL database using PHP in the JSON format and display on the
screen of an Android application.
o Create Database name “android” and add one table name with “heroes” and enter value same like
below:

o Now create [Link] and write the following code:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "android";

$conn = new mysqli($servername, $username, $password, $database); if

($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$heroes = array();

$sql = "SELECT id, name FROM heroes;";


$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $name);

while($stmt->fetch()){

$temp = [ 'id'=>$id,
'name'=>$name
];

array_push($heroes, $temp);
}

echo json_encode($heroes);

o Now we will create listview in activity_main.xml add below code


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

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


<RelativeLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link]">

<!-- this is our listview where we will display the fetched data -->
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />

</RelativeLayout>

o Add below code in [Link] file.

public class MainActivity extends AppCompatActivity

{ ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

listView = (ListView) findViewById([Link]);


getJSON("[Link]
}

private void getJSON(final String urlWebService) {

class GetJSON extends AsyncTask<Void, Void, String> {

@Override
protected void onPreExecute() {
[Link]();
}

@Override
protected void onPostExecute(String s) {
[Link](s);
[Link](getApplicationContext(), s,
Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
[Link]();
}
}

@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService); HttpURLConnection
con = (HttpURLConnection)
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

[Link]();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader([Link]()));
String json;
while ((json = [Link]()) != null) {
[Link](json + "\n");
}
return [Link]().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
[Link]();
}

private void loadIntoListView(String json) throws JSONException


{ JSONArray jsonArray = new JSONArray(json);
String[] heroes = new String[[Link]()];
for (int i = 0; i < [Link](); i++) {
JSONObject obj = [Link](i);
heroes[i] = [Link]("name");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
[Link].simple_list_item_1, heroes);
[Link](arrayAdapter);
}
}

o Now Run the application and below output comes:


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

o
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

22. Integrate Google maps API to your Android application and display your current location in the app
23. Integrate Google maps API to your Android application and find the distance of any nearby location from
your current location and display it.
o Add the following code in activity_main.xml file

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


<fragment xmlns:android="[Link]
xmlns:tools="[Link]
android:id="@+id/myMap"
android:name="[Link]"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />

o add the following dependency in the [Link](Module:app)

implementation '[Link]:play-services-maps:17.0.0'
implementation '[Link]:play-services-location:17.0.0'

o Add the following code to [Link] file

import [Link];
import [Link];
import [Link];
import [Link]; import
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link]; import
[Link];
import [Link];
public class MainActivity extends FragmentActivity implements
OnMapReadyCallback {
Location currentLocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
fusedLocationProviderClient =
[Link](this);
fetchLocation();
}
private void fetchLocation() {
if ([Link](
this, [Link].ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
[Link](
this, [Link].ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

[Link](this, new String[]


{[Link].ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
Task<Location> task =
[Link]();
[Link](new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
[Link](getApplicationContext(),
[Link]() + "" + [Link](),
Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment =
(SupportMapFragment)
getSupportFragmentManager().findFragmentById([Link]);
assert supportMapFragment != null;
[Link]([Link]);
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng([Link](),
[Link]());
MarkerOptions markerOptions = new
MarkerOptions().position(latLng).title("I am here!");
[Link]([Link](latLng));

[Link]([Link](latLng, 5));
[Link](markerOptions);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
if ([Link] > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
fetchLocation();
}
break;
}
}
}

o Open [Link] and add the following code:

<resources>
<string name="app_name">Sample</string>
<string name="map_key" translatable="false">Enter your google API key
here</string>
</resources>

o Add the following code [Link] file

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


<manifest xmlns:android="[Link]
package="[Link]">
<uses-permission android:name="[Link]"/>
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

<uses-permission
android:name="[Link].ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="[Link].ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data android:name="[Link].API_KEY"
android:value="@string/map_key"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]"
/>
</intent-filter>
</activity>
</application>
</manifest>

o Now run the code and output as per below:


Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)

You might also like