Mobile App Development: Hello World Guide
Mobile App Development: Hello World Guide
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 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
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">
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" />
<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" />
<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 Below is the code for [Link] file Comments are added inside the code to understand
the code in more detail
@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)
<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" />
<[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:
<[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>
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:
<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" />
<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" />
<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" />
<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
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>
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:
<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>
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.
<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 package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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)
[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) {
}
});
}
}
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];
[Link]=context;
[Link]=maintitle;
[Link]=subtitle;
[Link]=imgid;
[Link](maintitle[position]);
[Link](imgid[position]);
[Link](subtitle[position]);
return rowView;
};
}
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
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
<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.
<[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 <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];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// 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);
}
if ([Link](item)) {
return true;
}
return [Link](item);
}
}
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:
<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:
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
<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 FirstFragment(){
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
// Inflate the layout for this fragment
return [Link]([Link].fragment_first, container, false);
}
}
<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].*;
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];
@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);
});
}
}
<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 import [Link];
import [Link];
import [Link];
import [Link];
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
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.
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
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.
[Link];
import [Link]; import
[Link];
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
@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);
}
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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();
}
}
}
}
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
<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.
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>
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];
[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;
}
}
}
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)
@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();
}
});
}
@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;
}
<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
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
</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];
SQLiteDatabase db = [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];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
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];
// 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;
@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 {
public DBManager(Context c) {
context = c;
}
<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>
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].fragment_emp_list);
[Link](adapter);
String id = [Link]().toString();
String title = [Link]().toString();
String desc = [Link]().toString();
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) {
}
return [Link](item);
}
<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>
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>
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
[Link](savedInstanceState);
setContentView([Link].fragment_emp_list);
[Link](adapter);
String id = [Link]().toString();
String title = [Link]().toString();
String desc = [Link]().toString();
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];
@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);
@Override
public void onClick(View v) {
switch ([Link]()) {
case [Link].add_record:
[Link](name, desc);
startActivity(main);
break;
}
}
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = [Link]();
if (id == [Link].add_record) {
}
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
<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];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setTitle("Modify Record");
setContentView([Link].activity_modify_record);
_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();
case [Link].btn_delete:
[Link](_id);
[Link]();
break;
}
}
Course Title: Mobile Application Development
Semester –V (Course Code: 4351604)
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 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.
</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.
// an empty constructor is
// required when using
// Firebase Realtime Database.
public EmployeeInfo() {
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];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
sendDatabtn = findViewById([Link]);
@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 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
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 {
implementation '[Link]:firebase-ui-database:6.2.1'
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.
<[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.
<[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.
{
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];
public personAdapter(
@NonNull FirebaseRecyclerOptions<person> options)
{
super(options);
}
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];
@Override
protected void onCreate(Bundle savedInstanceState)
{
[Link](savedInstanceState);
setContentView([Link].activity_main);
recyclerView = findViewById([Link].recycler1);
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');
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'){
//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));
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
<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>
//Declaring views
private EditText editTextName;
private EditText editTextUsername;
private EditText editTextPassword;
private EditText editTextEmail;
@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]);
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);
}
try {
//Initializing buffered reader
reader = new BufferedReader(new
InputStreamReader([Link]().in()));
@Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
[Link]([Link],
[Link](),Toast.LENGTH_LONG).show();
}
}
);
}
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:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "android";
($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$heroes = array();
while($stmt->fetch()){
$temp = [ 'id'=>$id,
'name'=>$name
];
array_push($heroes, $temp);
}
echo json_encode($heroes);
<!-- 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>
{ ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
@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]();
}
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
implementation '[Link]:play-services-maps:17.0.0'
implementation '[Link]:play-services-location:17.0.0'
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]([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;
}
}
}
<resources>
<string name="app_name">Sample</string>
<string name="map_key" translatable="false">Enter your google API key
here</string>
</resources>
<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>