1 compatibility with new OS versions. Finally, interactive.
If the activity is interrupted, such going to discuss about the process of
What do you mean by mobile programming? monitoring & analytics are used to track the as by an incoming call, it enters the declaring both the activities “FirstActivity”
Features app's performance & user engagement, onPause() state, where it is partially and “SecondActivity” in manifest file.
Mobile programming involves developing providing insights for further improvements. obscured but still alive. If the activity is no AndroidManifest.xml
applications specifically for mobile devices This structured lifecycle ensures that mobile longer visible, it moves to the onStop() <?xml version="1.0" encoding="utf-8"?>
like smartphones & tablets. The development apps meet user needs, perform well, & phase, where it releases resources that aren't <manifest
process can follow four major approaches. remain relevant in a rapidly evolving needed when the activity is not visible. xmlns:android="http://schemas.android.com/
Mobile application development is the set of technological landscape. Finally, the activity can either be restarted, apk/res/android"
processes and procedures involved in writing Features of Mobile Devices: returning to onStart(), or destroyed, entering package="com.example.raazu.myapplication"
software for small, wireless computing Mobile devices, particularly smartphones & the onDestroy() phase, where it is >
devices, such as smartphones and other tablets, come with various features that completely removed from memory. <application
hand-held devices. make them versatile & powerful tools for Understanding this lifecycle helps developers android:allowBackup="true"
A mobile device has the following features: communication, productivity, entertainment, manage resources efficiently, save user data, android:icon="@mipmap/ic_launcher"
• It’s portable. & more. & ensure a smooth user experience.: android:label="@string/app_name"
• It’s personal. Some of the core features include: Creating Multiple Activities: Example android:roundIcon="@mipmap/ic_launcher_r
• It’s with you almost all the time. > Portability: Mobile devices are compact & Now we are going to create multiple activities ound"
• It’s easy and fast to use. lightweight, designed to be carried around and also going to learn about linking different android:supportsRtl="true"
• It has some kind of network connection. easily. activities. For this purpose, I am going create android:theme="@style/AppTheme">
==================================== >Wireless Connectivity: Includes cellular two activities having the name “FirstActivity” <activity android:name=".FirstActivity">
Explain History of Android and it’s versions in networks (4G, 5G), Wi-Fi, Bluetooth, NFC, & and “SecondActivity”. FirstActivity contains <intent-filter>
brief GPS. TextView and Button. On the other hand, <action
The code names of android ranges from A to J >Operating Systems: Mobile devices run on SecondActivity contains a TextView. android:name="android.intent.action.MAIN"
currently, such as Aestro, Blender, Cupcake, specific OS like &roid, iOS, & less commonly, FirstActivity.java />
Donut, Eclair, Froyo, Gingerbread, Windows Mobile. import android.app.Activity; <category
Honeycomb, Ice Cream Sandwitch, Jelly Bean, > Camera: High-resolution cameras with import android.os.Bundle; android:name="android.intent.category.LAU
KitKat and Lollipop. advanced features like image stabilization, public class FirstActivity extends Activity { NCHER"/>
1.Initially, Andy Rubin founded Android zoom, & multiple lenses. @Override </intent-filter>
Incorporation in Palo Alto, California, United > Battery Life: Devices are optimized for protected void onCreate(Bundle </activity>
States in October, 2003. energy efficiency to provide savedInstanceState) { <activity android:name=".SecondActivity"/>
2.In 17th August 2005, Google acquired > Security Features: Biometric authentication super.onCreate(savedInstanceState); </application>
android Incorporation. Since then, it is in the (fingerprint, facial recognition), encryption, & setContentView(R.layout.first_activity); </manifest>
subsidiary of Google Incorporation. secure boot. }} >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
SecondActivity.java Q: What is the role of intent-filter for any
Categories of Mobile Devices: Mobile devices import android.app.Activity; activity? Explain.
can be broadly categorized into several types: import android.os.Bundle; In Android, an <intent-filter> is used in the
> Smartphones: The most common mobile public class SecondActivity extends Activity { AndroidManifest.xml file to specify how an
devices, offering advanced computing ability, @Override activity (or service/broadcast receiver) can be
connectivity, & multimedia capabilities. protected void onCreate(Bundle b){ launched by intents. App activities, services,
> Tablets: Larger than smartphones, tablets super.onCreate(b); and broadcast receivers are activated by
offer a bigger screen & are often used for setContentView(R.layout.second_activity); intents. An intent is a message defined by an
media consumption, gaming, & productivity. }} Intent object that describes an action to
> Wearables: Includes smartwatches & first_activity.xml perform, including the data to be acted upon,
fitness trackers that offer health tracking, <?xml version="1.0" encoding="utf-8"?> the category of component that should
notifications, & some level of app interaction. <LinearLayout perform the action, and other instructions.
> Gaming Consoles: Handheld gaming xmlns:android="http://schemas.android.com/ When an app issues an intent to the system,
devices that focus on gaming with additional apk/res/android" the system locates an app component that
There are four major development connectivity & multimedia features. android:layout_width="match_parent" can handle the intent based on intent filter
approaches when building mobile * Major Brands & Models: android:layout_height="match_parent" declarations in each app's manifest file. The
applications: > Apple: Known for the iPhone series (iPhone android:orientation="vertical"> Role of intent-filter for an Activity:
5, 6, X, 12, 13, 14). <TextView > Declares the capability of the activity: An
> Samsung: Known for the Galaxy series android:layout_width="wrap_content" intent-filter tells the Android system what
Native app development focuses on building
(Galaxy S, Note, Z Fold, A series). android:layout_height="wrap_content" types of intents the activity can respond to,
apps for a specific platform (such as &roid or
> Google: Known for the Pixel series (Pixel 3, android:text="This is First Activity" such as opening a web page, sending a
iOS) using platform-specific languages &
4, 5, 6, 7). android:textSize="20sp" message, or being the launcher activity.
tools, offering high performance & full access
> Huawei: Known for the Mate & P series android:textStyle="bold" > Enables implicit intents: an app sends an
to device features, though it requires
(Mate 20, P30 Pro, Mate 40). android:layout_gravity="center" implicit intent (without specifying the target
maintaining separate codebases for each
> Xiaomi: Known for the Mi, Redmi, & Poco android:layout_marginTop="100dp" component), the system uses intent-filter
platform.
series. android:id="@+id/text1" information to find matching activities.
Mobile Platforms: /> > Allows activities to be entry points:
Cross-platform development allows apps to > Android: Developed by Google, &roid is the <Button Without an intent-filter, an activity cannot be
run on multiple platforms from a single most widely used mobile OS globally. It is android:layout_width="wrap_content" launched externally (i.e., by other apps or
codebase, using tools like React Native or open-source & allows extensive android:layout_height="wrap_content" system events).
Flutter, which speeds up development & customization by manufacturers. android:text="Click Me"
reduces costs, but may compromise > iOS: Developed by Apple, iOS is known for android:textSize="20sp" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
performance. its smooth user experience, strong security android:layout_gravity="center" The AndroidManifest.xml file is a critical
Hybrid app development creates web apps features, & integration with other Apple android:id="@+id/button1" component of every app. It acts as a blueprint
wrapped in a native container, enabling devices. /> for the application, providing essential
installation like native apps while being > Windows Mobile: Microsoft's mobile os </LinearLayout> information that the android system needs to
developed using web technologies such as which has largely been phased out but was second_activity.xml run the app. This file declares the app's
HTML, CSS, & JavaScript. These apps are known for its integration with Windows- <?xml version="1.0" encoding="utf-8"?> components (activities, services, broadcast
quicker to develop but may offer a less native based PCs. <LinearLayout receivers, & content providers), the required
experience. > BlackBerry OS: Was popular for its security xmlns:android="http://schemas.android.com/ permissions, hardware &s/w features the app
Progressive Web Apps (PWAs) function like features & email capabilities, mostly used by apk/res/android" needs, & other metadata like the app's
native apps but are accessible through a business professionals. android:layout_width="match_parent" theme, icon, & label.
browser, offering a single codebase that ================================ android:layout_height="match_parent" Add an Activity in the Manifest?
works across devices, though with limited An Android Activity: is a core component of android:orientation="vertical"> To add an activity in the AndroidManifest.xml
access to device features. an app that represents a single screen with <TextView file, you declare it within the <application>
which users can interact. It serves as a android:layout_width="wrap_content" tag using the <activity> element. This
The mobile app development lifecycle window or page where the app displays its android:layout_height="wrap_content" declaration informs the android system that
begins with planning, where the app's (UI) & handles user interactions, such as android:text="This is Second Activity" the activity exists & allows it to be used
purpose, features, & target audience are tapping, swiping, or entering text. Each android:textSize="20sp" within the app.
defined. This is followed by design, focusing activity is independent, & an app can have android:textStyle="bold" Example of Adding an Activity in the Manifest
on creating a user-friendly interface & multiple activities to perform different tasks, android:layout_gravity="center" Here’s an example of how you would add an
experience through wireframing & such as showing a login screen, displaying a android:layout_marginTop="100dp" activity named Second Activity to the
prototyping. The development stage involves list of items, or navigating to a detailed view. android:id="@+id/text2" androidManifest.xml file:
writing the code for both the frontend & The android Activity Lifecycle is a sequence /> <manifest
backend, integrating third-party services, & of states that an activity goes through from </LinearLayout> xmlns:android=http://schemas.&roid.com/apk/re
ensuring the app functions correctly. Testing the moment it is created until it is destroyed. s/android package="com.example.myapp">
is crucial for identifying & fixing bugs, The lifecycle begins with the <application
onCreate() method, where the activity is first android:allowBackup="true"
ensuring performance, & validating the app
initialized, including setting up the UI & android:icon="@mipmap/ic_launcher"
with users. After testing, the app moves to
android:label="@string/app_name
deployment, where it is released to users via restoring any previous state. Next, the
android:supportsRtl="true"
app stores or other distribution channels. activity enters the onStart() phase, where it
Declaring Activities in Manifest android:theme="@style/AppTheme">
Maintenance involves ongoing support, such becomes visible to the user, followed by <!-- Main activity -->
onResume(), where it gains focus & becomes Since we got only single activity to be
as fixing bugs, adding features, & ensuring <activity android:name=".MainActivity">
declared in manifest file. But now we are
<intent-filter> //passing data using putExtra /> experiences. It usually resides on the device,
<action i.putExtra("id",001); <Button or there is at least an icon representing the
android:name="android.intent.action.MAIN" /> i.putExtra("name","Ram"); android:layout_width="wrap_content"
app that is visible on the home screen or is
<Category i.putExtra("address","KTM"); android:layout_height="wrap_content"
android:name="android.intent.category.LAUNCH startActivity(i); android:text="Go to Second" pinned in the application CatLog of the
ER" /> }});} android:textSize="20sp" device. The application can be downloaded
</intent-filter> } android:layout_gravity="center" from the platform app store, side-loaded
</activity> SecondActivity.java android:id="@+id/button1"
directly onto the device, or can be reached
<!-- Second activity --> public class SecondActivity extends Activity { />
<activity android:name=".SecondActivity" /> @Override </LinearLayout> through the device’s browser.
</application></manifest> protected void onCreate(Bundle b){ second_activity.xml • Regardless of what front-end platform or
super.onCreate(b); <?xml version="1.0" encoding="utf-8"?> development methodology is being used,
How can you pass data between multiple setContentView(R.layout.second_activity); <LinearLayout
delivering high-quality mobile applications
activities using intent? Explain. //receiving data xmlns:android="http://schemas.android.com/ap
An intent is an object that a component can use Intent i=getIntent(); k/res/android" that delight and retain users requires reliable
to communicate with the OS. The only int id=i.getIntExtra("id",0); android:layout_width="match_parent" back-end services.
components you have seen so far are activities, //second argument is default value android:layout_height="match_parent" • Given the critical importance of back-end
but there are also services, broadcast receivers, String name=i.getStringExtra("name"); String android:orientation="vertical">
services for the success of the mobile
and content providers. Intents are multi-purpose address=i.getStringExtra("address"); //Displaying <TextView
communication tools, and the Intent class received data in TextView TextView android:layout_width="wrap_content" application, the developers have several
provides different constructors depending on txt=findViewById(R.id.text2); android:layout_height="wrap_content" important architectural decisions that they
what you are using the intent to do. In this case, txt.setText("Id="+id+"\n"+"Name="+name+"\n"+ android:text="This is Second Activity" must consider. These decisions include which
you are using an intent to tell the "Address="+ address); android:textSize="20sp"
services should they build themselves and
ActivityManager which activity to start, so you android:textStyle="bold"
will use this constructor: android:layout_gravity="center" which third party services should they
public Intent(Context packageContext, Class<?> android:layout_marginTop="100dp" leverage, and then should they run and
}} android:id="@+id/text2"
cls) Through Intent we can move from one maintain their own services or should they
activity to another activity and Intent can also be />
Getting Result Back form Child Activity take advantage of 3rd party services.
used to pass the data from one activity to <Button
another activity. In previous example, we pass data from android:layout_width="wrap_content" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Step 1: First of all, we have to link the views of FirstActivity to SecondActivity. Now if we android:layout_height="wrap_content" Environment Setup For android application
activity_login.xml with LoginActivity In want to pass data from SecondActivity back android:text="Go to First" Development
activity_login.xml, we have used two EditTexts to FirstActivity then we should use following android:textSize="20sp" In order to write an Android application, we
and one button. Lets initialize them in our procedure: android:layout_gravity="center"
are going to need a development
LoginActivity. FirstActivity.java android:id="@+id/button2"
public class LoginActivity extends public class FirstActivity extends Activity { /> environment. Google has made a very useful
AppCompatActivity { EditText TextView txt; </LinearLayout> tool for all Android Developers, the Android
edittextfullname,edittextusername; Button btn; >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Studio. Android Studio is the official IDE for
Button loginbutton; @Override Why we use Toast? How Toast can be used Android development, and with a single
@Override protected void onCreate(Bundle in android application? Explain with suitable
protected void onCreate(Bundle savedInstanceState) { download includes everything you need to
A Toast is a small message that pops up on
savedInstanceState) { super.onCreate(savedInstanceState); the screen to provide feedback to the user. It begin developing Android apps.
super.onCreate(savedInstanceState); setContentView(R.layout.first_activity); only appears for a short period and then Step 1 - First we have to have installed the
setContentView(R.layout.activity_login); txt=findViewById(R.id.text1);
disappears automatically. It only fills the Java Development Kit (JDK) from Oracle.
edittextfullname=findViewById(R.id.editTextFullN btn=findViewById(R.id.button1);
amount of space required for the message Step 2 – After installing JDK, now it’s the time
ame); btn.setOnClickListener(new
edittextusername=findViewById(R.id.editTextUse View.OnClickListener() {
and the current activity remains visible and for you to setup environment variables. For
rName); @Override interactive. Toasts automatically disappear
this procedure, right click This PC (My
loginbutton=findViewById(R.id.LoginButton); }} public void onClick(View view) { after a timeout.
Why do we use Toast? Computer) -> Properties -> Advanced System
Step2: Now we have to create a new activity so Intent i=new Intent(FirstActivity.this,
let’s create an activity SecondActivity.class); > To show temporary messages to the user. Settings -> Environment Variables -> New.
Name the new activity as SecondActivity. //starting activity with result code 2 > To give non-intrusive feedback (e.g., Step 3 – Now download the latest android
Now you have created two Activities. With the startActivityForResult(i,2); “Message Sent”, “Saved Successfully”). studio and install in your system.
help of Intent,we will go from one activity to } >It does not block user interaction and does Step 4: Download the android emulator from
another activity (LoginActivity toSecondActivity) }); } not require user input
Step 3: When we press the button, // Call Back method to get the Message form android studio to run the program
Syntax
setOnClickListener() will be called and inside other Activity Toast tost= Toast.makeText(Context c, >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
setOnClickListener(), we will write code to open @Override CharacterSequence text, int duration).show(); Intent filters roles for any activity
new activity and we can do this with the help of protected void onActivityResult(int requestCode, App activities, services, and broadcast
To control toast’s position on screen by using
Intent. int resultCode, Intent data) {
setGravity(int gravity, intxdist, int ydist) You receivers are activated by intents. An intent is
Step4: If we have to open one activity from super.onActivityResult(requestCode, resultCode,
another activity we have to add an Intent code in data); can use the following constants in the Gravity a message defined by an Intent object that
onClick(View view) method as shown below. // check if the request code is same as what is class to specify the overall position: TOP describes an action to perform, including the
Intent intent = new Intent(Source, Destination); passed here it is 2 data to be acted upon, the category of
BOTTOM, LEFT, RIGHT, CENTER,
startActivity(intent); if(requestCode==2) {
CENTER_HORIZONTAL, CENTER_VERTICAL component that should perform the action,
Stringmessage=data.getStringExtra("message");
Step 5: To pass the data through Intent we will txt.setText(message); Toast toast = and other instructions. When an app issues
use putExtra() method and in parameter, we will }}} Toast.makeText(getApplicationContext(),"Firs an intent to the system, the system locates an
use Key-Value Pair. app component that can handle the intent
t", Toast.LENGTH_LONG);
SecondActivity.java
toast.setGravity(Gravity.CENTER, 0, 0); based on intent filter declarations in each
Step 6: Now open the SecondActivity. public class SecondActivity extends Activity {
The data is successfully passed. Button btn; toast.show(); app's manifest file. The system launches an
Passing Data Between Activities: using intent @Override Toast second = instance of the matching component and
Between activities data can be passed and protected void onCreate(Bundle b){ passes the Intent object to that component. If
Toast.makeText(getApplicationContext(),"Sec
received by using Intent extras. Extras are super.onCreate(b);
ond", Toast.LENGTH_LONG); more than one app can handle the intent,
arbitrary data that the calling activity can include setContentView(R.layout.second_activity);
with an intent. The OS forwards the intent to the btn=findViewById(R.id.button2); second.setGravity(Gravity.TOP, 0, 0); then the user can select which app to use.
recipient activity, which can then access the btn.setOnClickListener(new second.show(); > An app component can have any number of
extra and retrieve the data. An extra is View.OnClickListener() { Toast bottom = intent filters (defined with the <intent-filter>
structured as a key-value pair. To add an extra to @Override Toast.makeText(getApplicationContext(),“Thir element), each one describing a different
an intent, you use Intent.putExtra(...). In public void onClick(View view) { capability of that component. If activity is
d", Toast.LENGTH_LONG);
particular, you will be calling public Intent Intent i=new Intent(); defined with <intent-filter> element in
bottom.setGravity(Gravity.BOTTOM, 0, 0);
putExtra(String name, boolean value) i.putExtra("message","Hello First Activity!"); manifest file than that activity will be
Intent.putExtra(...) comes in many flavors, but it setResult(2,i);
bottom.show();
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> launched as the first activity of application.
always has two arguments. The first argument is finish(); //finishing activity. }
Mobile Application Development Lifecycle >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
always a String key, and the second argument is }); }}
the value, whose type will vary. Suppose if we There are two interlinked core components Explain any four widgets with their
first_activity.xml
want to pass data like id, name and address of <?xml version="1.0" encoding="utf-8"?> of a mobile application: 1) the mobile attributes in detail android?
student from FirstActivity to SecondActivity then <LinearLayout application “Front-End” that resides on the A widget is a small gadget or control of your
we can use Intent extras as follows: xmlns:android="http://schemas.android.com/ap mobile device, and 2) the services “Back-End” android application placed on the home
FirstActivity.java k/res/android" that supports the mobile front-end. screen. Widgets can be very handy as they
public class FirstActivity extends Activity { android:layout_width="match_parent" allow you to put your favourite applications
@Override android:layout_height="match_parent" on your home screen in order to quickly
protected void onCreate(Bundle android:orientation="vertical"> access them. You have probably seen some
savedInstanceState) { <TextView common widgets, such as music widget,
super.onCreate(savedInstanceState); android:layout_width="wrap_content" weather widget, clock widget e.t.c
setContentView(R.layout.first_activity); android:layout_height="wrap_content" > Information widgets: are by far the most
Button btn=findViewById(R.id.button1); android:text="This is First Activity" common type of widget. They display vital
btn.setOnClickListener(new android:textSize="20sp"
information from an app that is easily visible
View.OnClickListener() { @Override android:textStyle="bold"
public void onClick(View view) {
• The mobile front-end is the visual and without actually accessing the app’s main UI.
android:layout_gravity="center"
Intent i=new Intent(FirstActivity.this, android:layout_marginTop="100dp" interactive part of the application the user Things like clocks, weather apps, sports score
SecondActivity.class); android:id="@+id/text1" trackers, and other sorts of things are all
good examples of informational widgets. It’s android:orientation Should the layout be a android:text="Label 3" > Constraint Layout: Constraint layout is an
important to remember that only the most column or a row? Use android:textSize="20sp" advanced version of a Relative layout. It is
vital information should be supplied in order "horizontal" for a row, android:layout_x="180dp" used to reduce the child view hierarchies and
"vertical" for a column. android:layout_y="150dp" />
to not clutter the home screen with too much improve the performance. It is used to define
information. Users typically have control over </AbsoluteLayout> a layout by assigning constraints for every
android:weightSum Defines the maximum
just how much information is displayed by an weight sum. child view/widget relative to other views
Table layout: TableLayout is a layout that
informational widget and, usually, touching present. A ConstraintLayout is similar to a
===================================== arranges its children into rows and columns.
the widget will open more detailed RelativeLayout, but with more power. The
> Relative Layout: Relative Layout is a view It consists of a number of TableRow objects,
information about what it’s displaying. aim of ConstraintLayout is to improve the
group that displays child views in relative each defining a row (actually, you can have
> Collection widgets: are similar to performance of the applications by removing
positions. The position of each view can be other children, which will be explained below).
information widgets in that they display the nested views with a flat and flexible
specified as relative to sibling elements (such TableLayout containers do not display border
information, however, the difference is that design.
as to the left-of or below another view) or in lines for their rows, columns, or cells. Each row
collection widgets display an aggregate of a Following code snippet will demonstrate
positions relative to the parent Relative has zero or more cells; each cell can hold one
bunch of different sources; such as news constraint layout.
Layout area (such as aligned to the bottom, View object. The table has as many columns as
article titles, galleries of images, or other lists <?xml version="1.0" encoding="utf-8"?>
left or center). the row with the most cells. A table can leave
comprised of multiple sources. Generally, this <android.support.constraint.ConstraintLayout
A RelativeLayout is a very powerful utility for cells empty. Cells can span columns, as they
lets the user do two things: browse a xmlns:android="http://schemas.android.com/
designing a user interface because it can can in HTML.
selection of items, and select one to look at apk/res/android"
eliminate nested view groups and keep your The children of a TableLayout cannot specify
more closely. xmlns:app="http://schemas.android.com/apk
layout hierarchy flat, which improves the layout_width attribute. Width is always
> Control widgets give simple access to basic /res-auto"
performance.. MATCH_PARENT. However, the layout_height
and essential features of an existing app. android:layout_width="match_parent"
Following code snippet will demonstrate attribute can be defined by a child; default
They’re sort of like remote controls – they android:layout_height="match_parent">
RelativeLayout: value is
offer control over a part of the app’s function <TextView
<?xml version="1.0" encoding="utf-8"?> ViewGroup.LayoutParams.WRAP_CONTENT.
that you can access without opening the app. android:layout_width="wrap_content"
<RelativeLayout If the child is a TableRow, then the height is
For example, a control widget could turn on android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/ap always
or off phone settings such as Bluetooth, WI-Fi android:text="Label 1"
k/res/android" ViewGroup.LayoutParams.WRAP_CONTENT.
and screen brightness, without having to go android:id="@+id/label1"
android:layout_width="match_parent"
into the settings. Control widgets can also android:textSize="20sp"/>
android:layout_height="match_parent">
feature a detailed view of something, such as <TextView
<TextView
a search result or a data set. android:layout_width="wrap_content" android:layout_width="wrap_content"
> Hybrid widget: As the name suggests, android:layout_height="wrap_content" android:layout_height="wrap_content"
hybrid apps combine the functionality of two android:text="Label 1" android:text="Label 2"
or more different types of other widgets. This android:textSize="20sp" android:collapseC The zero-based index of the android:textSize="20sp"
can be tricky to program, but they often offer android:id="@+id/label1" /> olumns columns to collapse. The column android:id="@+id/label2"
seamless and fully-integrated options that <TextView indices must be separated by a app:layout_constraintLeft_toRightOf="@+id/l
users enjoy. An example of a hybrid widget is android:layout_width="wrap_content" comma: 1, 2, 5. Illegal and abel1"
android:layout_height="wrap_content" duplicate indices are ignored.
a widget for a music player that, in addition app:layout_constraintTop_toBottomOf="@+i
android:text="Label 2" android:shrinkCol The zero-based index of the
to offering control over music, also includes d/label1" />
android:textSize="20sp" umns columns to shrink. The column
information about the song, band, album, indices must be separated by a <TextView
and so forth. android:id="@+id/label2" android:layout_width="wrap_content"
comma: 1, 2, 5. Illegal and duplicate
android:layout_toRightOf="@+id/label1"/>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> indices are ignored. You can shrink all android:layout_height="wrap_content"
<TextView columns by using the value "*"
Android Layout Types with examples: android:text="Label 3"
android:layout_width="wrap_content" instead. Note that a column can be
A layout defines the structure for a user android:layout_height="wrap_content" android:textSize="20sp"
marked stretchable and shrinkable
interface in your app, such as in an activity. android:text="Label 3" android:id="@+id/label3"
at the same time.
All elements in the layout are built using a android:textSize="20sp" app:layout_constraintBottom_toTopOf="@+i
android:stretchCo The zero-based index of the
hierarchy of View and View Group objects. A android:id="@+id/label3" lumns columns to stretch. The column d/label2"
View usually draws something the user can android:layout_below="@+id/label1" /> indices must be separated by a app:layout_constraintLeft_toRightOf="@+id/l
see and interact with. </RelativeLayout> comma: 1, 2, 5. Illegal and duplicate abel2" />
Following are the different types of layout android:layout_above Positions the indices are ignored. You can stretch </android.support.constraint.ConstraintLayou
used for designing the User Interface. bottom edge of this all columns by using the value "*" t>
view above the instead. Note that a column can
* Linear Layout given anchor view following dependency in your build.gradle file.
be marked stretchable and
* Relative Layout ID. shrinkable at the same time. implementation
* Constraint layout android:layout_center If true, centers this Example: 'com.android.support.constraint:constraint-
> Linear Layout: Linear Layout is a view group Vertical child vertically layout:1.1.3'
within its parent. <?xml version="1.0" encoding="utf-8"?>
that aligns all children in a single direction, <TableLayout However, the ConstraintLayout features several
android:layout_center If true, centers
vertically or horizontally. You can specify the Horizontal this child xmlns:android="http://schemas.android.com/ap more attributes:
layout direction with the android: orientation horizontally k/res/android"
> layout_constraintTop_toTopOf — Align the top
attribute. All children of a LinearLayout are within its android:layout_width="match_parent"
of the desired view to the top of another.
stacked one after the other, so a vertical list parent. android:stretchColumns="*" >layout_constraintBottom_toBottomOf — Align
will only have one child per row, no matter android:layout_alignLeft Makes the left android:collapseColumns="1" the bottom of the desired view to the bottom of
how wide they are, and a horizontal list will edge of this android:layout_height="match_parent"> another
view match the <TableRow
only be one row high (the height of the tallest > layout_constraintLeft_toRightOf -Align the left
left android:layout_height="match_parent"
child, plus padding). A LinearLayout respects edge of the given of the desired view to the right of another
android:layout_width="match_parent">
margins between children and the gravity anchor view ID. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<TextView
(right, center, or left alignment) of each child. Event Handling in detail:
android:layout_width="wrap_content"
Example: ===================================== android:layout_height="wrap_content" Events are a useful way to collect data about
<?xml version="1.0" encoding="utf-8"?> AbsoluteLayout: An Absolute Layout lets you specify android:text="Label 1" android:textSize="20sp" a user's interaction with interactive
<LinearLayout exact locations (x/y coordinates) of its children.
android:layout_column="1"/> components of Applications. Like button
Absolute layouts are less flexible and harder to
xmlns:android="http://schemas.android.com/ <TextView presses or screen touch etc. The Android
maintain than other types of layouts without
apk/res/android" absolute positioning. android:layout_width="wrap_content" framework maintains an event queue as first-
android:layout_width="match_parent" android:layout_x This specifies the x- android:layout_height="wrap_content"
android:layout_height="match_parent" coordinate of the view. android:text="Label 2"
android:orientation="vertical"> android:layout_y This specifies the y- android:textSize="20sp"
<TextView coordinate of the view. android:layout_column="2"/>
android:layout_width="wrap_content" <?xml version="1.0" encoding="utf-8"?> </TableRow>
android:layout_height="wrap_content" <AbsoluteLayout <TableRow
xmlns:android="http://schemas.android.com/ap android:layout_height="match_parent"
android:text="This is label 1"
k/res/android" android:layout_width="match_parent">
android:textSize="20sp"/> in, first-out (FIFO) basis.
android:layout_width="match_parent" <TextView
<TextView android:layout_width="wrap_content" There are following three concepts related
android:layout_height="match_parent">
android:layout_width="wrap_content" <TextView android:layout_height="wrap_content" to Android Event Management:
android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Label 3" android:textSize="20sp" • Event Listeners − An event listener is an
android:text="This is label 2" android:layout_height="wrap_content" android:layout_column="1"/> interface in the View class that contains a
android:textSize="20sp"/> android:text="Label 1" <TextView single callback method. These methods will
<TextView android:textSize="20sp" android:layout_width="wrap_content" be called by the Android framework when
android:layout_width="wrap_content" android:layout_x="100dp" android:layout_height="wrap_content" the View to which the listener has been
android:layout_height="wrap_content" android:layout_y="50dp" /> android:text="Label 4" android:textSize="20sp" registered is triggered by user interaction
android:text="This is label 3" <TextView android:layout_column="2"/> with the item in the UI.
android:textSize="20sp"/> android:layout_width="wrap_content" <TextView
• Event Listeners Registration − Event
</LinearLayout> android:layout_height="wrap_content" android:layout_width="wrap_content"
Registration is the process by which an Event
When set to false, prevents android:text="Label 2" android:layout_height="wrap_content"
android:baselineAligned Handler gets registered with an Event
the layout from aligning its android:textSize="20sp" android:text="Label 5"
android:layout_x="150dp" android:textSize="20sp" Listener so that the handler is called when
children's baselines.
android:divider Drawable to use as a android:layout_y="100dp" /> android:layout_column="3"/> the Event Listener fires the event.
vertical divider between <TextView </TableRow> • Event Handlers − When an event happens
buttons. android:layout_width="wrap_content" </TableLayout> and we have registered an event listener for
android:layout_height="wrap_content" the event, the event listener calls the Event
Handlers, which is the method that actually } android:text="I am inside Fragment 2" receives its own input events, and which you
handles the event. @Override android:layout_gravity="center" can add or remove while the activity is
Examples: protected void onResume() { android:textSize="20sp" running (sort of like a "sub activity" that you
onClick(),onLongClick(),onTouch() etc super.onResume(); android:layout_marginTop="20sp" can reuse in different activities). A fragment
Log.d("Lifecycle Test", "Activity Resumed"); android:textStyle="bold" /> must always be hosted in an activity and the
} </LinearLayout>
Event Listener & Description fragment's lifecycle is directly affected by the
@Override Fragment1.java
onClick() This is called when the user host activity's lifecycle. The lifecycle of
either clicks or touches or
protected void onRestart() { public class Fragment1 extends Fragment {
super.onRestart(); @Override
android fragment is like the activity lifecycle.
focuses upon any widget like Example of Fragment
button, text, image etc. You Log.d("Lifecycle Test", "Activity Restarted"); public View onCreateView(LayoutInflater inflater,
will use onClick() event } ViewGroup Following example creates two fragments
handler to handle such event. @Override container, Bundle savedInstanceState) { named as Fragment1 and Fragment2. After
onLongClick() This is called when the user protected void onPause() { // Inflate the layout for this fragment creating fragments, we will add these two
either clicks or touches or super.onPause(); View view= inflater.inflate(R.layout.fragment1, fragments in activity named as FirstActivity
focuses upon any widget like Log.d("Lifecycle Test", "Activity Paused"); container, and display them.
button, text, image etc. for one } false); Firstly, we start by creating two fragments,
or more seconds. You will use @Override return view; fragment1.xml
onLongClick() event handler to protected void onStop() { }} <?xml version="1.0" encoding="utf-8"?>
handle such event.
super.onStop(); Fragment2.java <LinearLayout
onKey() This is called when the user is
Log.d("Lifecycle Test", "Activity Stopped"); public class Fragment2 extends Fragment { xmlns:android="http://schemas.android.com/ap
focused on the item and
} @Override k/res/android"
presses or releases a hardware
key on the device. You will use @Override public View onCreateView(LayoutInflater inflater, android:orientation="vertical"
onKey() event protected void onDestroy() { ViewGroup android:background="#AEB6BF"
handler to handle such event. super.onDestroy(); container, Bundle savedInstanceState) { android:layout_width="match_parent"
onCreateConte This is called when the context Log.d("Lifecycle Test", "Activity Destroyed"); // Inflate the layout for this fragment android:layout_height="match_parent">
xtMenu() menu is being built(as the } View view= inflater.inflate(R.layout.fragment2, <TextView
result of a sustained "long click) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> container, android:layout_width="wrap_content"
Introduction to Fragment Manager false); android:layout_height="wrap_content"
When the Fragment class was introduced in return view; android:text="I am inside Fragment 1"
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Honeycomb, the Activity class was changed }} android:layout_gravity="center"
What do you mean by android activity? to include a piece called the Now it’s time to create Activity with two Buttons android:textSize="20sp"
FragmentManager. The FragmentManager is as follows. android:layout_marginTop="20sp"
Explain android activity life cycle in detail.
first_activity.xml android:textStyle="bold" />
Every instance of Activity has a lifecycle. responsible for managing your fragments and
<?xml version="1.0" encoding="utf-8"?> </LinearLayout>
During this lifecycle, an activity transitions adding their views to the activity’s view
<LinearLayout fragment2.xml
between three possible states: running, hierarchy. We can use FragmentManager to xmlns:android="http://schemas.android.com/ap <?xml version="1.0" encoding="utf-8"?>
paused, and stopped. For each transition, manage fragments as follows: k/res/android" <LinearLayout
there is an activity method that notifies the FragmentManager fm=getFragmentManager(); android:layout_width="match_parent" xmlns:android="http://schemas.android.com/ap
activity of the change in its state. As a user The FragmentManager handles two things: a android:orientation="vertical" k/res/android"
navigates through, out of, and back to your list of fragments and a back stack of fragment android:layout_height="match_parent"> android:orientation="vertical"
app, the Activity instances in your app transactions. It is shown below: <Button android:background="#D0ECE7"
transition through different states in their android:layout_width="match_parent" android:layout_width="match_parent"
lifecycle. The Activity class provides a number android:layout_height="wrap_content" android:layout_height="match_parent">
of callbacks that allow the activity to know android:id="@+id/btnFirst" <TextView
that a state has changed: that the system is android:text="Fragment 1" /> android:layout_width="wrap_content"
<Button android:layout_height="wrap_content"
creating, stopping, or resuming an activity, or
android:layout_width="match_parent" android:text="I am inside Fragment 2"
destroying the process in which the activity
android:layout_height="wrap_content" android:layout_gravity="center"
resides. android:id="@+id/btnSecond"
Fragment transactions are used to add, android:textSize="20sp"
Let's see the 7 lifecycle methods of android android:text="Fragment 2" /> android:layout_marginTop="20sp"
activity. remove, attach, detach, or replace fragments <fragment android:id="@+id/myfragment" android:textStyle="bold" />
> onCreate: called when activity is first in the fragment list. They are the heart of android:name="com.example.raazu.myapplicatio </LinearLayout>
created. how you use fragments to compose and n.Fragment1" Fragment1.java
> onStart: called when activity is becoming recompose screens at runtime. The android:layout_width="match_parent" public class Fragment1 extends Fragment {
visible to the user. FragmentManager maintains a back stack of android:layout_height="match_parent" /> @Override
> onResume: called when activity will start fragment transactions that you can navigate. </LinearLayout> public View onCreateView(LayoutInflater inflater,
interacting with the user. The FragmentManager.beginTransaction() FirstActivity.java ViewGroup
> onPause: called when activity is not visible method creates and returns an instance of public class FirstActivity extends Activity { container, Bundle savedInstanceState) {
to the user. FragmentTransaction. The Fragment Button btnFirst,btnSecond; // Inflate the layout for this fragment
Transaction class uses a fluent interface – @Override View view= inflater.inflate(R.layout.fragment1,
> onStop: called when activity is no longer
methods that configure FragmentTransaction protected void onCreate(Bundle container,
visible to the user.
savedInstanceState) { false);
> onRestart: called after your activity is return a FragmentTransaction instead of void,
super.onCreate(savedInstanceState); return view;
stopped, prior to start. which allows you to chain them together.
setContentView(R.layout.first_activity); }}
> onDestroy: called before the activity is demonstrate the use of FragmentManager. btnFirst=findViewById(R.id.btnFirst); Fragment2.java
destroyed. Here, we are creating two Fragments and one btnSecond=findViewById(R.id.btnSecond); public class Fragment2 extends Fragment {
Activity. Activity contains two buttons for btnFirst.setOnClickListener(new @Override
switching fragments i.e, if first Button is View.OnClickListener() { public View onCreateView(LayoutInflater inflater,
clicked Fragment1 is displayed and if second @Override ViewGroup
Button is clicked Fragment2 is displayed on public void onClick(View view) { container, Bundle savedInstanceState) {
screen. So, let’s begin by creating two Fragment fragment=new Fragment1(); // Inflate the layout for this fragment
fragments. FragmentManager manager = View view= inflater.inflate(R.layout.fragment2,
fragment1.xml getFragmentManager(); container,
<?xml version="1.0" encoding="utf-8"?> FragmentTransaction transaction = false);
<LinearLayout manager.beginTransaction(); return view;
xmlns:android="http://schemas.android.com/ap transaction.replace(R.id.myfragment, fragment); }}
k/res/android" transaction.commit(); Now we are going to add these fragments to
android:orientation="vertical" } Activity.
android:background="#AEB6BF" }); first_activity.xml
android:layout_width="match_parent" btnSecond.setOnClickListener(new <?xml version="1.0" encoding="utf-8"?>
android:layout_height="match_parent"> View.OnClickListener() { <LinearLayout
Following example will demonstrate <TextView @Override xmlns:android="http://schemas.android.com/ap
android:layout_width="wrap_content" public void onClick(View view) { k/res/android"
lifecycle of android:
android:layout_height="wrap_content" Fragment fragment=new Fragment2(); android:layout_width="match_parent"
import
android:text="I am inside Fragment 1" FragmentManager manager = android:orientation="vertical"
android.support.v7.app.AppCompatActivity;
android:layout_gravity="center" getFragmentManager(); android:weightSum="2"
import android.os.Bundle;
android:textSize="20sp" FragmentTransaction transaction = android:layout_height="match_parent">
import android.util.Log;
android:layout_marginTop="20sp" manager.beginTransaction(); <fragment
public class MainActivity extends
android:textStyle="bold" /> transaction.replace(R.id.myfragment, fragment); android:name="com.example.raazu.myapplicatio
AppCompatActivity {
</LinearLayout> transaction.commit(); n.Fragment1"
@Override
fragment2.xml }}); android:id="@+id/fragment1"
protected void onCreate(Bundle
<?xml version="1.0" encoding="utf-8"?> } android:layout_weight="1"
savedInstanceState) {
<LinearLayout >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> android:layout_width="match_parent"
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); xmlns:android="http://schemas.android.com/ap What do you mean by fragment? Explain android:layout_height="match_parent" />
//displaying message in Log k/res/android" lifecycle of fragment in detail. <fragment
Log.d("Lifecycle Test", "Activity Created"); android:orientation="vertical" A Fragment represents a behaviour or a android:name="com.example.raazu.myapplicatio
} android:background="#D0ECE7" portion of user interface in FragmentActivity. n.Fragment2"
@Override android:layout_width="match_parent" You can combine multiple fragments in a android:id="@+id/fragment2"
protected void onStart() android:layout_height="match_parent"> single activity to build a multi-pane UI and android:layout_weight="1"
{ <TextView android:layout_width="match_parent"
reuse a fragment in multiple activities. You
super.onStart(); android:layout_width="wrap_content" android:layout_height="match_parent" />
can think of a fragment as a modular section
Log.d("Lifecycle Test", "Activity Started"); android:layout_height="wrap_content" </LinearLayout>
of an activity, which has its own lifecycle,
FirstActivity.java false); return super.onOptionsItemSelected(item);
public class FirstActivity extends Activity { return view; }}}
@Override }} first_activity.xml
protected void onCreate(Bundle Fragment2.java <?xml version="1.0" encoding="utf-8"?>
savedInstanceState) { public class Fragment2 extends Fragment { <RelativeLayout
super.onCreate(savedInstanceState); xmlns:android="http://schemas.android.com/ap
@Override
setContentView(R.layout.first_activity); k/res/android"
public View onCreateView(LayoutInflater
}} android:layout_width="match_parent"
inflater, ViewGroup
There are 12 lifecycle methodsfor fragment. android:layout_height="match_parent">
container, Bundle savedInstanceState) { <TextView
It is shown below:
// Inflate the layout for this fragment android:layout_width="wrap_content"
View view= android:layout_height="wrap_content"
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> inflater.inflate(R.layout.fragment2, container, android:text="Hello World !"
Creating a UI Fragment with example false); android:textSize="20sp"
Fragment can be created in UI resource file as return view; android:layout_centerInParent="true" />
follows: }. } </RelativeLayout>
<fragment Above code produces following output:
android:name="com.example.raazu.myapplic >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ation.Fragment1" What do you mean by menu? Explain its
android:id="@+id/headlines_fragment" types.
android:layout_weight="1" Menus are a common user interface
android:layout_width="0dp" component in many types of applications. To
android:layout_height="match_parent" /> provide a familiar and consistent user
experience, you can use the it to present user 2. Creating Context Menu
Creating a Fragment Class: To create a actions & other options in your activities. To provide a floating context menu:
fragment, extend the Fragment class, then Types of Menu 1. Register the View to which the context menu
override key lifecycle methods to insert your > Options Menu: The options menu is the should be associated by calling
app logic, similar to the way you would with primary collection of menu items for an registerForContextMenu() and pass it the View.
an Activity class. One difference when activity. It's where you should place actions 2. Implement the onCreateContextMenu()
creating a Fragment is that you must use the that have a global impact on the app, such as method in your Activity or Fragment.
onCreateView() callback to define the layout. 3. For event handling on click implement
"Search," "Compose email," and "Settings."
onContextItemSelected().
In fact, this is the only callback you need in Menu shown in above diagram is an example
FirstActivity.java
order to get a fragment running. For of options menu. public class FirstActivity extends
example, here's a simple fragment that > Context Menu: Android context menu AppCompatActivity {
specifies its own layout: appears when user press long clicks on the Button btnClick;
Method. || description public class Fragment1 extends Fragment { element. It is also known as floating menu. It @Override
* onAttach(Activity) -> it is called only once @Override affects the selected content while doing protected void onCreate(Bundle
when it is attached with public View onCreateView(LayoutInflater action on it. It doesn't support item shortcuts savedInstanceState) {
* onCreate(Bundle) ->It is used to initialize inflater, ViewGroup container,Bundle and icons. super.onCreate(savedInstanceState);
the fragment. savedInstanceState) { >Popup Menu: A popup menu displays a list setContentView(R.layout.first_activity);
* onCreateView(LayoutInflater, ViewGroup, // Inflate the layout for this fragment of items in a vertical list that's anchored to btnClick=findViewById(R.id.btnClick);
Bundle) -> creates and returns view return inflater.inflate(R.layout.article_view, the view that invoked the menu. It's good for //registering view for context menu
hierarchy. container, providing an overflow of actions that relate registerForContextMenu(btnClick);
* onActivityCreated(Bundle) -> It is invoked false); }
to specific content or to provide options for a
after the completion of onCreate() Method @Override
}} second part of a command. Actions in a
* onViewStateRestored(Bundle) -> It provides public void onCreateContextMenu(ContextMenu
Example of Fragment popup menu should not directly affect the
information to the fragment that all the menu, View v,
Following example creates two fragments corresponding content—that's what ContextMenu.ContextMenuInfo menuInfo) {
saved state of fragment view hierarchy has named as Fragment1 and Fragment2. After contextual actions are for. Rather, the popup super.onCreateContextMenu(menu, v,
been restored. creating fragments, we will add these two menu is for extended actions that relate to menuInfo);
* onStart() -> makes the fragment visible. fragments in activity named as FirstActivity regions of content in your activity. MenuInflater inflater = getMenuInflater();
* onDestroyView() -> allows the fragment to and display them. Example: mymenu.xml inflater.inflate(R.menu.mymenu, menu);
clean up resources. fragment1.xml <?xml version="1.0" encoding="utf-8"?> }
* onDestroy() -> allows the fragment to do <?xml version="1.0" encoding="utf-8"?> <menu @Override
final clean up of fragment state. <LinearLayout xmlns:android="http://schemas.android.com/ap public boolean
* onDetach() -> It is called immediately prior xmlns:android="http://schemas.android.com/ k/res/android" onContextItemSelected(MenuItem item) {
to the fragment no longer being associated apk/res/android" xmlns:app="http://schemas.android.com/apk/re switch (item.getItemId()) {
with its activity. android:orientation="vertical" s-auto"> case R.id.item1: return true; //your stuffs
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <item android:id="@+id/item1" case R.id.item2: return true;
android:background="#AEB6BF"
The Need for UI Flexibility android:title="Item 1"/> //your stuffs
android:layout_width="match_parent"
Android introduced fragments in Android 3.0 <item android:id="@+id/item2" default: return
android:layout_height="match_parent"> android:title="Item 2"/> super.onContextItemSelected(item);
(API level 11), primarily to support more <TextView <item android:id="@+id/item3" }}}
dynamic and flexible UI designs on large android:layout_width="wrap_content" android:title="Item 3" first_activity.xml
screens, such as tablets. Because a tablet's android:layout_height="wrap_content" app:showAsAction="withText"/> <?xml version="1.0" encoding="utf-8"?>
screen is much larger than that of a handset, android:text="I am inside Fragment 1" </menu> <RelativeLayout
there's more room to combine and android:layout_gravity="center" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> xmlns:android="http://schemas.android.com/ap
interchange UI components. Fragments allow android:textSize="20sp" Types of menu demonstration: k/res/android"
such designs without the need for you to android:layout_marginTop="20sp" 1. Creating Options Menu android:layout_width="match_parent"
manage complex changes to the view android:textStyle="bold" We can create options menu by overriding android:layout_height="match_parent">
hierarchy. By dividing the layout of an activity </linearlayout> onCreateOptionsMenu() method. For <Button
into fragments, you become able to modify android:layout_width="wrap_content"
fragment2.xml handling clicks we must override
the activity's appearance at runtime and android:layout_height="wrap_content"
<?xml version="1.0" encoding="utf-8"?> onOptionsItemSelected() method. It is shown
preserve those changes in a back stack that's android:text="Show context menu"
<LinearLayout by the following example.
managed by the activity. android:layout_centerHorizontal="true"
xmlns:android="http://schemas.android.com/ FirstActivity.java android:layout_marginTop="20sp"
You should design each fragment as a apk/res/android" public class FirstActivity extends android:id="@+id/btnClick"
modular and reusable activity component. android:orientation="vertical" AppCompatActivity { android:textSize="20sp" />
That is, because each fragment defines its android:background="#D0ECE7" @Override </RelativeLayout>
own layout and its own behavior with its own android:layout_width="match_parent" protected void onCreate(Bundle
Above code produces following output:
lifecycle callbacks, you can include one android:layout_height="match_parent"> savedInstanceState) {
fragment in multiple activities, so you should super.onCreate(savedInstanceState);
<TextView
design for reuse and avoid directly setContentView(R.layout.first_activity);
android:layout_width="wrap_content"
manipulating one fragment from another }
android:layout_height="wrap_content" //adding options menu
fragment. This is especially important android:text="I am inside Fragment 2" @Override
because a modular fragment allows you to android:layout_gravity="center" public boolean onCreateOptionsMenu(Menu
change your fragment combinations for android:textSize="20sp" menu) {
different screen sizes. When designing your android:layout_marginTop="20sp" 3. Creating Popup Menu
MenuInflater inflater = getMenuInflater();
application to support both tablets and android:textStyle="bold" /> inflater.inflate(R.menu.mymenu, menu);
If you define your menu in XML, here's how
handsets, you can reuse your fragments in </LinearLayout> return true; you can show the popup menu:
different layout configurations to optimize Fragment1.java } • Instantiate a PopupMenu with its
the user experience based on the available public class Fragment1 extends Fragment { //handling clicks constructor, which takes the current
screen space. For example, on a handset, it @Override @Override application
might be necessary to separate fragments to public View onCreateView(LayoutInflater public boolean onOptionsItemSelected(MenuItem Context and the View to which the menu
provide a single-pane UI when more than one item) { should be anchored.
inflater, ViewGroup container, Bundle
cannot fit within the same activity. // Handle item selection • Use MenuInflater to inflate your menu
savedInstanceState) {
switch (item.getItemId()) { resource into the Menu object returned by
// Inflate the layout for this fragment case R.id.item1: return true; //your stuffs
View view= PopupMenu.getMenu().
case R.id.item2: return true; //your stuffs • Call PopupMenu.show().
inflater.inflate(R.layout.fragment1, container, default:
To perform an action when the user selects a android:id="@+id/edtFirst" /> relational database, okay and the most
menu item, you must implement the <EditText important feature about SQLite database is
PopupMenu.OnMenuItemClickListener android:layout_width="match_parent" it’s a local database so it doesn’t require any
interface and register it with your android:layout_height="wrap_content" server or any ODBC or JDBC query or
} android:hint="Enter second number"
PopupMenu by calling >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> connection for its functionality.
android:inputType="number"
setOnMenuItemclickListener(). When the Building an Alert Dialog It's just, You can say it saves the data in word
android:id="@+id/edtSecond" />
user selects an item, the system calls the There are three regions of an alert dialog: text file and saved locally on you can say
<Button
onMenuItemClick() callback in your interface. > Title: This is optional and should be used android:layout_width="wrap_content"
mobile device or tablet or whatever Android
FirstActivity.java only when the content area is occupied by a android:layout_height="wrap_content" device you are using and Android comes with
public class FirstActivity extends Activity android:layout_gravity="center" the built-in SQLite database implementation.
detailed message, a list, or custom layout. If
implements android:text="Caluclate" So you don’t need to install any extra libraries
you need to state a simple message or
PopupMenu.OnMenuItemClickListener{ android:id="@+id/btnCalculate"/> to use SQLite with Android
@Override
question (such as the dialog in figure 1), you
don't need a title. <TextView To create or update a database in your
protected void onCreate(Bundle android:layout_width="wrap_content" Android Application you just need to create a
savedInstanceState) { > Content area: This can display a message, a
android:layout_height="wrap_content" subclass of the SQLiteOpenHelper class. In
super.onCreate(savedInstanceState); list, or other custom layout.
android:text="Result:" the constructor of your subclass you call the
setContentView(R.layout.first_activity); > Action buttons:There should be no more android:textSize="20sp"
} than three action buttons in a dialog. super() method of SQLiteOpenHelper.
android:layout_gravity="center"
//showing popup menu FirstActivity.java android:layout_marginTop="20dp"
public void showMenu(View v) { public class FirstActivity extends Activity{ Please follow the steps below in order to
android:id="@+id/txtResult" />
PopupMenu popup = new PopupMenu(this, v); Button btnClick; create database tables:
</LinearLayout>
// This activity implements @Override first_activity.xml Step 1) So just open your Android studio, we
OnMenuItemClickListener protected void onCreate(Bundle <?xml version="1.0" encoding="utf-8"?> are going to start a new Android Application
popup.setOnMenuItemClickListener(this); savedInstanceState) { <RelativeLayout and we will name our application as SQLite
popup.inflate(R.menu.mymenu); super.onCreate(savedInstanceState); xmlns:android="http://schemas.android.com/ap app for example and then click next or select
popup.show(); setContentView(R.layout.first_activity); k/res/android" you minimum sdk. Click next and select a
} btnClick=findViewById(R.id.btnClick); android:layout_width="match_parent" blank activity next, and leave main activity as
//handling clicks btnClick.setOnClickListener(new android:layout_height="match_parent"> default and click finish.
@Override View.OnClickListener() { <Button Step 2) Now once your basic app is created,
public boolean onMenuItemClick(MenuItem @Override android:layout_width="wrap_content" what we’re going to do is we’re going to
item) { public void onClick(View view) { android:layout_height="wrap_content"
switch (item.getItemId()) { showDialog(); } create a class for handling the SQLite
android:text="Show Dialog" database. So go to your app folder and in the
case R.id.item1: return true; //your stuff }); } android:layout_centerHorizontal="true"
case R.id.item2: return true; // your stuffs public void showDialog(){ app folder go to your java folder and inside
android:layout_marginTop="20sp"
default: return false; AlertDialog.Builder builder = new here go to the package in which your main
android:id="@+id/btnClick"
}}} AlertDialog.Builder(FirstActivity.this); android:textSize="20sp" /> activity and right click the package and we’re
first_activity.xml builder.setTitle("Exit App"); </RelativeLayout> going to create a new java class.
<?xml version="1.0" encoding="utf-8"?> builder.setMessage("Do you want to exit App?"); FirstActivity.java Step 3) Now below is a basic blank class and
<RelativeLayout builder.setCancelable(true); public class FirstActivity extends Activity{ in here we want to create or extend this class
xmlns:android="http://schemas.android.com/ap builder.setPositiveButton( EditText edtFirst,edtSecond; using our SQLiteOpenHelper, so just write
k/res/android" "Yes", Button btnClick,btnCalculate; extend SQLiteOpenHelper.
android:layout_width="match_parent" new DialogInterface.OnClickListener() { TextView txtResult; Step 4) It might show some error because we
android:layout_height="match_parent"> public void onClick(DialogInterface dialog, int id) @Override haven’t imported the classes related to this
<Button { //your stuffs. } protected void onCreate(Bundle SQLite open helper so just click Alt+Enter,
android:layout_width="wrap_content" }); savedInstanceState) {
android:layout_height="wrap_content" builder.setNegativeButton( and just click the button called import class
super.onCreate(savedInstanceState); and its going to import this class okay.
android:text="Show popup menu" "No", setContentView(R.layout.first_activity);
android:layout_centerHorizontal="true" new DialogInterface.OnClickListener() { Step 5) Still it might show you some error
btnClick=findViewById(R.id.btnClick);
android:layout_marginTop="20sp" public void onClick(DialogInterface dialog, int id) because we need to create or implement
btnClick.setOnClickListener(new
android:onClick="showMenu" { dialog.cancel(); } View.OnClickListener() {
some of the methods from it so you will be
android:textSize="20sp" /> }); @Override able to see a small bulb there. You just need
</RelativeLayout> AlertDialog alert = builder.create(); public void onClick(View view) { to click this bulb and you just need to click
alert.show(); showDialog(); } implement methods and there are two
}} }); } methods related to this class which are
first_activity.xml public void showDialog(){ onCreate and onUpgrade. You are going to
<?xml version="1.0" encoding="utf-8"?> AlertDialog.Builder builder = new select both of them and click OK.
<RelativeLayout AlertDialog.Builder (FirstActivity.this); Step 6) And one more thing which is required
xmlns:android="http://schemas.android.com/ap builder.setTitle("Calculate Sum"); to be created is a default constructor so once
k/res/android" builder.setCancelable(true);
android:layout_width="match_parent" again click this red bulb here and just choose
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Inflate and set the layout for the dialog constructor matching super and we are going
Dialogs and its types: android:layout_height="match_parent"> // Pass null as the parent view because it’s going
<Button to select first of them and just create it.
A dialog are a small window that prompts the in the dialog layout
android:layout_width="wrap_content" Step 7) So we have successfully created our
user to decide or enter additional info. A LayoutInflater inflater = getLayoutInflater();
android:layout_height="wrap_content" View
database helper class which extends from
dialog does not fill the screen and is normally android:text="Show Dialog" SQLite open helper which is the main class for
used for modal events that require users to view=inflater.inflate(R.layout.custom_dialog,
android:layout_centerHorizontal="true" null); handling SQLite and we have some basic
take an action before they can proceed. android:layout_marginTop="20sp" methods and constructor.
builder.setView(view);
Following are the different types of dialogs: android:id="@+id/btnClick" //wiring up widgets Step 8) Now for creating the database, first of
> AlertDialog: A dialog that can show a title, android:textSize="20sp" /> all, we need a database name. Now let us see
edtFirst=view.findViewById(R.id.edtFirst);
up to three buttons, a list of selectable items, </RelativeLayout> edtSecond=view.findViewById(R.id.edtSecond); how we are going to create a database and
or a custom layout. btnCalculate=view.findViewById(R.id.btnCalculat what will be the name of our database and all
> DatePickerDialog or TimePickerDialog: A e); other stuff. So, for this, for example, to start
dialog with a pre-defined UI that allows the txtResult=view.findViewById(R.id.txtResult); with we are going to create a base like SQLite
user to select a date or time. btnCalculate.setOnClickListener(new database like shown in the images below and
> Custom Dialog: A custom dialog built by View.OnClickListener() {
the name of the database will be Student.db.
programmer as per the requirement. @Override
So our database name will be student.b and
Example: public void onClick(View view) {
int first,second, result;
its going to contain four columns:
public class MyActivity extends DialogFragment {
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> first=Integer.parseInt(edtFirst.getText().toString() 1) id of the student
@Override
Building Custom Dialog and Setting Dialog ); 2) name of the student
public Dialog onCreateDialog(Bundle
savedInstanceState) { Content: Calculate Sum second=Integer.parseInt(edtSecond.getText().toS 3) surname or last name of the student
// Use the Builder class for convenient dialog To demonstrate this topic, I am going to tring()); 4) marks scored by the student.
construction create a custom layout file for a dialog. This result=first+second; We are going to create a database or insert
AlertDialog.Builder builder = new file contains two EditText for inputting two txtResult.setText("Result="+result); } some data like this so id can be one two three
AlertDialog.Builder numbers and a Button. After clicking Button }); four for example, name, surname and marks
(getActivity()); sum of these numbers will be displayed in a AlertDialog alert = builder.create(); scored by the students.
builder.setMessage(“Do you want to Exit?”) alert.show(); Step 9) Now we will declare some variables
TextView. So, let’s begin by creating custom
.setPositiveButton(“YES”, new }} so that we can define the names of our
layout for dialog.
DialogInterface.OnClickListener() { Above code produces following output:
custom_dialog.xml database. So let's declare our variable which
public void onClick(DialogInterface dialog, int id) <?xml version="1.0" encoding="utf-8"?> we are going to assign the database name so
{ // your stuffs } <LinearLayout let's declare a variable name called
}) xmlns:android="http://schemas.android.com/ap database_name, we will assign the name of
.setNegativeButton(“NO”, new k/res/android" our database, for example, 'student.db'. And
DialogInterface.OnClickListener() { android:orientation="vertical"
public void onClick(DialogInterface dialog, int id) second what we are going to do is we are
android:layout_width="match_parent" going to declare our table name, so this will
{ // User cancelled the dialog } android:layout_height="match_parent">
}); >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> be a table name and let's give the name to
<EditText
// Create the AlertDialog object and return it Explain the process of creating database and our table as 'student_table' which will
android:layout_width="match_parent"
return builder.create(); android:layout_height="wrap_content" table using SQlite into android. resonate perfectly with our table.
android:hint="Enter first number" SQLite is database, which is an open source Step 10) And as we have discussed, this table
android:inputType="number" database so you can use it free, and its is going to contain 4 columns, one, two,
three, four and for simplicity lets keep all the protected void onResume() { mMap.moveCamera(CameraUpdateFactory.newLatL =====================================
variables as a string. First column name was super.onResume(); ng(location)); //Adding zoom effect API: API is an abbreviation for Application
mMap.animateCamera(CameraUpdateFactory.zoom
ID for the student and the column name is ID Log.d("Lifecycle","activityresume"); Programming Interface which is a collection
To(12.0f) );
right, so do something like this, col 1, col 1 is } } of communication protocols and subroutines
ID, similarly column 1, column 2, column 3 @Override } used by various programs to communicate
column 4. Column 2, column 3, column 4, protected void onPause() { between them. A programmer can make use
first column is ID, the second column is name, super.onPause(); >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> of various API tools to make its program
the third column is surname and fourth Log.d("Lifecycle","activitypause"); SQLIte and it’s features easier and simpler.
column is marks. So, these are the four } SQLite is an open-source relational database > Types of API’S
columns, this is our table name and this is our @Override i.e. used to perform database operations on There are various kinds of API’s available
database name. protected void onStop() { android devices such as storing, manipulating according to their uses and applications like
Step 11) Now in order to create our super.onStop(); or retrieving persistent data from the the Browser API which is created for the web
database, we are going to create our Log.d("Lifecycle","activitystop"); database. It is very lightweight database that browsers to abstract and to return the data
database in the constructor. So, we need to } comes with Android OS. It supports all the from surroundings or the Third-party API’s,
call a function which creates a database. So, @Override relational database features. In order to for which we have to get the codes from
for simplicity let's reduce our constructor protected void onDestroy() { access this database, you don't need to other sites on the web (e.g. Facebook,
which only takes this context and as you can super.onDestroy(); establish any kind of connections for it like Twitter).
see here this superclass, we can just give the Log.d("Lifecycle","activitydestroy"); JDBC, ODBC etc. There are three basic forms of API:
name of the database. Our database name is }} Features of SQLite: 1. Web APIs: A Web API also called as Web
this variable, pass it here. Thirds is factory, >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Following is a list of features which makes Services is an extensively used API over the
we are going to pass null here, and the Steps for Getting Google Maps API Key and SQLite popular among other lightweight web and can be easily accessed using the
version. For example, version is equal to 1. map program. databases: HTTP protocols. A Web API is an open source
Now whenever this constructor is called, your An API key is needed to access the Google 1. SQLite is totally free: SQLite is open-source. interface and can be used by a large number
database will be created. Maps servers. This key is free and you can So, no license is required to work with it. of clients through their phones,
Step 12) Now in order to create the table useit with any of your applications. If you 2.SQLite is server less: SQLite doesn't require tablets. or PC’s.
inside your database, we are going to create haven’t created project, you can follow the a different server process or system to 2. Local APIs: in this type of API, the
a table whenever the onCreate method of belowsteps to get started: operate. programmers get the local middleware
this class is called. So, you can see SQLite Step 1: Open Google developer console and 3.SQLite is very flexible: It facilitates you to services. TAPI (Telephony Application
database class is the argument inside sign in with your Gmail account: work on multiple databases on the same Programming Interface), .NET are common
onCreate. http:/console.developers.google.com/project session on the same time. examples of Local API’s.
Step 13) So we can just take the db which is Step 2: Now create new project. You can 4.Configuration Not Required: SQLite doesn't 3. Program APIs: It makes a remote program
the variable of SQLite database, so take this create new project by clicking on the Create require configuration. No setup or appears to be local by making use of RPC’s
instance db and call a method called. exacsql Project button and give name to your project. administration required. (Remote Procedural Calls). SOAP is a well-
and what it does is it executes whatever Step 3: Now click on APIs & Services and open 5. SQLite is a cross-platform DBMS: You don't known example of this type of API.
query you pass inside this method as an Dashboard from it. need a large range of different platforms like
argument. Step 4: Now click Enable APIS AND SERICES. Windows, Mac OS, Linux, and Unix. It can also Few other types of APIs:
Step 14) It takes the string variable or the Step 5: Now search for Google Map Android be used on a lot of embedded operating • SOAP (SIMPLE OBJECT ACCESS PROTOCOL):
string query so here you can prepare the API and enable it. systems like Symbian, and Windows CE. It defines messages in XML format
creatable query and whenever it called, its Step 6: Now refresh page and go to 6. Storing data is easy: SQLite provides an used by web applications to communicate
going to execute the query and is going to Credentials. efficient way to store data. with each other.
create this table. So, lets write our query, for Step 7: Now click on Create credentials and Advantages and Disadvantages of SQLite • REST (Representational State Transfer): It
example create the table name, so create choose API key. It will create API key to Following are the advantages of using SQLite: makes use of HTTP to GET, POST, PUT,
table and the table name in our case is this integrate maps in your application. 1. Lightweight: SQLite is a very light weighted or DELETE data. It is basically used to take
one so you can use his concatenation Step 8: Now API your API key will be database so, it is easy to use it as an advantage of the existing data.
operator to concatenate this and then inside generated. Copy it and save it somewhere as embedded software with devices like • JSON-RPC: It use JSON for data transfer and
your bracket your column name comes right. televisions, Mobile phones, cameras, home is a light-weight remote procedural call
So first column name is ID or you can just we will need it when implementing Google electronic devices, etc. defining few data structure types.
take these name or column 1, column 2, Map in our Android project. 2. Better Performance: Reading and writing • XML-RPC: It is based on XML and uses HTTP
column 3 and column 4 . Step 1: Add following permission in your manifest operations are very fast for SQLite database. for data transfer. This API is widely used
So just write create table and your table file. <uses-permission to exchange information between two or
It is almost 35% faster than File system. It
android:name="android.permission.ACCESS_FINE_LO
name and then in the brackets comes the ID only loads the data which is needed, rather more networks.
CATION"/>
which is the first column name and then Step 2: Add your generated API Key in your manifest than reading the entire file and hold it in
comes he attributes of this column, so it’ll be file inside application tag as follows. memory. If you edit small parts, it only Advantages and Disadvantages of API
integer and its going to be my primary key. <meta-data overwrites the parts of the file which was Following are the advantages of APIs:
Primary key means the unique key which you android:name="com.google.android.geo.API_KEY" changed. • Efficiency: API produces efficient, quicker
will be able to identify the rows, okay. And android:value="AIzaSyCWIdlyqlFhC7lOthG164H42he and more reliable results than the
3. No Installation Needed: SQLite is very easy
V1F7N3v0" />
then its going to auto increment. to learn. You don’t need to install and outputs produced by human beings in an
Step 3: Add following dependency in build.gradle file
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> dependencies { configure it. Just download SQLite libraries in organization.
Develop android application to illustrate implementation 'com.google.android.gms:play- your computer & it is ready for creating the • Flexible delivery of services: API provides
activity life cycle. services-maps:15.0.1' } database. fast and flexible delivery of services
<?xml version="1.0" encoding="utf-8"?> Step 4: Now create layout resource file to display 4. Reliable: It updates your content according to developer’s requirements.
<androidx.constraintlayout.widget.Constraint google map. map_activity.xml • Integration: The best feature of API is that it
continuously so, little or no work is lost in a
<?xml version="1.0" encoding="utf-8"?>
Layout case of power failure or crash. SQLite is less allows movement of data between
<RelativeLayout
xmlns:android="http://schemas.android.com/ xmlns:android="http://schemas.android.com/apk/res bugs prone rather than custom written file various sites and thus enhances integrated
apk/res/android" /android" android:layout_width="match_parent" I/O codes. SQLite queries are smaller than user experience.
xmlns:app="http://schemas.android.com/apk android:layout_height="match_parent" equivalent procedural codes so, chances of • Automation: As API makes use of robotic
/res-auto" xmlns:tools="http://schemas.android.com/tools"> bugs are minimal. computers rather than humans, it
xmlns:tools="http://schemas.android.com/to <fragment produces better and automated results.
5. Portable: SQLite is portable across all 32-
xmlns:android="http://schemas.android.com/apk/res
ols" bit and 64-bit operating systems and big- and • New functionality: While using API the
/android" android:id="@+id/map"
android:layout_width="match_parent" android:name="com.google.android.gms.maps.Supp little-endian architectures. Multiple processes developers find new tools and functionality
android:layout_height="match_parent" ortMapFragment" tools:context=".MapsActivity" can be attached with same application file for API exchanges.
tools:context=".lab3a"> android:layout_width="match_parent" and can read and write without interfering disadvantages of APIs:
</androidx.constraintlayout.widget.Constrain android:layout_height="match_parent" /> each other. It can be used with all • Cost: Developing and implementing API is
tLayout> </RelativeLayout> costly at times and requires high
programming languages without any
Step 5: Now finally create an Activity by
//lab3a.java compatibility issue. maintenance and support from developers.
implementing OnMapReadyCallback interface.
package com.example.lab3; MapsActivity.java 6. Accessible: SQLite database is accessible • Security issues: Using API adds another
import public class MapsActivity extends AppCompatActivity through a wide variety of third-party tools. layer of surface which is then prone to
androidx.appcompat.app.AppCompatActivity; implement OnMapReadyCallback { SQLite database's content is more likely to be attacks, and hence the security risk problem
import android.os.Bundle; GoogleMap mMap; recoverable if it has been lost. Data lives is common in API’s.
import android.util.Log; @Override
longer than code.
protected void onCreate(Bundle b){
public class lab3a extends AppCompatActivity 7. Reduce Cost and Complexity: It reduces =====================================
super.onCreate(b);
{ setContentView(R.layout.map_activity); application cost because content can be JSON: The JSON syntax is derived from
@Override SupportMapFragment mapFragment = accessed and updated using concise SQL JavaScript object notation syntax, but the
protected void onCreate(Bundle (SupportMapFragment).getSupportFragmentManage queries instead of lengthy and error-prone JSON format is text only. Code for reading
savedInstanceState) { r().findFragmentB yId(R.id.map); procedural queries. SQLite can be easily and generating JSON data can be written in
super.onCreate(savedInstanceState); mapFragment.getMapAsync(this); any programming language
extended in in future releases just by adding
}
setContentView(R.layout.activity_lab3a); new tables and/or columns. It also preserves Encoding JSON Data in PHP In PHP the
@Override
Log.d("Lifecycle","activitycreated"); public void onMapReady(GoogleMap googleMap) { the backwards compatibility. json_encode() function is used to encode a
} mMap = googleMap; disadvantages of using SQLite: value to JSON format. The value being
@Override // Adding latitude and longitude 1. SQLite is used to handle low to medium encoded can be any PHP data type except a
protected void onStart() { LatLng location = new LatLng(26.6096, 87.9891); traffic HTTP requests. resource, like a database or file handle.
super.onStart(); //Adding red marker to point location Introduction to iOS and iOS Programming
2. Database size is restricted to 2GB in most
mMap.addMarker(new
Log.d("Lifecycle","activitystarted"); cases. iOS (formerly iPhone OS) is a mobile
MarkerOptions().position(location). title("Marker in
} Birtamode")); operating system created and developed by
@Override //Moving camera to desired location Apple Inc. exclusively for its hardware. It is
the operating system that presently powers developing iPhone prior to its unveiling in View that represents each data entry. <RelativeLayout
many of the company's mobile devices, 2007, Apple's then-CEO Steve Jobs did not xmlns:android="http://schemas.android.com/ap
including the iPhone, and iPod Touch; it also intend to let third-party developers build k/res/android"
powered the iPad prior to the introduction of native apps for iOS, instead directing them to android:layout_width="match_parent"
iPadOS in 2019. It is the second most popular make web applications for the Safari web android:layout_height="match_parent">
<ListView
mobile operating system globally after browser.
android:layout_width="match_parent"
Android. its apple integrated development
android:id="@+id/mylist"
==================================== environment (IDE). The Xcode editor is the android:layout_height="match_parent" />
Introduction to Swift Language primary development tool for any type of Features of ListView: </RelativeLayout>
Swift is a new language that Apple introduced apple platforms like OSX Software’s, iPhones 1. It displays a vertically-scrollable collection customlist_items.xml
in 2014. It replaces Objective-C as the App, Mac, etc. of views, where each view is positioned <?xml version="1.0" encoding="utf-8"?>
recommended development language for iOS Hello World in ios immediately below the previous view in the <RelativeLayout
and Mac. Swift maintains the expressiveness import UIKit list. xmlns:android="http://schemas.android.com/ap
of Objective-C while introducing a syntax that class ViewController: UIViewController { 2. ListView uses Adapter classes which add k/res/android"
is safer, @IBOutlet var displayLabel: UILabel! the content from data source android:layout_width="match_parent"
succinct, and readable. It emphasizes type @IBAction func saySomethingTapped(_ (such as string array, array, database etc.) android:layout_height="match_parent">
safety and adds advanced features such as sender: UIButton) { <ImageView
3. ListView is a default scrollable which does
optionals, generics, and sophisticated displayLabel.text = "Hello World!" } android:layout_width="wrap_content"
not use another scroll view.
android:layout_height="wrap_content"
structures and enumerations. Most } 4. ListView is implemented by importing android:src="@drawable/ic_launcher"
importantly, >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> android.widget.ListView class. android:id="@+id/image" />
Swift allows the use of these new features What do you mean by view hierarchy? <TextView
while relying on the same tested, elegant iOS Explain with the help of suitable example. listview_example.xml android:layout_width="match_parent"
frameworks that developers have built upon In Android, View Hierarchy refers to the tree- <?xml version="1.0" encoding="utf-8"?> android:layout_height="wrap_content"
for years. like structure of views (UI components) that <RelativeLayout android:textSize="20sp"
Types in Swift are nested inside each other to build the user xmlns:android="http://schemas.android.com/ap android:id="@+id/title"
Swift types can be arranged into three basic interface (UI) of an app. The root is always a k/res/android" android:textStyle="bold"
groups: structures, classes, and ViewGroup. Children can be other views or android:layout_width="match_parent" android:layout_marginTop="10dp"
enumerations. viewgroups. Views are drawn on the screen android:layout_height="match_parent"> android:layout_toRightOf="@+id/image"
All three can have: in the order they appear in the XML layout. <ListView android:text="Title" />
android:layout_width="match_parent" <TextView
• properties – values associated with a type The hierarchy determines how views are
android:id="@+id/mylist" android:layout_width="match_parent"
• initializers – code that initializes an instance arranged, measured, and drawn. example
android:layout_height="match_parent" /> android:layout_height="wrap_content"
of a type <LinearLayout
</RelativeLayout>
xmlns:android="http://schemas.android.com/ap android:textSize="18sp"
• instance methods – functions specific to a listview_items.xml
k/res/android" android:id="@+id/description"
type that can be called on an instance of <?xml version="1.0" encoding="utf-8"?> android:layout_below="@+id/title"
that type android:layout_width="match_parent"
<RelativeLayout android:text="This is description"
• class or static methods – functions specific android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/ap android:layout_toRightOf="@+id/image” />
android:orientation="vertical">
to a type that can be called on the type k/res/android" </RelativeLayout>
<TextView
Itself android:layout_width="match_parent"
android:id="@+id/textView"
Built-in Data Types android:layout_height="match_parent"> MyListAdapter.java
android:layout_width="wrap_content"
The following types of basic data types are <TextView public class MyListAdapter extends
android:layout_height="wrap_content"
most frequently when declaring variables − android:layout_width="match_parent" ArrayAdapter<String> {
android:text="Hello World" />
• Int or UInt − This is used for whole android:layout_height="wrap_content" Activity context;
<Button
android:textSize="20sp" String[] title;
numbers. More specifically, you can use android:id="@+id/button"
android:id="@+id/text" String[] description;
Int32, Int64 to define 32 or 64-bit signed android:layout_width="wrap_content"
android:textStyle="bold" int[] image;
integer, whereas UInt32 or UInt64 to define android:layout_height="wrap_content"
android:layout_margin="10dp" />
android:text="Click Me" /> public MyListAdapter(Activity context, String[]
32 or 64-bit unsigned integer variables. For </RelativeLayout>
</LinearLayout> title, String[] description, int[] image) {
example, 42 and -23. Now we are creating a java file to for
• Float − This is used to represent a 32-bit * LinearLayout is the root view.
displaying String array in a ListView. //ArrayAdapter needs String so we are supplying
floating-point number and numbers with * TextView and Button are child views.
ListViewExample.java title
smaller decimal points. For example, 3.14159, public class ListViewExample extends super(context, R.layout.customlist_items,title);
0.1, and -273.158. Explain the procedure for creating an AVD. AppCompatActivity { this.context=context;
• Double − This is used to represent a 64-bit Also write steps for running application on ListView listView; this.title=title;
floating-point number and used when Emulator. @Override this.description=description;
floating-point values must be very large. For An AVD is an emulator configuration that lets protected void onCreate(Bundle b){ this.image=image;
example, 3.14159, 0.1, and -273.158. you model a real Android device on your super.onCreate(b); }
• Bool − This represents a Boolean value computer. setContentView(R.layout.listview_example); public View getView(int position, View view,
which is either true or false. Steps to create an AVD: listView=findViewById(R.id.mylist); ViewGroup parent) { LayoutInflater
1. Open Android Studio. //creating string array inflater=context.getLayoutInflater();
• String − This is an ordered collection of
2. Go to Tools > Device Manager (or AVD String names[]= View
characters. For example, "Hello, World!"
Manager). {"Ram","Shyam","Hari","Sita","Gita","Rita"}; rowView=inflater.inflate(R.layout.customlist_ite
• Character − This is a single-character string ms,
3. Click on “Create Device”. //displaying list using ArrayAdapter
literal. For example, "C" ArrayAdapter<String> adapter=new null,true);
• Optional − This represents a variable that 4. Choose a device model (e.g., Pixel 4) →
ArrayAdapter<String>
can hold either a value or no value. Click Next. //wiring widgets
(this,R.layout.listview_items,R.id.text,names);
• Tuples − This is used to group multiple 5. Select a System Image (e.g., Android 12) → listView.setAdapter(adapter); TextView txtTitle = (TextView)
values in single Compound Value. Click Next. } rowView.findViewById(R.id.title);
6. Set AVD Name, Orientation, and other } ImageView imageView = (ImageView)
Storyboard and View Controllers options. Following code can be used for handling rowView.findViewById
Storyboards are an exciting feature first 7. Click on Finish to create the AVD. clicks in a ListView: (R.id.image);
introduced in iOS 5, which save time building Now the emulator is ready to use. listView.setOnItemClickListener(new TextView txtDescription = (TextView)
user interfaces for your apps. Storyboards Steps to Run Application on Emulator: AdapterView.OnItemClickListener() { rowView.findViewById
1. Start Android Studio. @Override (R.id.description);
allow you to prototype and design multiple
2.. Open your Android project. public void onItemClick(AdapterView<?> txtTitle.setText(title[position]);
view controller views within one file, and also
3.. Click on the "Run" button on the toolbar. adapterView, View view, int position, long l) { imageView.setImageResource(image[position]);
let you create transitions between view txtDescription.setText(description[position]);
4. Choose your created AVD from the list of //retrieving value
controllers. To demonstrate storyboard now return rowView;
available devices. String value=adapter.getItem(position);
I am going to create a storyboard containing };
5.. Android Studio will launch the emulator //displaying in Toast
a Tab and Toast.makeText(getApplicationContext(),value,To }
multiple view controllers linking with the Tab. and install the app. CustomListExample.java
ast.LENGTH_SHORT).
So, let’s begin by creating a project with 6. Your app will start running on the virtual public class CustomListExample extends
show();
following information: device. } AppCompatActivity {
* Product Name: MyExample. 1.Efficiency 2.Flexible delivery service }); ListView listView;
* Organization Name: Fill this in however you 3.Integration 4.Automation 5.New @Override
like. functionality Creating Custom ListView protected void onCreate(Bundle b){
* Organization Identifier: The identifier you > Disadvantages: After creating simple ListView, android also super.onCreate(b);
1.Cost 2.Security Issues provides facilities to customize our ListView. setContentView(R.layout.custom_list);
use for your apps.
Like simple ListView, custom ListView also uses listView=findViewById(R.id.mylist);
* Language: Swift.
Adapter classes which added the content // creating arrays
* User Interface: Storyboard. ListView: Android ListView is a view which String[] title={
from data source (such as string array, array,
* Make sure you’ve unchecked the Use Core groups several items and display them in "Title 1", "Title 2",
database etc). Adapter bridges data between
Data, Include Unit Tests and UI Tests options. vertical scrollable list. The list items are "Title 3", "Title 4"};
an AdapterViews and other Views.
Open Main.storyboard in the Project automatically inserted to the list using an To display a more custom view for each item in String[] description={
navigator to view it in the Interface Builder your dataset, extend ArrayAdapter and "This is description 1",
Adapter that pulls content from a source such
editor: as an array or database. The ListView and create and configure the view for each data item "This is description 2",
===================================== in getView(...). Example is shown below: "This is description 3",
GridView are subclasses of AdapterView and
iOS Platform: The iOS SDK (Software "This is description 4"
they can be populated by binding them to an
Development Kit) allows for the development custom_list.xml };
Adapter, which retrieves data from an int[] image={
of mobile apps on iOS. While originally <?xml version="1.0" encoding="utf-8"?>
external source and creates a //Replace with different images
R.drawable.ic_launcher, android:layout_width="match_parent" //passing arrays to constructor of MyListAdapter int[] image={
R.drawable.ic_launcher, android:layout_height="match_parent"> MyGridAdapter adapter=new MyGridAdapter R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher, <GridView (this,title,description,image); R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher android:layout_width="match_parent" gridView.setAdapter(adapter); R.drawable.ic_launcher
}; android:id="@+id/mygrid" } };
//setting layout manager
//passing arrays to constructor of MyListAdapter android:numColumns="2" ===================================== layoutManager=new LinearLayoutManager(this);
MyListAdapter adapter=new MyListAdapter android:layout_height="match_parent" /> RecyclerView recyclerView.setLayoutManager(layoutManager);
(this,title,description,image); </RelativeLayout> The RecyclerView widget is a more advanced //passing array to Adapter class
listView.setAdapter(adapter); customgrid_items.xml and flexible version of ListView. If your app adapter=new
} <?xml version="1.0" encoding="utf-8"?> needs to display a scrolling list of elements RecyclerViewAdapter(this,name,address,image);
} <RelativeLayout recyclerView.setAdapter(adapter);
based on large data sets (or data that
===================================== xmlns:android="http://schemas.android.com/ap }}
frequently changes), you should use RecyclerViewAdapter.java
GridView k/res/android"
android:layout_width="match_parent"
RecyclerView. RecyclerView is mostly used to public class RecyclerViewAdapter extends
Android GridView shows items in two-
android:layout_height="match_parent"> design the user interface with the fine-grain RecyclerView.Adapter<RecyclerViewAdapter.ViewHol
dimensional scrolling grid (rows & columns).
<ImageView control over the lists and grids of android der> {
The items in the grid come from the Activity context;
android:layout_width="wrap_content" application. It was introduced in
ListAdapter associated with this view. int[] image;
android:layout_height="wrap_content" Marshmallow.
String[] name;
android:src="@drawable/ic_launcher" Features of RecyclerView String[] address;
android:layout_centerHorizontal="true" 1.RecyclerView widget is a more advanced public RecyclerViewAdapter(Activity context,String[]
android:id="@+id/image" /> and flexible version of ListView. So, we 2.can name, String[] address, int[] image){
<TextView use RecyclerView to display large dataset. this.name=name;
android:layout_width="wrap_content" 3.It contains integrated animations for this.address=address;
android:layout_height="wrap_content" adding, updating and removing items. this.image=image;
Features of GridView android:textSize="20sp" this.context=context;
4.RecyclerView enforces the recycling of
1.GridView displays items in two-dimensional android:id="@+id/title" }
views by using the ViewHolder pattern. @Override
scrolling grid. android:textStyle="bold"
5.RecyclerView supports both grids and lists. public ViewHolder onCreateViewHolder(ViewGroup
2.GridView uses Adapter classes which add android:layout_centerHorizontal="true"
android:layout_below="@+id/image" 6.It supports vertical and horizontal scrolling. parent, int viewType) {
the content from data source (such as string LayoutInflater layoutInflater = LayoutInflater.from
array, array, database etc.) android:text="Title" />
(context);
3.GridView is a default scrollable which does <TextView View listItem= layoutInflater.inflate
not use other scroll view. android:layout_width="wrap_content" (R.layout.recyclerview_items, parent, false);
android:layout_height="wrap_content" ViewHolder viewHolder = new ViewHolder(listItem);
4.GridView is implemented by importing
android:textSize="18sp" return viewHolder;
android.widget.GridView class.
android:id="@+id/description" }
gridview_example.xml android:text="This is description" @Override
gridview_example.xml android:layout_centerHorizontal="true" public void onBindViewHolder(ViewHolder holder, int
<?xml version="1.0" encoding="utf-8"?> android:layout_below="@+id/title" /> position){
<RelativeLayout </RelativeLayout> holder.txtName.setText(name[position]);
xmlns:android="http://schemas.android.com/ap holder.txtAddress.setText(address[position]);
k/res/android" MyGridAdapter.java recyclerview_example.xml holder.imageView.setImageResource(image[position]
android:layout_width="match_parent" <?xml version="1.0" encoding="utf-8"?> );
public class MyGridAdapter extends
android:layout_height="match_parent"> <RelativeLayout }
ArrayAdapter<String> { @Override
<GridView Activity context; xmlns:android="http://schemas.android.com/apk/res
android:layout_width="match_parent" /android" public int getItemCount() {
String[] title; return name.length;
android:id="@+id/mygrid" android:layout_width="match_parent"
String[] description; android:layout_height="match_parent"> }
android:numColumns="3" int[] image; <android.support.v7.widget.RecyclerView public static class ViewHolder extends
android:layout_height="match_parent" /> public MyGridAdapter(Activity context, String[] RecyclerView.ViewHolder{
android:id="@+id/recyclerview"
</RelativeLayout> title, String[] description, int[] image) { TextView txtName,txtAddress;
android:scrollbars="vertical"
gridview_items.xml //ArrayAdapter needs String so we are supplying ImageView imageView;
android:layout_width="match_parent"
<?xml version="1.0" encoding="utf-8"?> title android:layout_height="match_parent"/> public ViewHolder(View itemView) {
<RelativeLayout super(context, R.layout.customgrid_items,title); </RelativeLayout> super(itemView);
xmlns:android="http://schemas.android.com/ap this.context=context; Now we are creating layout file for placing txtName = itemView.findViewById(R.id.txtName);
k/res/android" RecyclerView items. txtAddress = itemView.findViewById(R.id.txtAddress);
this.title=title;
android:layout_width="match_parent" recyclerview_items.xml imageView = itemView.findViewById(R.id.image);
this.description=description; }}}
android:layout_height="match_parent"> this.image=image; <?xml version="1.0" encoding="utf-8"?>
<TextView <RelativeLayout =====================================
}
android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res Displaying Data Using MVC Pattern in
public View getView(int position, View view, /android"
android:layout_height="wrap_content" ViewGroup parent) {
RecyclerView
android:textSize="20sp" android:layout_width="match_parent"
LayoutInflater For this purpose, we need a model where
android:layout_height="wrap_content">
android:id="@+id/text" inflater=context.getLayoutInflater(); data is to be stored. So, now I am going to
<ImageView
android:textStyle="bold" View create a model named as MyData.java which
android:layout_width="wrap_content"
android:layout_margin="10dp" /> rowView=inflater.inflate(R.layout.customgrid_ite android:layout_height="wrap_content" contains all required variables i.e., name,
</RelativeLayout> ms, null,true); android:src="@drawable/ic_launcher" address and image.
Now we are creating a java file to for displaying //wiring widgets android:id="@+id/image" /> MyData.java
String array in a GridView. TextView txtTitle = (TextView) <TextView public class MyData {
GridViewExample.java rowView.findViewById(R.id.title); android:layout_width="wrap_content" private String name;
public class GridViewExample extends ImageView imageView = (ImageView) android:layout_height="wrap_content"
private String address;
AppCompatActivity { android:textSize="20sp"
rowView.findViewById(R.id.image); private int image;
GridView gridView; android:id="@+id/txtName"
TextView txtDescription = (TextView) android:textStyle="bold"
public MyData(String name,String address,int
@Override rowView.findViewById(R.id.description); image){
protected void onCreate(Bundle b){ android:layout_toRightOf="@+id/image"
txtTitle.setText(title[position]); android:layout_marginTop="10dp" this.name=name;
super.onCreate(b); imageView.setImageResource(image[position]); this.address=address;
android:text="Name" />
setContentView(R.layout.gridview_example); txtDescription.setText(description[position]); this.image=image;
<TextView android:layout_width="wrap_content"
gridView =findViewById(R.id.mygrid); return rowView; android:layout_height="wrap_content" }
//creating string array }; android:textSize="18sp" public String getName(){
String names[]= } android:id="@+id/txtAddress" return name;
{"Ram","Shyam","Hari","Sita","Gita"}; CustomGridExample.java android:text="Address" }
//displaying list using ArrayAdapter public class CustomGridExample extends android:layout_toRightOf="@+id/image" public String getAddress(){
ArrayAdapter<String> adapter=new AppCompatActivity { android:layout_below="@+id/txtName" />
return address;
ArrayAdapter<String> </RelativeLayout>
GridView gridView; }
(this,R.layout.gridview_items,R.id.text,names); Now it’s time to create java files. Here we need to
@Override java classes one will be the Activity and public int getImage(){
gridView.setAdapter(adapter); protected void onCreate(Bundle b){ return image;
} another is needed for creating Adapter for
super.onCreate(b); RecycerView. }}
} setContentView(R.layout.custom_grid); RecyclerViewExample.java
RecyclerViewExample.java
Creating Custom GridView gridView =findViewById(R.id.mygrid); public class RecyclerViewExample extends
public class RecyclerViewExample extends
After creating simple GridView, android also // creating arrays AppCompatActivity { AppCompatActivity {
provides facilities to customize our GridView. String[] title={ RecyclerView recyclerView; RecyclerView recyclerView;
Like simple GridView, custom GridView also uses "Title 1", "Title 2", RecyclerView.Adapter adapter; RecyclerView.Adapter adapter;
Adapter classes which added the content "Title 3", "Title 4"}; RecyclerView.LayoutManager layoutManager; RecyclerView.LayoutManager layoutManager;
from data source (such as string array, array, String[] description={ @Override @Override
database etc). Adapter bridges data between "This is description 1",
protected void onCreate(Bundle b){
protected void onCreate(Bundle b){
an AdapterViews and other Views. super.onCreate(b);
"This is description 2", super.onCreate(b);
To display a more custom view for each item in setContentView(R.layout.recyclerview_example);
"This is description 3", recyclerView=findViewById(R.id.recyclerview); setContentView(R.layout.recyclerview_example);
your dataset, extend ArrayAdapter and "This is description 4" recyclerView=findViewById(R.id.recyclerview);
create and configure the view for each data item //creating array
}; String[] name={ //filling data in model
in getView(...). Example is shown below: int[] image={ ArrayList<MyData> data=new ArrayList<>();
"Ram","Shyam","Hari",
//Replace with different images "Gita","Sita" data.add(new
custom_grid.xml R.drawable.ic_launcher, }; MyData("Ram","Birtamode",R.drawable.ic_launc
<?xml version="1.0" encoding="utf-8"?> R.drawable.ic_launcher, String[] address={ her));
<RelativeLayout R.drawable.ic_launcher, "Birtamode","Kathmandu","Pokhara", data.add(new
xmlns:android="http://schemas.android.com/ap R.drawable.ic_launcher "Birtamode","Kathmandu" MyData("Shyam","Kathmandu",R.drawable.ic_la
k/res/android" }; }; uncher));
data.add(new android:layout_height="wrap_content" @Override result=first+second;
MyData("Hari","Pokhara",R.drawable.ic_launche android:text="Student Form" public void onClick(View view) { //displaying result in TextView
r)); android:textSize="20sp" //getting data from edit text txtResult.setText("Result="+result);
data.add(new android:layout_centerHorizontal="true" String id=edtId.getText().toString(); } }); } }
MyData("Gita","Birtamode",R.drawable.ic_launc android:layout_marginTop="10dp" String name=edtName.getText().toString();
her)); android:id="@+id/txtForm" /> //getting data from radio button
data.add(new <EditText String gender="";
MyData("Sita","Kathmandu",R.drawable.ic_laun android:layout_width="match_parent" if(radMale.isChecked())
cher)); android:layout_height="wrap_content" gender="Male";
//setting layout manager android:layout_below="@+id/txtForm" else
layoutManager=new LinearLayoutManager(this); android:layout_margin="5dp" gender="Female"; >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
recyclerView.setLayoutManager(layoutManager; android:hint="Enter Student Id" //getting data from spinner
Introduction to iOS and iOS Programming
//passing array to Adapter class android:id="@+id/edtId" /> String
iOS (formerly iPhone OS) is a mobile
adapter=new RecyclerViewAdapter(this,data); <EditText program=spProgram.getSelectedItem().toString()
recyclerView.setAdapter(adapter); android:layout_width="match_parent" ;
operating system created and developed by
}} android:layout_height="wrap_content" //displaying data in text view Apple Inc. exclusively for its hardware. It is
RecyclerViewAdapter.java android:layout_below="@+id/edtId" txtResult.setText("Student Id="+id+"\n"+"Student the operating system that presently powers
public class RecyclerViewAdapter extends android:layout_margin="5dp" Name=" many of the company's mobile devices,
RecyclerView.Adapter<RecyclerViewAdapter.Vie android:hint="Enter Student Name" +name+"\n"+"Gender="+gender+"\n"+"Program including the iPhone, and iPod Touch; it also
wHolder> { android:id="@+id/edtName" /> ="+program); } powered the iPad prior to the introduction of
Activity context; <TextView }); } } iPadOS in 2019. It is the second most popular
ArrayList<MyData> data; android:layout_width="wrap_content" Above code will produce following output: mobile operating system globally after
public RecyclerViewAdapter(Activity context, android:layout_height="wrap_content" Android.
ArrayList<MyData> data){ android:text="Gender:" iOS Platform: The iOS SDK (Software
this.context=context; android:textSize="18sp" Development Kit) allows for the development
this.data=data; android:id="@+id/txtGender"
of mobile apps on iOS. While originally
} android:layout_below="@+id/edtName"
developing iPhone prior to its unveiling in
@Override android:layout_marginLeft="10dp"
public ViewHolder android:layout_margin="5dp" />
2007, Apple's then-CEO Steve Jobs did not
onCreateViewHolder(ViewGroup parent, int <RadioGroup intend to let third-party developers build
viewType) { android:layout_width="match_parent" native apps for iOS, instead directing them to
LayoutInflater layoutInflater = android:layout_height="wrap_content" make web applications for the Safari web
LayoutInflater.from(context); android:layout_below="@+id/edtName" Output demonstrating getting and setting data browser. its apple integrated development
View listItem= layoutInflater.inflate android:id="@+id/radGroup” to/from xml file environment (IDE). The Xcode editor is the
(R.layout.recyclerview_items, parent, false); android:orientation="horizontal" Now we are going to look another example primary development tool for any type of
ViewHolder viewHolder = new android:layout_toRightOf="@+id/txtGender"> where user input two numbers using EditText. apple platforms like OSX Software’s, iPhones
ViewHolder(listItem); <RadioButton When user clicks a Button then our application App, Mac, etc.
return viewHolder; android:layout_width="wrap_content" performs addition of two numbers and displays
} android:layout_height="wrap_content" result in a TextView. Hello World in ios
@Override android:text="Male" first_activity.xml
import UIKit
public void onBindViewHolder(ViewHolder android:id="@+id/radMale" /> <?xml version="1.0" encoding="utf-8"?>
class ViewController: UIViewController {
holder, int position) { <RadioButton <RelativeLayout
MyData current=data.get(position); android:layout_width="wrap_content" xmlns:android="http://schemas.android.com/ap @IBOutlet var displayLabel: UILabel!
holder.txtName.setText(current.getName()); android:layout_height="wrap_content" k/res/android" @IBAction func saySomethingTapped(_
holder.txtAddress.setText(current.getAddress()); android:text="Female" android:layout_width="match_parent" sender: UIButton) {
holder.imageView.setImageResource(current.get android:id="@+id/radFemale" /> android:layout_height="match_parent"> displayLabel.text = "Hello World!" }
Image()); </RadioGroup> <EditText }
} <TextView android:layout_width="match_parent"
@Override android:layout_width="wrap_content" android:layout_height="wrap_content" =====================================
public int getItemCount() { android:layout_height="wrap_content" android:layout_margin="5dp" SQL vs SQLite difference between
return data.size(); android:text="Program:" android:hint="Enter First Number" SQL SQLite
} android:textSize="18sp" android:inputType="number" SQL is a Structured SQLite is an embedded
public static class ViewHolder extends android:layout_below="@+id/radGroup" android:id="@+id/edtFirst" /> Query Language used to Relational Database
RecyclerView.ViewHolder { android:layout_margin="5dp" <EditText query & manage data in Management System
TextView txtName,txtAddress; android:id="@+id/txtProgram" /> android:layout_width="match_parent" relational databases. (RDBMS) written in ANSI-
ImageView imageView; <Spinner android:layout_height="wrap_content" SQL is a standard SQLite is a software librar
public ViewHolder(View itemView) { android:layout_width="wrap_content" android:layout_below="@+id/edtFirst" language, not a that implements a self-
super(itemView); android:layout_height="wrap_content" android:layout_margin="5dp" software or DBMS. It contained, file-based SQL
txtName = itemView.findViewById(R.id.txtName); android:entries="@array/programs" android:hint="Enter Second Number" defines how to create database engine.
and manage relational
txtAddress = android:layout_below="@+id/radGroup" android:inputType="number"
data.
itemView.findViewById(R.id.txtAddress); android:layout_toRightOf="@+id/txtProgam" android:id="@+id/edtSecond" />
SQL includes SQLite supports most of
imageView = itemView.findViewById(R.id.image); android:layout_marginTop="5dp" <Button
components like DDL, SQL syntax but lacks
}}} android:id="@+id/spProgram" /> android:layout_width="wrap_content" DML, Embedded SQL, advanced features like
Handling clicks in RecyclerView <Button android:layout_height="wrap_content" and Dynamic SQL. stored procedures.
@Override android:layout_width="wrap_content" android:layout_below="@+id/edtSecond" SQL is used by SQLite is a lightweight,
public void onBindViewHolder(ViewHolder android:layout_height="wrap_content" android:layout_marginTop="10dp" databases like MySQL, portable database that yo
holder, int position) { android:layout_below="@+id/txtProgram" android:text="Calculate" PostgreSQL, Oracle, SQL can embed directly into
final MyData current=data.get(position); android:layout_marginTop="10dp" android:id="@+id/btnCalculate" Server, etc. It cannot applications.
holder.txtName.setText(current.getName()); android:text="Submit" android:layout_centerHorizontal="true" /> store data on its own.
holder.txtAddress.setText(current.getAddress()); android:id="@+id/btnSubmit" <TextView Traditional SQL SQLite is serverless and
holder.imageView.setImageResource(current.get android:layout_centerHorizontal="true" /> android:layout_width="wrap_content" databases require a file-based — no separate
Image()); <TextView android:layout_height="wrap_content" server process to run process or server is
//handling clicks android:layout_width="wrap_content" android:text="Result" (e.g., Oracle, MySQL). needed.
holder.imageView.setOnClickListener(new android:layout_height="wrap_content" android:textSize="18sp" SQL is just a language SQLite is a full-fledged
android:id="@+id/txtResult" used to communicate database system that use
View.OnClickListener() { android:text="Result"
with databases. SQL internally.
@Override android:textSize="18sp" android:layout_below="@+id/btnCalculate"
public void onClick(View view) { android:id="@+id/txtResult" android:layout_margin="5dp"
android:layout_centerHorizontal="true" /> Activity vs Fragments difference between
//retieving data android:layout_below="@+id/btnSubmit"
Activity Fragment
String name=current.getName(); android:layout_margin="5dp" </RelativeLayout>
An Activity is a A Fragment is a reusable
String address=current.getAddress(); android:layout_centerHorizontal="true" /> FirstActivity.java
complete application portion of an Activity’s UI. It
Toast.makeText(context,name,Toast.LENGTH_SH </RelativeLayout> public class FirstActivity extends Activity {
component that contributes its own UI and
ORT).show(); EditText edtFirst,edtSecond; provides a UI for user behavior to the Activity.
} }); FirstActivity.java Button btnCalculate; interaction.
} public class FirstActivity extends Activity { TextView txtResult; Activity can exist Fragment cannot exist
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> EditText edtId,edtName; @Override independently. without being hosted in an
Getting and Setting Data to/from Layout File RadioButton radMale,radFemale; protected void onCreate(Bundle Activity.
To demonstrate this topic, now we are going Spinner spProgram; savedInstanceState) { You must declare You do not need to declare
to create an activity containing some Button btnSubmit; super.onCreate(savedInstanceState); every Activity in the Fragments in the
TextView txtResult; setContentView(R.layout.first_activity); AndroidManifest.xml AndroidManifest.xml file.
important widgets like TextView, Button,
@Override edtFirst=findViewById(R.id.edtFirst); file.
EditText, RadioButton and Spinner. First we
protected void onCreate(Bundle edtSecond=findViewById(R.id.edtSecond); You cannot create a Using multiple Fragments in
tryto get all data that we have inputted using multi-screen UI single Activity allows creatio
savedInstanceState) { btnCalculate=findViewById(R.id.btnCalculte);
these widgets. After getting all data we will within a single of multi-screen or dynamic
super.onCreate(savedInstanceState); txtResult=findViewById(R.id.txtResult);
display all received data in a TextView. setContentView(R.layout.first_activity); btnCalculate.setOnClickListener(new Activity without using UIs.
first_activity.xml Fragments.
edtId=findViewById(R.id.edtId); View.OnClickListener() {
<?xml version="1.0" encoding="utf-8"?> Lifecycle methods Lifecycle methods of
edtName=findViewById(R.id.edtName); @Override
<RelativeLayout (onCreate, onStart, Fragments are managed by
radMale=findViewById(R.id.radMale); public void onClick(View view) { etc.) are managed by the hosting Activity.
xmlns:android="http://schemas.android.com/ap radFemale=findViewById(R.id.radFemale); //getting data from edit text
k/res/android" the OS.
spProgram=findViewById(R.id.spProgram); int first, second,result; Project built with Fragments allow for modula
android:layout_width="match_parent" btnSubmit=findViewById(R.id.btnSubmit); first=Integer.parseInt(edtFirst.getText().toString() only Activities can maintainable, and reusable
android:layout_height="match_parent"> txtResult=findViewById(R.id.txtResult); ); become complex and UI components, improving
<TextView btnSubmit.setOnClickListener(new second=Integer.parseInt(edtSecond.getText().toS harder to manage. project structure.
android:layout_width="wrap_content" View.OnClickListener() { tring());
Activity is not Fragment is dependent on an
dependent on a Activity to function.
Fragment.
Linear. Vs Relative layout
LinearLayout RelativeLayout
Arranges views linearly Arranges views relative to
(either horizontally or each other or to the
vertically). parent.
Suitable for simple, one- Suitable for complex,
directional layouts. flexible layouts.
Syntax: <LinearLayout> Syntax: <RelativeLayout>
<!-- Views --> <!-- Views -->
</LinearLayout> </RelativeLayout>
Requires nested Requires fewer nested
LinearLayouts to create views, making it more
complex UIs, which can efficient for complex
affect performance. layouts.
Less used compared to More commonly used due
RelativeLayout in to its flexibility.
complex applications.
Views are placed in Views can be positioned
order — one after above, below, to the left,
another. right, or centered.
Can be used inside Can also be used as a child
RelativeLayout for of LinearLayout, but often
specific linear sections. serves as the main layout.
Working with Drawable
A drawable resource is a general concept for a
graphic that can be drawn to the screen and
which you can retrieve with APIs such as
getDrawable(int) or apply to another XML
resource with attributes such as
android:drawable and android:icon.
A bitmap file is a .png, .jpg, or .gif file. Android
creates a Drawable resource for any of these
files when you save them in the res/drawable/
directory.
With an image saved at
res/drawable/myimage.png, this layout XML
applies the image to a View:
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/myimage" />
The following application code retrieves the
image as a Drawable:
Resources res = getResources();
Drawable drawable =
ResourcesCompat.getDrawable(res,
R.drawable.myimage, null);