Application Development Using Advanced Android
Application Development Using Advanced Android
Advanced Android
Mobile Application Development using Android
What is Android?
● Android is an open-source operating system based on Linux with a Java programming
interface for mobile devices such as Smartphone (Touch Screen Devices who supports
Android OS) as well for Tablets too.
● Android was developed by the Open Handset Alliance (OHA), which is led by Google.
The Open Handset Alliance (OHA) is a consortium of multiple companies like Samsung,
Sony, Intel and many more to provide services and deploy handsets using the android
platform.
● On September 23, 2008, Android was introduced by Andy Rubin, Larry Page, Sergey Brin,
Cole Brodman, Christopher Schlaeffer and Peter Chou at a press conference in a New
York subway station
Android History
● Initially, Google launched the first version of Android platform on Nov 5, 2007, from that
onwards Google released a lot of android versions under a codename based on desserts,
such as Apple Pie, Banana Bread, Cupcake, Donut, Éclair, Froyo, Gingerbread, Jellybeans,
Kitkat, Lollipop, marshmallow, etc. and made a lot of changes and additions to the
android platform.
● The following table lists the different version details of android which was released by
Google from 2007 to till date.
Android Features
Android is a powerful open-source operating system which provides a lot of great features,
those are
● It’s open-source and we can customize the OS based on our requirements.
Applications
● The top layer of the android architecture is Applications. The native and third-party
applications like contacts, email, music, gallery, clock, games, etc. whatever we will build
those will be installed on this layer only.
● The application layer runs within the Android run time using the classes and services
made available from the application framework.
Application Framework
● The Application Framework provides the classes used to create Android applications. It
also provides a generic abstraction for hardware access and manages the user interface
and application resources. It basically provides the services through which we can create
a particular class and make that class helpful for the Application creation.
Android SDK
● Android SDK stands for Android Software Development Kit which is developed by
Google for Android Platform. With the help of Android SDK, we can create Android Apps
easily.
● Android SDK is a collection of libraries and Software Development tools that are
essential for Developing Android Applications. Whenever Google releases a new version
or update of Android Software, a corresponding SDK also releases with it. In the updated
or new version of SDK, some more features are included which are not present in the
previous version.
● Android SDK consists of some tools which are very essential for the development of
Android Application. These tools provide a smooth flow of the development process
from developing and debugging.
● Android SDK is compatible with all operating systems such as Windows, Linux, macOS,
etc.
Android Emulator
● An Android Emulator is a device that simulates an Android device on your system.
Suppose we want to run our android application that we code. One option is that we will
run this on our Android Mobile by Enabling USB Debugging on our mobile. Another
option is using Android Emulator. In Android Emulator the virtual android device is
shown on our system on which we run the Android application that we code.
● Thus, it simply means that without needing any physical device Android SDK component
“Android Emulator” provides a virtual device on the System where we run our
Application. The emulator’s come with the configuration for Various android phones,
tablets, Wear OS, and Android TV devices.
AVD
● Android Virtual Device(AVD) is a software representation of an actual world physical
android device. In other words, it doesn’t have any physical existence but behaves like a
physical android device itself. It has everything which you think a physical machine
would have.
● Whether it’s storage, audio, notifications, applications, etc., all are present in the
android virtual device. Most of the android virtual devices are self-configurable. In other
words, you can configure the hardware and the version of android which you wish to
operate on.
● Android Virtual Device brings many features that make it so popular among developers,
gamers, and android users. Let’s see a few of the features of AVD before proceeding with
the setup.
○ It is self-configurable and allows users to pick up any android version of their
choice.
○ It provides storage and also allows applications to be installed.
○ This behaves mostly like your actual physical device and provides most of the
functionalities.
○ You can alter the appearance of your android virtual device depending on your
needs.
○ Android Virtual Device is as secure as your physical device.
Android IDE
Java
This contains the .java source files for your project. By default, it includes an
1
MainActivity.java source file having an activity class that runs when your app is
launched using the app icon.
res/drawable-hdpi
2
This is a directory for drawable objects that are designed for high-density screens.
res/layout
3
This is a directory for files that define your app's user interface.
res/values
4 This is a directory for other various XML files that contain a collection of resources,
such as strings and colors definitions.
AndroidManifest.xml
5 This is the manifest file which describes the fundamental characteristics of the app
and defines each of its components.
Build.gradle
6 This is an auto generated file which contains compileSdkVersion, buildToolsVersion,
applicationId, minSdkVersion, targetSdkVersion, versionCode and versionName
A Simple Example
<resources>
<string name=”app_name”>To Do List</string>
<color name=”app_background”>#000</color>
<dimen name=”default_border”>5px</dimen>
<string-array name=“string_array“>
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</string-array>
<array name=“integer_array“>
<item>3</item>
<item>2</item>
<item>1</item>
</array>
</resources>
EXAMPLE:
XML file saved at res/values-small/bools.xml:
<resources>
<bool name="screen_small">true</bool>
<bool name="adjust_view_bounds">true</bool>
</resources>
Color Resource
Syntax
<resources>
<color name="color_name">hex_color</color>
</resources>
EXAMPLE:
XML file saved at res/values/colors.xml:
<resources>
<color name="opaque_red">#f00</color>
</resources>
Dimension
<resources>
<style name=”mandatory_text_field_style”>
<item name=”android:textColor”>#000000</item>
<item name=”android:textSize”>16dp</item>
<item name=”android:textStyle”>bold</item>
</style>
<style name=”optional_text_field_style”>
<item name=”android:textColor”>#0F0F0F</item>
<item name=”android:textSize”>12dp</item>
<item name=”android:textStyle”>italic</item>
</style>
</resources>
Android terminologies
The following terminologies are used in Android:
● XML: In Android, XML is used for designing the application’s UI like creating
layouts,views, buttons, text fields etc. and also used in parsing data feeds from the
internet.
● Layout(ViewGroup): Layout is the parent of view. It arranges all the views in a proper
manner on the screen.
● Activity: An activity can be referred to as your device’s screen which you see. Users can
place UI elements in any order in the created window of the user's choice.
● Emulator: An emulator is an Android virtual device through which you can select the
target Android version or platform to run and test your developed application.
● Manifest file: Manifest file acts as a metadata for every application. This file contains all
the essential information about the application like app icon, app name, launcher
activity, and required permissions etc.
● Content Providers: Content Providers are used to share data between two
applications. This can be implemented in two ways:
● Intent: Intent is a messaging object which can be used to communicate between two or
more components like activities, services, broadcast receiver etc. Intent can also be used
to start an activity or service or to deliver a broadcast message.
● Gravity: Determine alignment of text within a view of android size. Value can include
top, bottom, left, right, center.
Activity
● An activity is the single screen in android. It is like a window or frame of Java.
● By the help of activity, you can place all your UI components or widgets in a single
screen.
● onStart(): This method is called when the activity becomes visible to the user. It is a
good place to start animations and other visual changes.
● onResume(): This method is called when the activity becomes the foreground activity. It
is the state in which the user can interact with the activity. This is where you should
register any listeners or start any services that need to be running while the activity is in
the foreground.
● onPause(): This method is called when the activity is no longer the foreground activity. It
is a good place to unregister listeners, save any data that needs to be saved, and stop
● onStop(): This method is called when the activity is no longer visible to the user. It is a
good place to stop animations and other visual changes.
● It’s important to note that an activity can also be in a “stopped” state if it is temporarily
Basic Views
What is View?
● Views are the building block of an Android Application’s UI Interface (UI). In very blunt
terms it’s a box that users can interact with either for giving input or performing some
action. There are many views, but today we will highlight only a few most commonly
used views.
○ TextView: For displaying text contents in the UI.
○ EditTextView: For adding input area in the UI.
○ ImageView: For displaying Image contents in the UI.
○ ButtonView: For adding (action) buttons in the UI.
○ ImageButtonView: For adding (action) buttons with an image in the UI.
○ RadioButtonView: For adding radio buttons in the UI.
○ Checkbox ButtonView: For adding CheckBox buttons in the UI.
What is ViewGroup?
● ViewGroup, as the name suggests, is a special type of view that can contain
other views (children) one or more. It is an invisible container for other
views and can also contain another ViewGroup inside it. Below are some
ViewGroups
○ LinearLayout
○ RelativeLayout
○ FrameLayout
○ TableLayout
○ ConstraintLayout
Widgets(Views) of Android
TextView
● In android, TextView is a user interface control that is used to set and display the text to
the user based on our requirements. The TextView control will act as like label control
and it won’t allow users to edit the text.
Attribute Description
android:autoLink It will automatically find and convert URLs and email addresses as
clickable links.
android: ems It is used to make the textview be exactly this many ems wide.
android:gravity It is used to specify how to align the text by the view's x and y-axis.
android:maxWidth It is used to make the TextView be at most this many pixels wide.
android:minWidth It is used to make the TextView be at least this many pixels wide.
android:typeface It is used to specify the Typeface (normal, sans, serif, monospace) for
the text.
android:inputType It is used to specify the type of text being placed in text fields.
android:editable If we set it, it specifies that this TextView has an input method.
● In android, we can set the text of TextView control either while declaring it in the Layout
file or by using setText() method in the Activity file.
● Following is the example to set the text of TextView control while declaring it in the XML
Layout file.
● Following is another way to set the textview control programmatically in an activity file
using setText() method.
● Example
Output:
Button
● Button is a user interface control which is used to perform an action whenever the user
clicks or taps on it.
● Generally, Buttons in android will contain a text or an icon or both and perform an action
when the user touches it.
● We have a different type of buttons available to use based on our requirements, those
are ImageButton, ToggleButton, RadioButton.
● Whenever the user clicks on a Button, the Button object will receive an on-click event.
● We can define click event handler for button by adding android:onClick attribute to the
<Button> element in our XML layout file.
● The value of android:onClick attribute must be the name of the method which we need
to call in response to a click event and the Activity file which hosts the XML layout must
implement the corresponding method.
● Attributes:
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center,
top, etc.
android:padding It is used to set the padding from left, right, top and bottom.
● Example:
activity_main.xml
MainActivity.java
Output:
AutoCompleteTextView
● In android, AutoCompleteTextView is an editable text view which is used to show the list
of suggestions based on the user typing text. The list of suggestions will be shown as a
dropdown menu from which the user can choose an item to replace the content of the
textbox.
● The AutoCompleteTextView is a subclass of the EditText class so we can inherit all the
properties of EditText in AutoCompleteTextView based on our requirements.
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center,
top, etc.
android:ems It is used to make the textview be exactly this many ems wide.
● Example:
activity_main.xml
Image Button
● In android, Image Button is a user interface control that is used to display a button with
an image and to perform an action when a user clicks or taps on it.
● By default, the ImageButton looks the same as a normal button and it performs an
action when a user clicks or touches it, but the only difference is we will add a custom
image to the button instead of text.
● In android, we have different types of buttons available to use based on our
requirements, those are Button, ImageButton, ToggleButton, and RadioButton.
● In android, we can add an image to the button by using <ImageButton> attribute
android:src in the XML layout file or by using the setImageResource() method.
● Attributes:
Attribute Description
android:padding It is used to set the padding from left, right, top and bottom of
the image button.
● Example:
Activity_main.xml
MainActivity.java
EditText
● In android, EditText is a user interface control which is used to allow the user to enter or
modify the text. While using EditText control in our android applications, we need to
specify the type of data the text field can accept using the inputType attribute.
● For example, if it accepts plain text, then we need to specify the inputType as “text”. In
case if EditText field is for password, then we need to specify the inputType as
“textPassword”.
● In android, EditText control is an extended version of TextView control with additional
features and it is used to allow users to enter input values.
● Attributes:
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center,
top, etc.
android:background It is used to set the background color for edit text control
android:ems It is used to make the textview be exactly this many ems wide.
android:inputType It is used to specify the type of text being placed in text fields.
● Example:
Activity_main.xml
MainActivity.java
ToggleButton
● In android, Toggle Button is a user interface control that is used to display ON (Checked)
or OFF (Unchecked) states as a button with a light indicator.
● The ToggleButton is useful for the users to change the settings between two states
either ON or OFF. We can add a ToggleButton to our application layout by using the
ToggleButton object.
● By default, the android ToggleButton will be in OFF (Unchecked) state. We can change
the default state of ToggleButton by using android:checked attribute.
● In case, if we want to change the state of ToggleButton to ON (Checked), then we need
to set android:checked = “true” in our XML layout file.
● Attributes:
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center,
top, etc.
android:textOn It is used to set the text when the toggle button is in the ON /
Checked state.
android:textOff It is used to set the text when the toggle button is in the OFF /
Unchecked state.
android:background It is used to set the background color for toggle button control.
android:padding It is used to set the padding from left, right, top and bottom.
● Example:
Activity_main.xml
MainActivity.java
CheckBox
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center,
top, etc.
android:padding It is used to set the padding from left, right, top and bottom.
android:onClick It’s the name of the method to invoke when the checkbox is
clicked.
● Example:
Activity_main.xml
MainActivity.java
RadioButton
● In android, Radio Button is a two-states button that can be either checked or unchecked
and it’s the same as CheckBox control, except that it will allow only one option to select
from the group of options.
● The user can press or click on the radio button to make it select. In android, CheckBox
control allows users to change the state of control either Checked or Unchecked but the
radio button cannot be unchecked once it is checked.
● In android, we use radio buttons within a RadioGroup to combine multiple radio
buttons into one group and it will make sure that users can select only one option from
the group of multiple options.
● By default, the android RadioButton will be in OFF (Unchecked) state. We can change
the default state of RadioButton by using the android:checked attribute.
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center,
top, etc.
android:padding It is used to set the padding from left, right, top and bottom.
android:onClick It’s the name of the method to invoke when the checkbox is
clicked.
RadioGroup
● In android, Radio Group is used to group one or more radio buttons into separate
groups based on our requirements.
● If we group Radio Buttons using RadioGroup, at a time only one item can be selected
from the group of radio buttons. In this case, if we select one radio button that belongs
to a radio group it will unselect all other previously selected radio buttons within the
same group.
● Initially, all the radio buttons of the radio group are in the unchecked state, once we
select a radio button then it’s not possible for us to uncheck it like CheckBox control.
● Example:
Activity_main.xml
MainActivity.java
ProgressBar
● In android, ProgressBar is a user interface control that is used to indicate the progress of
an operation. For example, downloading a file, uploading a file.
● By default the ProgressBar will be displayed as a spinning wheel, in case if we want to
show it like a horizontal bar then we need to change the style property to horizontal like
style="?android:attr/progressBarStyleHorizontal".
● Attributes:
Attribute Description
android:progress It is used to set the default progress value between 0 and max.
It must be an integer value.
● Example:
Activity_main.xml
MainActivity.java
Spinner
● In android, Spinner is a view that allows a user to select one value from the list of
values. The spinner in android will behave the same as a dropdown list in other
programming languages.
● Generally, the android spinners will provide a quick way to select one item from the list
of values and it will show a dropdown menu with a list of all values when we click or tap
on it.
● We can populate our Spinner control with a list of choices by defining an ArrayAdapter
in our Activity file.
Android Adapter
● In android, Adapter will act as an intermediate between the data sources and adapter
views such as ListView, Gridview to fill the data into adapter views. The adapter will hold
the data and iterate through items in the data set and generate the views for each item
in the list.
● Generally, in android we have a different types of adapters available to fetch the data
from different data sources to fill the data into adapter views, those are
Attribute Description
● Example:
Activity_main.xml
MainActivity.java
Layouts(ViewGroup) in Android
Attribute Description
android:layout_marginLeft It is used to define the extra space in the left side for View
and ViewGroup elements in a layout
android:layout_marginRight It is used to define the extra space in right side for View and
ViewGroup elements in layout
android:layout_marginTop It is used to define the extra space on top for View and
ViewGroup elements in layout
android:layout_marginBott It is used to define the extra space in the bottom side for
om View and ViewGroup elements in a layout
android:paddingLeft It is used to define the left side padding for View and
ViewGroup elements in layout files
android:paddingRight It is used to define the right side padding for View and
ViewGroup elements in layout files
android:paddingBottom It is used to define the bottom side padding for View and
ViewGroup elements in layout files
Linear Layout
● In android, LinearLayout is a ViewGroup subclass which is used to render all child View
instances one by one either in Horizontal direction or Vertical direction based on the
orientation property.
● In android, we can specify the linear layout orientation using android:orientation
attribute.
● In LinearLayout, the child View instances are arranged one by one, so the horizontal list
Relative Layout
Attribute Description
ayout_alignParentTop If it specified “true”, the top edge of view will match the top
edge of the parent.
layout_alignParentBottom If it specified “true”, the bottom edge of view will match the
bottom edge of parent.
layout_alignParentLeft If it specified “true”, the left edge of view will match the left
edge of parent.
layout_alignParentRight If it specified “true”, the right edge of view will match the right
edge of the parent.
layout_above It accepts another sibling view id and places the view above the
specified view id.
layout_below It accepts another sibling view id and places the view below the
specified view id.
layout_toLeftOf It accepts another sibling view id and places the view left of the
specified view id.
layout_toRightOf It accepts another sibling view id and places the view right of
the specified view id.
layout_toStartOf It accepts another sibling view id and places the view to start
off the specified view id.
layout_toEndOf It accepts another sibling view id and places the view to the
end of the specified view id.
● Example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Button" />
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/b1"
android:layout_centerInParent="true"
android:text="Button" />
<Button
android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/b1"
android:layout_centerInParent="true"
android:text="Button" />
<Button
android:id="@+id/b4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/b1"
android:layout_centerInParent="true"
android:text="Button" />
<Button
android:id="@+id/b5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/b1"
android:layout_centerInParent="true"
android:text="Button" />
</RelativeLayout>
Frame Layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imgvw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/flimg" />
<TextView
android:id="@+id/txtvw1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="#4C374A"
android:padding="10dp"
android:text="Grand Palace, Bangkok"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TextView
android:id="@+id/txtvw2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:text="21/Aug/2017"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</FrameLayout>
Table Layout
● In android, TableLayout is a ViewGroup subclass that is used to display the child View
elements in rows and columns.
● In android, TableLayout will position its children elements into rows and columns and it
won’t display any border lines for rows, columns or cells.
● The TableLayout in android will work the same as the HTML table and the table will have
as many columns as the row with the most cells. The TableLayout can be explained as
<table> and TableRow is like <tr> element.
● Create a new android application using android studio and give names as TableLayout. In
case you are not aware of creating an app in android studio check this article Android
Hello World App.
● Example:
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="UserId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Suresh Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hyderabad" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rohini Alavala" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Trishika Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
</TableLayout>
Database Connectivity
● In android, by using SQLiteOpenHelper class we can easily create required databases and
tables for our application. To use SQLiteOpenHelper, we need to create a subclass that
overrides the onCreate() and onUpgrade() call-back methods.
Method Description
onCreate() This method is called only once throughout the application after the
database is created and the table creation statements can be written in
this method.
onUpgrade() This method is called whenever there is an update in the database like
modifying the table structure, adding constraints to the database, etc.
execSQL( )
● To execute SQL statements in Android SQLite databases, you typically use methods
provided by the SQLiteDatabase class. One of these methods is execSQL, which is used
to execute a single SQL statement that is NOT a SELECT or any other SQL statement that
returns data.
● execSQL is used to execute the SQL statements for creating a table (CREATE TABLE) and
inserting data into that table (INSERT INTO). It's important to handle database
operations like opening, executing SQL, and closing the database properly to prevent
resource leaks and ensure data integrity.
● For managing all the operations related to the database , a helper class has been given
and is called SQLiteOpenHelper. It automatically manages the creation and update of
the database. Its syntax is given below
Table Creation
Data Fetching
● We can retrieve anything from the database using an object of the Cursor class. We will
call a method of this class called rawQuery and it will return a resultset with the cursor
● rawQuery(query, selectionArgs)
○ In Android development, the rawQuery() method is used to execute a raw SQL
query on an SQLite database. This method allows you to run any SQL query
directly and retrieve the result set.
○ The rawQuery() method returns a Cursor object, which allows you to iterate over
the result set and access the retrieved data.
○ Here's a breakdown of the parameters used in the rawQuery() method:
■ query: The raw SQL query to execute.
■ selectionArgs: An optional array of strings that represent the values to
replace the placeholders (?) in the SQL query. This parameter is useful for
avoiding SQL injection vulnerabilities.
○ Using the rawQuery() method gives you flexibility in executing complex SQL
queries directly on an SQLite database in Android applications.
SQLiteDatabase db=this.getWritableDatabase();
Cursor resultSet = db.rawQuery("Select * from Student",null);
resultSet.moveToFirst();
String enrollmentNo= resultSet.getString(0);
String name= resultSet.getString(1);
Data Insertion
● We can insert anything into the database using an object of the Cursor class. We will call
a method of this class called insert and it will insert the data into a given table of the
database.we can create table or insert data into table using execSQL method defined in
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("ID",101);
values.put("NAME",”Meera”);
db.insert("STUDENT",null,values);
Data Updation
● update(table_name,content_values,selection,selectionArgs)
● In Android development, the update() method is used to modify existing rows of
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("ID",101);
values.put("NAME",”Meera”);
db.update("STUDENT",values,"ID=?",new String[]{Id});
Data Deletion
● delete(table_name,selection,selectionArgs)
● In Android development, the delete() method is used to remove rows from an
SQLite database table based on a specified condition. It allows you to delete one
or more rows that match the given criteria.
● Here's a breakdown of the parameters used in the delete() method:
■ TABLE_NAME: The name of the table from which to delete rows.
SQLiteDatabase db=this.getWritableDatabase();
db.delete("STUDENT","ID=?",new String[]{Id});
Shared Preferences
● In android, Shared Preferences are used to save and retrieve the primitive data types
(integer, float,Boolean, string, long) data in the form of key-value pairs from a file within
an app's file structure.
● Generally, the Shared Preferences object will point to a file that contains a key-value
pair and provides a simple read and write method to save and retrieve the key-value
pairs from a file.
● The Shared Preferences file is managed by an android framework and it can be
accessed anywhere within the app to read or write data into the file, but it’s not
possible to access the file from any other app so it’s secured.
● The Shared Preferences are useful to store the small collection of key-values such as
user’s login information, app preferences related to users, etc. to maintain the state of
the app, next time when they login again to the app.
Method Description
getSharedPreferences() This method is useful to get the values from multiple shared
preference files by passing the name as parameter to
identify the file. We can call this from any Context in our
app.
● Following are the different ways to initialize the Shared Preferences in our application.
● If we are using a single shared preference file for our activity, then we need to initialize
the SharedPreferences object by using getPreferences() method as shown below.
● In case, if we are using multiple shared preference files, then we need to initialize the
SharedPreferences object by using getSharedPreferences() method like shown below.
● Here, the name “filename1” is the preference file, which wants to read the values based
on our requirements and the context mode MODE_PRIVATE, will make sure that the file
can be accessed only within our application.
● To store data in a shared preference file, we need an editor to edit and save the changes
in the SharedPreferences object. Following is the code snippet to store the data in a
shared preference file using editor.
● To read or retrieve a value from a Shared Preferences file, we need to call methods such
as getInt(), getString(), etc. by providing the key for the value which we want to get as
shown below.
● To delete a value from a Shared Preferences file, we need to call a remove() method by
providing the key for the value which we want to delete as shown below.
● If you observe the above code snippet, we are deleting the values from shared
preferences using a method called remove() by providing the key for the value which we
want to delete and committing the changes to the shared preferences file using
commit() method.
● We can clear all the data from the Shared Preferences file using the clear() method like
shown below.
● If you observe the above code snippet, we are clearing all the values from shared
preferences using a method called clear() and committing the changes to the shared
preferences file using commit() method.
● Now we will see how to store and retrieve primitive data type key-value pairs in a shared
preferences file using the SharedPreferences object in an android application with
examples.
File Storage
● Android provides many kinds of storage for applications to store their data. These
storage places are shared preferences, internal and external storage, SQLite storage, and
storage via network connection.
● In this topic we are going to look at the internal storage. Internal storage is the storage
of the private data on the device memory.
● By default these files are private and are accessed by only your application and get
deleted , when the user deletes your application.
Writing file
● In order to use internal storage to write some data in the file, call the openFileOutput()
method with the name of the file and the mode. The mode could be private , public
Reading file
● In order to read from the file you just created , call the openFileInput() method with the
name of the file. It returns an instance of FileInputStream.
● After that, you can call the read method to read one character at a time from the file
and then you can print it.
Content Provider
● A content provider manages access to a central repository of data. A provider is part of
an Android application, which often provides its own UI for working with the data.
However, content providers are primarily used by other applications, which access the
provider using a provider client object.
● What is Content URI(Universal Resource Identifier)?
○ Content URI is the key concept of a content provider. To query a content provider,
you can specify the query string in the form of URI.
○ URI: content://authority/data_type/id
○ content:// →This is a prefix of all the URI and it is a mandatory part of URI.
○ authority →This part should be always unique for every content provider, it
specifies the name of the content provider. for example contacts, browsers etc.
○ data_type → This indicates the type of data provider by content provider.
● ContextCompat is a useful utility class in Android that allows you to work with the
Context object in a backward-compatible way. It provides methods for accessing
resources, performing permission checks, working with drawables, and more.
● A contract class is a public final class that contains constant definitions for the URIs,
column names, MIME types, and other meta-data about the ContentProvider. It can also
contain static helper methods to manipulate the URIs.
● ContentResolver is a “class that provides applications access to the content model”.
ContentResolvers expose methods to interact, fetch, or modify content provided from
the following: Installed apps ( content:// URI scheme) File systems ( file:// URI scheme).
if(ContextCompat.checkSelfPermission(getApplicationContext(), permission.READ_CONTACTS)!=
PackageManager.PERMISSION_GRANTED) {
}
}
Telephony Services(API)
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
● Use the TelephonyManager object to retrieve the state of the phone and some
information about the phone service itself, such as the phone number of the handset.
● One important method is getCallState().This method can determine the voice call status
of the handset.
● Various states are :
○ CALL_STATE_IDLE – when there is no incoming call
○ CALL_STATE_OFFHOOK – when the line is busy
○ CALL_STATE_RINGING – when call is incoming
● In addition to call and service state information, your application can retrieve other
information about the device like :
● The network operator name is the descriptive name of the current provider that the
handset connects to.This is typically the current tower operator.
● The SIM operator name is typically the name of the provider that the user is subscribed
to for service.
Using SMS
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage("789654123",null,"Hello, This is Test Message",null,null);
Web API
● Android applications can simply use the WebView control to display web content to the
screen, which can think of WebView control as a browser-like view.
● The WebView control uses the WebKit rendering engine to draw HTML content on the
screen.
● This content could be HTML pages on the Web or it can be locally sourced.
● It does not have all the features of a full browser.It does not display the title of a
webpage or provide buttons for reloading pages.
● If the user clicks on a link within the WebView control, that action does not load the new
page within the view. Instead, it fires up the Browser application.
● By default, all the WebView control does is display the web content provided by the
developer using its internal rendering engine,WebKit.
● Use three classes, in particular, to help modify the behavior of the control:
○ WebSettings class
○ WebViewClient class, and
○ WebChromeClient class.
● WebKit is an open source browser engine.Using the WebView control requires the
android.permission.INTERNET permission.
● You can add this permission to your application’s Android manifest file as follows:
WebView
● The WebView control can be added to a layout resource file like any other view.
● It can take up the entire screen or just a portion of it. A typical WebView definition in a
layout resource might look like this:
<WebView
android:id=”@+id/web_holder”
android:layout_height=”wrap_content”
android:layout_width=”fill_parent”
/>
● You can load content into a WebView control in a variety of ways.For example, WebView
control can load a specific website or render raw HTML content.
● Web pages can be stored on a remote web server or stored of the device.how to use a
WebView control to load content from a specific website:
WebView webview=findViewById(R.id.w1);
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("https://www.w3schools.com");
● If, instead, you want to render raw HTML, you can use the loadData() method:
● Load an HTML file called demo.html stored in the application’s assets directory like this:
w1.loadUrl("file:///android_asset/demo.html");
URL Parsing
● When you want the user to have full access to all Browser features, such as bookmarking
and browsing, you’re better off launching the Browser application to a specific
website,letting users do their browsing, and having them return to your application
when they’re done.
● You can do this as follows:
Network API
● Android network connectivity services allow us to check the network connectivity
information of the device. It is very important to check the internet connection of the
device while performing the task which is based on internet service such as fetching data
from the server (internet) or writing data to the server.
● Using Android Network Connectivity Services we can also determine the types of a
network of android devices. It may be of types TYPE_WIFI (wifi), TYPE_MOBILE
(mobile), TYPE_BLUETOOTH (Bluetooth), etc.
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
ConnectivityManager connectivityManager=
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
Sending Notifications
nBuilder.setSmallIcon(R.drawable.ic_launcher_background);
nBuilder.setContentTitle("TITLE");
nBuilder.setContentText("TEXT");
nBuilder.setChannelId("atmiya");
nBuilder.setContentIntent(pi);
Vibrating Phone
● In android, using vibrate service, we can vibrate android mobile.
● To use the vibrator services , we have to add permission in android manifest file:
● In the code below, we have taken vibrate service, it is a system service as shown
below.we have given 500ms so it is going to vibrate 500ms continuously.
LocationManagerlocationManager=(LocationManager)getSystemService(Context.LOC
ATION_SERVICE);
● Next step is to identify the location provider you would like to use for retrieving location
details.The location providers actually provide the location data in Android. Android
exposes two main locations.
{
employee: {
name: meera shah ,
salary:5000
}
}
e.printStackTrace();
}
<?php
header("Content-Type: application/json; charset=UTF-8");
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
switch ($request_method) {
case 'GET':
// Retrieve users
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
$users = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$users[] = $row;
}
}
echo json_encode($users);
break;
case 'POST':
// Add a new user
$data = json_decode(file_get_contents("php://input"), true);
// $name = $data['name'];
// $email = $data['email'];
$name ="111";
$email = "[email protected]";
$conn->close();
?>
if(data==null){
break;
}
Log.d("data",data);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
}