Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views22 pages

Mobile 2

The document provides an overview of Android fragments, mobile devices, and the process of passing data between activities using intents. It explains the types of fragments, the concept of menus in Android applications, and the importance of mobile programming and its lifecycle. Additionally, it discusses dialog boxes, view hierarchy, and the use of Toast for user feedback in mobile applications.

Uploaded by

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

Mobile 2

The document provides an overview of Android fragments, mobile devices, and the process of passing data between activities using intents. It explains the types of fragments, the concept of menus in Android applications, and the importance of mobile programming and its lifecycle. Additionally, it discusses dialog boxes, view hierarchy, and the use of Toast for user feedback in mobile applications.

Uploaded by

Prakritee Pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

To pass the data through Intent we will use

1. What do you mean by fragment? How putExtra() method and in parameter, we will use
fragment can be added to an activity? Ans: Key-Value Pair.
In Android, the fragment is the part of Activity, which Step 6:
represents a portion of User Interface (UI) on the Now open the SecondActivity.
screen. It is the modular section of the android The data is successfully passed.
activity that is very helpful in creating UI designs that Example:
are flexible in nature and auto-adjustable based on // activity_first.xml
the device screen size. The UI flexibility on all <?xml version="1.0" encoding="utf-8"?>
devices improves the user experience and <LinearLayout
adaptability of the application. Fragments can exist xmlns:android="http://schemas.android.com/apk/res/
only inside an activity as its lifecycle is dependent android"
on the lifecycle of host activity. For example, if the xmlns:app="http://schemas.android.com/apk/res-
host activity is paused, then all the methods and 2. What do you mean by mobile device? Explain auto"
operations of the fragment related to that activity will its feature xmlns:tools="http://schemas.android.com/tools"
stop functioning, thus fragment is also termed as Ans: android:layout_width="match_parent"
sub-activity. Fragments can be added, removed, or A mobile device is a handheld tablet or other device android:layout_height="match_parent"
replaced dynamically i.e., while activity is running. that is made for portability, and is therefore both android:layout_gravity="center"
<fragment> tag is used to insert the fragment in an tools:context=".FirstActivity">
compact and lightweight. New data storage,
android activity layout. By dividing the activity’s processing and display technologies have allowed <Button
layout multiple fragments can be added in it. android:id="@+id/Btnpass"
these small devices to do nearly anything that had
Below is the pictorial representation of fragment previously been traditionally done with larger android:layout_width="wrap_content"
interaction with the activity: personal computers. android:layout_height="wrap_content"
Features of Mobile Device are: android:text="Pass Data"
Types of Android Fragments Mobile devices are also known as handheld android:textStyle="bold"
Single Fragment: Display only one single view on the android:textSize="20sp"
computers.
device screen. This type of fragment is mostly used A portable computing device that: android:layout_gravity="center" />
for mobile phones. </LinearLayout>
(i) has a small form factor such that it can
List Fragment: This Fragment is used to display a easily be carried by a single individual; //FirstActivity.java
list-view from which the user can select the desired (ii) It is designed to operate without a public class FirstActivty extends AppCompatActivity {
sub-activity. The menu drawer of apps like Gmail is physical connection (e.g., wirelessly transmit or @Override
the best example of this kind of fragment. Fragment receive information); protected void onCreate(Bundle
Transaction: This kind of fragments supports the savedInstanceState) {
(iii) It possesses local, non-removable or
transition from one fragment to another at run time. removable data storage; and super.onCreate(savedInstanceState);
Users can switch between multiple fragments like setContentView(R.layout.activity_first_activty);
(iv)It includes a self-contained power source. Mobile
switching tabs. devices may also include voice communication Button b=(Button) findViewById(R.id.Btnpass);
<?xml version="1.0" encoding="utf-8"?> capabilities, on-board sensors that allow the devices b.setOnClickListener(new View.OnClickListener() {
<LinearLayout to capture information, and/or built-in features for @Override
xmlns:android="http://schemas.android.com/apk/res/ synchronizing local data with remote locations. public void onClick(View v) {
android" Intent i=new Intent(FirstActivty.this,
Examples include smart phones, tablets, and e-
android:layout_width="match_parent" readers. SecondActivity.class); //passing Data using PutExtra
android:layout_height="match_parent" i.putExtra("Roll", 101);
android:orientation="vertical" > 3. How can you pass data between multiple i.putExtra("Name","Tabita");
<fragment activities using intent? Explain. Ans: i.putExtra("Address", "Lalitpur");
android:name="com.example.android.FirstFragment" Through Intent we can move from one activity to startActivity(i);
android:id="@+id/FirstFragment" another activity and Intent can also be used to pass } });
android:layout_width="match_parent" }}
the data from one activity to another activity.
android:layout_height="match_parent" /> Step 1: // SecondActivity.java
</LinearLayout> public class SecondActivity extends
First of all, we have to link the views of
Creating Fragments activity_login.xml with LoginActivity In AppCompatActivity {
Create XML layout file is just like any other layout activity_login.xml, we have used two EditTexts and @Override
file, and can be named fragment_first.xml. one button. Lets initialize them in our LoginActivity. protected void onCreate(Bundle
<?xml version="1.0" encoding="utf-8"?> public class LoginActivity extends savedInstanceState) {
<LinearLayout super.onCreate(savedInstanceState);
AppCompatActivity {
xmlns:android="http://schemas.android.com/apk/res/ EditText edittextfullname,edittextusername; setContentView(R.layout.activity_second);
android" //Receiving Data from firstActivity using
Button loginbutton;
android:layout_width="match_parent" @Override getTypeExtra
android:layout_height="match_parent" Intent i= getIntent();
protected void onCreate(Bundle savedInstanceState)
android:orientation="vertical" > { int roll=i.getIntExtra("Roll",0);
<TextView super.onCreate(savedInstanceState); String name=i.getStringExtra("Name");
android:id="@+id/textView1" String address=i.getStringExtra("Address");
setContentView(R.layout.activity_login);
android:layout_width="wrap_content" edittextfullname=findViewById(R.id.editTextFullNam //Displaying Received Data
android:layout_height="wrap_content" TextView t=(TextView) findViewById(R.id.rtext);
e);
android:text="TextView" /> edittextusername=findViewById(R.id.editTextUserNa t.setText("Roll
</LinearLayout> ="+roll+"\n"+"Name="+name+"\n"+"Address="+addre
me);
Create Java Controller for Fragments loginbutton=findViewById(R.id.LoginButton); ss);
import androidx.fragment.app.Fragment; }} }}
public class FirstFragment extends Fragment { //activity_second.xml
Step 2 :
// The onCreateView method is called when Now we have to create a new activity so let’s create <?xml version="1.0" encoding="utf-8"?>
Fragment should create its View object hierarchy, // <LinearLayout
an activity
either dynamically or via XML layout inflation. Name the new activity as SecondActivity. xmlns:android="http://schemas.android.com/apk/res/
@Override android"
Now you have created two Activities. With the help of
public View onCreateView(LayoutInflater inflater, Intent,we will go from one activity to another activity xmlns:app="http://schemas.android.com/apk/res-
ViewGroup cotainer, Bundle savedInstanceState) { (LoginActivity to SecondActivity) auto"
// Defines the xml file for the fragment xmlns:tools="http://schemas.android.com/tools"
Step 3:
View view = inflater.inflate(R.layout.fragment_first, When we press the button, setOnClickListener() will android:layout_width="match_parent"
container, false); android:layout_height="match_parent"
be called and inside setOnClickListener(), we will
return view; write code to open new activity and we can do this android:layout_gravity="center"
} tools:context=".SecondActivity"> <TextView
with the help of Intent.
} Step 4 : android:id="@+id/rtext"
Add a fragment to an activity If we have to open one activity from another activity android:layout_width="wrap_content"
• There are two ways to add a fragment to an android:layout_height="wrap_content"
we have to add an Intent code in onClick(View view)
activity: Add a fragment via XML(Statically), Add a method as shown below. android:textStyle="bold"
fragment programmatically(dynamically) android:background="@color/colorAccent"
Intent intent = new Intent(Source, Destination);
Add a fragment via XML (Statically) startActivity(intent); android:textSize="30sp"
• To add the fragment statically, simply embed the android:layout_gravity="center" />
Step 5:
fragment in the activity's xml layout file:. </LinearLayout>
4. What do you mean by menu? Explain its type • The mobile front-end is the visual and interactive 7(and arranges other widgets. You use a
Ans: part of the application the user experiences. It LinearLayout when you want widgetsarranged in a
In android, Menu is an important part of the UI usually resides on the device, or there is at least an single column or row. Other ViewGroup subclasses
component which is used to provide some common icon representing the app that is visible on the home are FrameLayout,TableLayout, and RelativeLayout.
functionality around the application. With the help of screen or is pinned in the application CatLog of the When a widget is contained by a ViewGroup, that
menu, users can experience a smooth and device. The application can be downloaded from the widget is said to be a child of theViewGroup. The
consistent experience throughout the application. In platform app store, side-loaded directly onto the root LinearLayout has two children: a TextView and
order to use menu, we should define it in a separate device, or can be reached through the device’s another LinearLayout.The child LinearLayout has
XML file and use that file in our application based on browser. two Button children of its own.)7
our requirements. Also, we can use menu APIs to • Regardless of what front-end platform or
represent user actions and other options in our development methodology is being used, delivering 8. Differentiate activity and fragment with example?
android application activities. high-quality mobile applications that delight and Ans:
Android Different Types of Menus retain users requires reliable back-end services.
In android, we have three types of Menus available • Given the critical importance of back-end services
to define a set of options and actions in our android for the success of the mobile application, the
applications. The Menus in android applications are developers have several important architectural
the following: decisions that they must consider. These decisions
Android Options Menu is a primary collection of include which services should they build themselves
menu items in an android application and is useful and which third party services should they leverage,
for actions that have a global impact on the and then should they run and maintain their own
searching application. services or should they take advantage of 3rd party
Android Context Menu is a floating menu that only services
appears when the user clicks for a long time on an
element and is useful for elements that affect the
selected content or context frame.
Android Popup Menu displays a list of items in a
vertical list which presents the view that invoked the
menu and is useful to provide an overflow of actions
related to specific content.

5. Which dialog boxes can you use in your


android application?
Ans:
A dialog is a small window that prompts the user to 7. What do you mean by view hierarchy? Explain
make a decision or enter additional information. A view hierarchy of android with the help of
dialog does not fill the screen and is normally used suitable example? 9. What do you mean by IOS programming?
for modal events that require users to take an action Ans: Ans:
before they can proceed. A view hierarchy defines the relationships of views in IOS is a mobile operating system for Apple-
The Dialog class is the base class for dialogs, but a window to each other. You can think of a view manufactured devices. iOS runs on the iPhone, iPad,
you should avoid instantiating Dialog directly. hierarchy as an inverted tree structure with the iPod Touch and Apple TV. iOS is best known for
Instead, use one of the following subclasses: window being the top node of the tree. Under it serving as the underlying software that allows
Alert Dialog:- A dialog that can show a title, up to come views structurally specified by parent-child iPhone users to interact with their phones using
three buttons, a list of selectable items, or a custom relationships. From a visual perspective, the gestures such as swiping, tapping and pinching.
layout. essential fact of a view hierarchy is enclosure: one These finger actions are typically performed on multi
Custom Dialog:- A custom dialog built by view contains one or more other views, and the touch capacitive touch screen displays, which
programmer as per the requirement. window contains them all. provide fast response and accept inputs from
DatePickerDialog or TimePickerDialog:- A dialog The view hierarchy is also the governing concept multiple fingers
with a pre-defined UI that allows the user to select a behind view composition: You construct compound 10. Why we use Toast? How Toast can be used in
date or time. views by adding subviews to a superview. Finally, android application? Explain with suitable example.
the view hierarchy is a critical factor in the multiple Ans:
6. What do you mean by mobile programming? coordinate systems found in a window. A toast provides simple feedback about an operation
Explain life cycle of mobile application Example: in a small popup. It only fills the amount of space
development? second.xml required for the message and the current activity
Ans: <?xml version="1.0" encoding="utf-8"?> remains visible and interactive. Toasts automatically
Mobile application development is the process of <LinearLayout disappear after a timeout.
creating software applications that run on a mobile xmlns:android="http://schemas.android.com/apk/res/ Why we use Toast
device, and a typical mobile application utilizes a android" • Giving user feedback regarding some operation.
network connection to work with remote computing android:layout_width="match_parent" • It does not block the activity or the fragment in
resources. android:layout_height="match_parent" which it appears.
The life cycle of a typical development project, no android:gravity="center" • It is not like dialog it just appear on the top of
matter the complexity: android:orientation="vertical"> activity and disppears after short time. Syntax
1. Planning stage (project manager, marketer, and <TextView Toast tost= Toast.makeText(Context c,
business analyst are involved) – carrying out the android:layout_width="wrap_content" CharacterSequence text, int duration).show(); • To
business analysis and crafting mobile strategy. android:layout_height="wrap_content" control toast’s position on screen by using
2. Technical documentation (covered by the android:text="@string/text_question" setGravity(int gravity, intxdist, int ydist) • You can use
technical writer) – describing all tech requirements android:textStyle="bold" the following constants in the Gravity class to specify
and details. android:textSize="20sp"/> the overall position: • TOP
3. Prototyping (usually made by a UX/UI designer) – <LinearLayout • BOTTOM
creating the sketch, wireframes, prototype and final android:layout_width="wrap_content" • LEFT
app skins upon approval. android:layout_height="wrap_content" • RIGHT
4. Development (performed by the developers) – android:orientation="horizontal"> • CENTER
front-end and back-end segments of coding. 5. <Button • CENTER_HORIZONTAL
Quality Assurance (usually performed continuously android:layout_width="wrap_content" • CENTER_VERTICAL
after each agile sprint is completed; followed by bug android:layout_height="wrap_content" Toast toast =
fixing) – testing tech requirements, device android:text="@string/text_true"/> Toast.makeText(getApplicationContext(),"First",
compatibility, interface, security aspects, etc. 6. <Button Toast.LENGTH_LONG);
Publishing & Maintenance (covered by DevOps) – android:layout_width="wrap_content" toast.setGravity(Gravity.CENTER, 0, 0);
publishing to the app store, updates releases, android:layout_height="wrap_content" toast.show();
infrastructure, and entire app maintenance. android:text="@string/text_false"/> Toast second =
Mobile Application Development Lifecycle </LinearLayout> Toast.makeText(getApplicationContext(),"Second",
There are two interlinked core components of a </LinearLayout> Toast.LENGTH_LONG);
mobile application: 1)the mobile application “Front- The root element of this layout’s view hierarchy is a second.setGravity(Gravity.TOP, 0, 0);
End” that resides on the mobile device, and 2) the LinearLayout. As the root element, the LinearLayout second.show();
services “Back-End” that supports the mobile front- must specify the Android resource XML namespace Toast bottom =
end. at http://schemas.android.com/ apk/res/android. Toast.makeText(getApplicationContext(),“Third",
LinearLayout inherits from a subclass of View named Toast.LENGTH_LONG);
ViewGroup. A ViewGroup is a widget that contains bottom.setGravity(Gravity.BOTTOM, 0, 0);
However, Java is a complicated language for a must have if they want to access content from this
beginner to use as it contains complex topics like app.
11. What do you mean by API? Explain its types. constructors, null pointer exceptions, concurrency, • The hardware and software features the app
Ans: checked exceptions, etc. Also, The Android requires, which affects which devices can install the
Application Programming Interface (API) is a Software Development Kit (SDK) increases the app from Google Play.
software interface that allows two applications to complexity to a new level! All in all, Java is a great If you subclass any of these components without
interact with each other without any user language to experience the full joys of Android App declaring it in the manifest file, the system cannot
intervention. API is a collection of software functions Development. However, it may be a little complex start it.
and procedures. In simple terms, API means a for beginners who would prefer to start with The name of your subclass must be specified with
software code that can be accessed or executed. something easier and then return to it. the name attribute, using the full package
API is defined as a code that helps two different 2. Kotlin: Now Kotlin is the official language for designation. For example, an Activity subclass can
software’s to communicate and exchange data with Android App Development declared by Google in be declared as follows:
each other. 2019. Kotlin is a cross-platform programming <manifest ... >
It offers products or services to communicate with language that may be used as an alternative to Java <application ... >
other products and services without having to know for Android App Development. It has also introduced <activity
how they’re implemented. as a secondary “official” Java language in 2017. android:name="com.example.myapp.MainActivity" ...
Kotlin can interoperate with Java and it runs on the >
There are mainly four main types of APIs: Java Virtual Machine. The only sizable difference is </activity>
WEB APIs that Kotlin removes the superfluous features of Java </application>
A Web API is an open source interface and can be such as null pointer exceptions. It also removes the </manifest>
used by a large number of clients through their necessity of ending every line with a semicolon. In Example
phones, tablets. Alternatively, PC’s. short, Kotlin is much simpler for beginners to try as AndroidManifest.xml
LOCAL APIs: compared to Java and it can also be used as an <manifest
In these types of API, the programmers get the local “entry point” for Android App Development. xmlns:android="http://schemas.android.com/apk/res/
middleware services. TAPI (Telephony Application 3. C++: C++ can be used for Android App android"
Programming Interface), .NET are common Development using the Android Native Development package="com.example.raazu.myapplication">
examples of Local API’s. PROGRAM APIs: Kit(NDK). However, an app cannot be created totally <application
It makes a remote program appears to be local by using C++ and the NDK is used to implement parts android:allowBackup="true"
making use of RPC’s (Remote Procedural Calls). of the app in C++ native code. This helps in using android:icon="@mipmap/ic_launcher"
SOAP is a well-known example of this type of API. C++ code libraries for the app as required. While android:label="@string/app_name"
C++ is android:roundIcon="@mipmap/ic_launcher_round"
useful for Android App Development in some cases, android:supportsRtl="true"
it is much more difficult to set up and is much less android:theme="@style/AppTheme">
flexible. It may also lead to more bugs because of <activity android:name=".Second">
the increased complexity. So, it is better to use Java <intent-filter>
as compared to C++ as it does not provide enough <action android:name="android.intent.action.MAIN"
gain to offset the efforts required. />
12. How do you find view element in your 4. C#:- C# is quite similar to Java and so it is ideal <category
program? Explain five different programming for Android App Development. Like Java, C# also android:name="android.intent.category.LAUNCHER"
language used for developing mobile application. implements garbage collection so there are fewer />
Ans:- chances of memory leaks. And C# also has a </intent-filter>
View:- The view is the component which Android cleaner and simpler syntax than Java which makes </activity>
provides us to design the layouts of the app. So, we coding with it comparatively easier. Earlier, the </application>
can understand view as a rectangular area which is biggest drawback of C# was that it could run only on </manifest>
going to contain some element inside it. A View is a Windows systems as it used the .NET Framework. 14. Differentiate linear layout and relative layout
superclass for all the UI components. However, this problem was handled by Xamarin. with example.
list of some of the view components: Android (formerly Mono for Android) is a cross- Ans:
∙ TextView: To add some text in your application. platform implementation of the Common Language
∙ EditText: This is used when you want to take some Infrastructure. Now, Xamarin. Android tools can be
input from the users. used to write native Android apps and share the
∙ ImageView: To add some image in the application. code across multiple platforms.
∙ ProgressBar: To show the progress to something. 5. Python: Python can be used for Android App
For example, the loading screen. ∙ Button: Buttons Development even though Android doesn’t support
are used to trigger some action on the click of the native Python development. This can be done using
button. It can be starting a new activity or something various tools that convert the Python apps into
else. Android Packages that can run on Android devices.
∙ ImageButton: It is used to make a clickable image. An example of this is Kivy which is an open-source
∙ CheckBox: CheckBox is used to select some Python library used for developing mobile apps. It
options out of many available options. ∙ DatePicker: supports Android and also encourages rapid app
To select some particular date. development (which is a win-win situation according
These are some of the UI components that are to me!). However, a downside to this is that there
available for our use. won’t be native benefits for Kivy as it isn’t natively
Example of view element Button supported.
<Button 13. Explain about manifest file. How can we add
android:id="@+id/button" activity in manifest? Explain with example. Ans:
android:layout_width="160dp" The manifest file describes essential information
android:layout_height="80dp" about your app to the Android build tools, the
Android operating system, and Google Play.
android:background="@color/backgroundButtonBefo • The app's package name, which usually matches
re" your code's namespace. The Android build tools use
android:text="@string/text_before" this to determine the location of code entities when
app:layout_constraintBottom_toBottomOf="parent" building your project. When packaging the app, the
app:layout_constraintEnd_toEndOf="parent" build tools replace this value with the application ID
app:layout_constraintStart_toStartOf="parent" from the Gradle build files, which is used as the
app:layout_constraintTop_toTopOf="parent" /> unique app identifier on the system and on Google
Top mobile app development languages Play.
JavaScript, Kotlin, C++, C#, Python, PHP, Swift, • The components of the app, which include all
Objective-C, JAVA, HTML 5, Ruby, Rust, Lua, Action activities, services, broadcast receivers, and content
Script, SQL providers. Each component must define basic
1. Java: Firstly Java was the official language for properties such as the name of its Kotlin or Java
Android App Development (but now it was replaced class. It can also declare capabilities such as which
by Kotlin) and consequently, it is the most used device configurations it can handle, and intent filters
language as well. Many of the apps in the Play Store that describe how the component can be started.
are built with Java, and it is also the most supported • The permissions that the app needs in order to
language by Google. In addition to all this, Java has access protected parts of the system or other apps.
a great online community for support in case of any It also declares any permissions that other apps
problems (And trust me, there will be problems!).
15. Explain android architecture briefly with ∙ Process Management: It manages the process well, 17. What are activities? Describe the lifecycle of
suitable diagram. allocates resources to processes whenever they an activity.
Ans: need them. Ans:
Android operating system is a stack of software ∙ Network Stack: It effectively handles the network • An activity is an application component that
components which is roughly divided into five communication. provides a screen with which user can interact in
sections and four main layers as shown below in the ∙ Driver Model: It ensures that the application works order to do something such as dial the phone, take a
architecture diagram. properly on the device and hardware manufacturers photo, send a email or view a map. • Each activity is
The main components of android architecture are responsible for building their drivers into the Linux given a window in which user interface can be
following:- build drawn.
∙ Applications • An application usually consist of multiple activities
∙ Application Framework that are loosely bounded to each other. • Each time a
∙ Android Runtime new activity starts, the previous activity is stopped
∙ Platform Libraries but the system preserves the activity in a stack
∙ Linux Kernel • When a new activity starts, it is pushed onto the
Applications – back stack and take user focus.
Applications is the top layer of android architecture.
The pre-installed applications like home, contacts, The Activity class defines the following call backs i.e.
camera, gallery etc and third party applications events. You don't need to implement all the callbacks
downloaded from the play store like chat methods. However, it's important that you
applications, games etc. will be installed on this understand each one and implement those that
layer only. ensure your app behaves the way users expect.
It runs within the Android run time with the help of 16. What is event? Explain Different way to
the classes and services provided by the application handle event in android application. Ans:
framework. Events are a useful way to collect data about a
Application framework – user's interaction with interactive components of
Application Framework provides several important Applications. Like button presses or screen touch
classes which are used to create an Android etc. The Android framework maintains an event
application. It provides a generic abstraction for queue as first-in, first-out (FIFO) basis.
hardware access and also helps in managing the
user interface with application resources. Generally,
it provides the services with the help of which we can
create a particular class and make that class helpful
for the Applications creation. It includes different
types of services activity manager, notification
manager, view system, package manager etc. which
are helpful for the development of our application
according to the prerequisite. Application runtime –
Android Runtime environment is one of the most
important part of Android. It contains components
like core libraries and the Dalvik virtual
machine(DVM). Mainly, it provides the base for the
application framework and powers our application
with the help of the core libraries.
Like Java Virtual Machine (JVM), Dalvik Virtual
Machine (DVM) is a register-based virtual machine
and specially designed and optimized for android to
ensure that a device can run multiple instances
efficiently. It depends on the layer Linux kernel for
threading and low-level memory management. The The Activity class defines the following call backs i.e.
core libraries enable us to implement android events. You don't need to implement all the callbacks
applications using the standard JAVA or Kotlin methods. However, it's important that you understand each
programming languages. one and implement those that ensure your app behaves
Platform libraries – the way users expect.
The Platform Libraries includes various C/C++ core
libraries and Java based libraries such as Media,
Graphics, Surface Manager, OpenGL etc. to provide
a support for android development. ∙ Media library
provides support to play and record an audio and
video formats. ∙ Surface manager responsible for
managing access to the display subsystem. ∙ SGL
and OpenGL both cross-language, cross-platform
application program interface (API) are used for 2D
and 3D computer graphics.
∙ SQLite provides database support and FreeType
provides font support. Example: of onClickListener
∙ Web-Kit This open source web browser engine // Get button using its ID:
provides all the functionality to display web content Button btn = findViewById(R.id.my_btn);
and to simplify page loading.
∙ SSL (Secure Sockets Layer) is security technology
// Set OnClickListener() using anonymous class:
to establish an encrypted link between a web server
btn.setOnClickListener(new View.OnClickListener(){
and a web browser. @Override
Linux Kernel – public void onClick(View v){
Linux Kernel is heart of the android architecture. It // Functionality for the button...
manages all the available drivers such as display }
drivers, camera drivers, Bluetooth drivers, audio });
drivers, memory drivers, etc. which are required
during the runtime.
The Linux Kernel will provide an abstraction layer
between the device hardware and the other
components of android architecture. It is responsible
for management of memory, power, devices etc. The
features of Linux kernel are:
∙ Security: The Linux kernel handles the security
between the application and the system.
∙ Memory Management: It efficiently handles the
memory management thereby providing the
freedom to develop our apps.
18. Define widget. Explain any five widgets used 20. Write a swift program to find minimum 2) name of the student
in android application with their attributes. Ans: element from all element of 1-D array Ans: 3) surname or last name of the student
Funcsum(_data:[int]-> int 4) marks scored by the student.
Widgets are the micro-version of the application that { We are going to create a database or insert some
consists of some functionality of the application that Var result: int =0 data like this so id can be one two three four for
is displayed only on the Home Screens or the Lock Var i: int =0 example, name, surname and marks scored by the
Screen. For example, we see Weather, Time, For element indata students.
Google Search Bars on the Home Screen, and { Step 9) Now we will declare some variables so that
FaceLock, FingerprintLock on the Lock Screen, Result += data[i] we can define the names of our database. So let's
which are some of the Widgets available on the i+=1; declare our variable which we are going to assign
device. Widgets come along with the Application } the database name so let's declare a variable name
when you install it or download it from the Web. Return result called database_name, we will assign the name of
Generally, phones come with a manufacturing } our database, for example, 'student.db'. And second
configuration but such elements can be adjusted by Let array ={3,5,6,5,4,8,22,12,14} what we are going to do is we are going to declare
a user later in time. In this article, we demonstrate Print(sum(array)) our table name, so this will be a table name and let's
how one can implement a basic widget for an give the name to our table as 'student_table' which
Android App. 21. Explain the process of creating database and will resonate perfectly with our table.
Some of Android UI Widgets table using SQlite into android. Ans: Step 10) And as we have discussed, this table is
There are given a lot of android widgets with SQLite is database, which is an open source going to contain 4 columns, one, two, three, four and
simplified examples such as Button, EditText, database so you can use it free, and its relational for simplicity lets keep all the variables as a string.
AutoCompleteTextView, ToggleButton, DatePicker, database, okay and the most important feature First column name was ID for the student and the
TimePicker, ProgressBar etc. The widely used about SQLite database is it’s a local database so it column name is ID right, so do something like this,
android widgets with examples are given below: doesn’t require any server or any ODBC or JDBC col 1, col 1 is ID, similarly column 1, column 2,
Android Button:- Let's learn how to perform event query or connection for its functionality. column 3 column 4. Column 2, column 3, column 4,
handling on button click. It's just, You can say it saves the data in word text first column is ID, the second column is name, the
Android Toast:- Displays information for the short file and saved locally on you can say mobile device third column is surname and fourth column is marks.
duration of time. or tablet or whatever Android device you are using So these are the four column, this is our table name
Custom Toast:- We are able to customize the toast, and Android comes with the built-in SQLite database and this is our database name.
such as we can display image on the toast implementation. So you don’t need to install any Step 11) Now in order to create our database, we
ToggleButton:- It has two states ON/OFF. extra libraries to use SQLite with Android are go ing to create our database in the constructor.
CheckBox:- Let's see the application of simple food To create or update a database in your Android So we need to call a function which creates a
ordering. Application you just need to create a subclass of the database. So for simplicity let's reduce our
AlertDialog:- Alert Dialog displays a alert dialog SQLiteOpenHelper class. In the constructor of your constructor which only takes this context and as you
containing the message with OK and Cancel buttons. subclass you call the super() method of can see here this superclass, we can just give the
Spinner:- Spinner displays the multiple options, but SQLiteOpenHelper. name of the database. Our database name is this
only one can be selected at a time. Please follow the steps below in order to create variable, pass it here. Thirds is factory, we are going
AutoCompleteTextView:- Let's see the simple database tables: to pass null here, and the version. For example,
example of AutoCompleteTextView. RatingBar:- Step 1) So just open your Android studio, we are version is equal to 1. Now whenever this constructor
Rating Bar displays the rating bar. going to start a new Android Application and we will is called, your database will be created.
DatePicker:- Date picker displays the date picker name our application as SQLite app for example and
dialog that can be used to pick the date. then click next or select you minimum sdk. Click Step 12) Now in order to create the table inside your
TimePicker:- Time Picker displays the time picker next and select a blank activity next, and leave main database, we are going to create a table whenever
dialog that can be used to pick the time. activity as default and click finish. the onCreate method of this class is called . So you
ProgressBar:- Progress Bar displays progress task. Step 2) Now once your basic app is created, what can see SQLite database class is the argument
we’re going to do is we’re going to create a class for inside onCreate.
19. Why Recycle view is recommended over List handling the SQLite database. So go to your app
view? Explain with example. folder and in the app folder go to your java folder Step 13) So we can just take the db which is the
Ans: and inside here go to the package in which your variable of SQLite database, so take this instance db
ListView is the ancestor to RecyclerView. There main activity and right click the package and we’re and call a method called .exacsql and what it does
were many things that ListView either didn't do, or going to create a new java class. is it executes whatever query you pass inside this
didn't do well. If you were to gather the Step 3) Now below is a basic blank class and in here method as an argument.
shortcomings of the ListView and solved the problem we want to create or extend this class using our
by abstracting the problems into different domains SQLiteOpenHelper, so just write extend Step 13) It takes the string variable or the string
you'd end up with something like the recycler view. SQLiteOpenHelper. query so here you can prepare the creatable query
Here are the main problem points with ListViews: and whenever its called, its going to execute the
∙ Didn't enforce View Reuse for same item types Step 4) It might show some error because we query and is going to create this table. So lets write
(look at one of the adapters that are used in a haven’t imported the classes related to this SQLite our query, for example create the table name, so
ListView, if you study the getView method you will open helper so just click Alt+Enter, and just click the create table and the table name in our case is this
see that nothing prevents a programmer from button called import class and its going to import this one so you can use his concatenation operator to
creating a new view for every row even if one is class okay. concatenate this and then inside your bracket your
passed in via the convertView variable) Step 5) Still it might show you some error because column name comes right. So first column name is
∙ Didn't prevent costly findViewById uses(Even if you we need to create or implement some of the ID or you can just take these name or column 1,
were recycling views as noted above it was possible methods from it so you will be able to see a small column 2, column 3 and column 4 .
for devs to be calling findViewById to update the bulb there. You just need to click this bulb and you So just write create table and your table name and
displayed contents of child views. The main purpose just need to click implement methods and there are then in the brackets comes the ID which is the first
of the ViewHolder pattern in ListViews was to cache two methods related to this class which are column name and then comes he attributes of this
the findViewById calls. However this was only onCreate and onUpgrade. You are going to select column, so it’ll be integer and its going to be my
available if you knew about it as it wasn't part of the both of them and click OK. primary key. Primary key means the unique key
platform at all) Step 6) And one more thing which is required to be which you will be able to identify the rows, okay. And
∙ Only supported Vertical Scrolling with Row created is a default constructor so once again click then its going to auto increment.
displayed Views (Recycler view doesn't care about this red bulb here and just choose constructor
where views are placed and how they are moved, matching super and we are going to select first of
it's abstracted into a LayoutManager. A Recycler can them and just create it.
therefore support the traditional ListView as shown Step 7) So we have successfully created our
above, as well as things like the GridView, but it isn't database helper class which extends from SQLite
limited to that, it can do more, but you have to do the open helper which is the main class for handling
programming foot work to make it happen). SQLite and we have some basic methods and
∙ Animations to added/removed was not a use case constructor. Step 8) Now for creating the database,
that was considered. It was completely up to you to first of all, we need a database name. Now let us see
figure out how go about this (compare the how we are going to create a database and what will
RecyclerView. Adapter classes notify* method be the name of our database and all other stuff. So
offerings v. ListViews to get an idea). for this, for example, to start with we are going to
In short RecyclerView is a more flexible take on the create a base like SQLite database like shown in the
ListView, albeit more coding may need to be done on images below and the name of the database will be
your part. Student.db.
So our database name will be student.b and its going
to contain four columns: 1) id of the student
22. How can you use string and string array in android:layout_width=wrap_content tells the view to 25. Explain the procedure for publishing signed
android? Explain. size itself to the dimensions required by its content. APK in play store
Ans: android:layout_width=match_parent tells the view to Ans:
A string resource provides text strings for your become as big as its parent view. Android Studio allows you to create two kinds of APK
application with optional text styling and formatting. Linear Layout:- LinearLayout is a view group that files.
There are three types of resources that can provide aligns all children in a single direction, vertically or a) Debug APK files that are generated solely for
your application with strings: horizontally. testing purposes. They will run on your Android
String Relative Layout:- RelativeLayout is a view group that mobile. However, they cannot be uploaded to the
XML resource that provides a single string. displays child views in relative positions. Table Play Store or made available to the public.
String Array Layout:- TableLayout is a view that groups views into b) Signed APK files. Signed APK files come in handy
XML resource that provides an array of strings. rows and columns. Absolute Layout:- when you've tested your application and it is ready
Quantity Strings (Plurals) AbsoluteLayout enables you to specify the exact to be uploaded on the Play Store and released to the
XML resource that carries different strings for location of its children. Frame Layout:- The general public.
pluralization. FrameLayout is a placeholder on screen that you Creating an APK file
All strings are capable of applying some styling can use to display a single view. Scroll Layout;- Generating a debug APK file is easy and is a matter
markup and formatting arguments. For information ListView is a view group that displays a list of of just a few clicks.
about styling and formatting strings scrollable items. First, open up your project or application that you
Referencing an XML string in an XML Array Grid View;- GridView is a ViewGroup that displays want to import into an APK file. Then, select Build >
(Android) items in a two-dimensional, scrollable grid. Build Bundle(s)/APK(s) > Build APK(s) from the
Linear Layout toolbar menu.
in arrays.xml We use this layout to place the elements in a linear Creating an Debug APK file
<string-array name="my_items"> manner. A Linear manner means one element per Generating a debug APK file is easy and is a matter
<item>My item 1</item> line. This layout creates various kinds of forms on of just a few clicks.
<item>My item 2</item> Android. In this, arrangement of the elements is in a First, open up your project or application that you
<item>My item 3</item> top to bottom manner. want to import into an APK file. Then, select Build >
</string-array> This can have two orientations: Build Bundle(s)/APK(s) > Build APK(s) from the
in strings.xml a. Vertical Orientation – It is shown above where the toolbar menu.
<resources> widgets such as TextViews, and all in a vertical If you miss the notification, you can still locate the
<string name="item1">My item 1</string> manner. APK file in the following path within your project
<string name="item2">My item 2</string> b. Horizontal Orientation – It is shown above where folder: app/build/outputs/apk/debug. The file is
<string name="item3">My item 3</string> the widgets such as TextViews, and all in a named app-debug.apk by default.
</resources> horizontal manner. Creating a Signed APK File
A LinearLayout respects margins between children To generate a signed APK file, open the Build menu
23. How can we create string resource? Explain and the gravity (right, center, or left alignment) of from the toolbar and select Generate Signed
with the help of suitable example? Ans: each child. Bundle/APK.
Add String Resources Most important attribute of the LinearLayout is This opens up a screen where you have to select
By default, your Android project includes a string orientation android:orientation="vertical"or between creating an Android App Bundle and
resource file at res/values/strings.xml. Here, you'll android:orientation="horizontal" creating an APK file. Check the APK radio button
add a new string named "edit_message" and set the <?xml version="1.0" encoding="utf-8"?> and proceed to the next window.
value to "Enter a message." <LinearLayout In the next window, you will be shown the module
In Android Studio, from the res/values directory, xmlns:android="http://schemas.android.com/apk/res/ (your application) for which the APK file is being
open strings.xml. android" generated. You’ll be asked about your Key store
Add a line for a string named "edit_message" with android:layout_width="match_parent" path, Key store password, Key alias, and the Key
the value, "Enter a message". Add a line for a string android:layout_height="match_parent" password.
named "button_send" with the value, "Send". android:paddingLeft="16dp" Creating a New Key Store
The result for strings.xml looks like this: android:paddingRight="16dp" Assuming that this is the first time you’re creating a
<?xml version="1.0" encoding="utf-8"?> android:orientation="vertical" > Signed APK file, you will have to create a new key
<resources> </LinearLayout> store.
<string name="app_name">My First App</string> Relative layout Keys are used by the developer to access their
<string name="edit_message">Enter a RelativeLayout is a view group that displays child application once it has been uploaded to the Play
message</string> views in relative positions. The position of each view Store. The need for the keys usually arises when
<string name="button_send">Send</string> can be specified as relative to sibling elements you have to update your application. All of the keys
<string name="action_settings">Settings</string> (such as to the left-of or below another view) or in are stored in the key store.
</resources> positions relative to the parent RelativeLayout area Both the key store and the keys are protected by
24. What do you mean by layout? List and (such as aligned to the bottom, left of center). For passwords of their own. The passwords should be at
explain different types of layout using in android example in a class, if a Student A is sitting on a chair least six characters in length. Also, it is a good
with their attribute? and the teacher of the class asks Student B to sit to practice to keep multiple copies of your keys since
Ans: the right of the Student A. Student B will know where they are your only gateway to your application. If the
A layout defines the structure for a user interface in he/she has to sit. key is lost, you will not be able to access your
your app, such as in an activity. All elements in the A RelativeLayout is a very powerful utility for application or update it.
layout are built using a hierarchy of View and designing a user interface because it can eliminate Creating your own app requires you to create a new
ViewGroup objects. A View usually draws something nested view groups and keep your layout hierarchy key store. To do so, select Create new. You will find
the user can see and interact with. Whereas a flat, which improves performance. If you find yourself it underneath the input field where you enter the key
ViewGroup is an invisible container that defines the using several nested LinearLayout groups, you may store path.
layout structure for View and other ViewGroup be able to replace them with a single RelativeLayout. In the new window, enter the path for your new key
objects, as shown in figure Center relative to Parent View store, and then enter a password to protect it.
android:id : This is the ID which uniquely identifies When you want to place your Views in the center In the same window, you will also be setting a new
the view relative to the parent, you can use the following 3 key for your application. Enter an identity for your
android:layout_width : This is the width of the layout attributes: key in the key alias field and then enter a password
android:layout_height : This is the height of the android:layout_centerHorizontal="true" for it.
layout This places the view horizontally in the center of the You can keep the same password as that of your key
android:layout_margin : This is the extra space parent. As our parent view covers the whole screen store, but it's a good practice to give a new
outside of the view. For example if you give of mobile therefore the view gets placed in the password to each of your keys. The same goes for
android:marginLeft=20dp, then the view will be middle of the mobile screen horizontally. (See the the key alias.
arranged after 20dp from left yellow view in the above figure) The next field defines the validity of your application.
android:layout_padding : This is similar to android:layout_centerVertical="true" This is the duration after which the key to your
android:layout_margin except that it specifies the This places the view vertically in the center of the application will expire, leaving your application
extra space inside the view parent. Since the parent view covers the whole inaccessible. The default validity for a key is 25
android:layout_gravity : This specifies how child screen of mobile hence the view gets placed in the years.
Views are positioned(left,right, center, center- middle of the mobile screen vertically. (See the blue For each key that you generate, you’re given a
horizontal) android:layout_weight : This specifies view in the above figure) certificate that contains all the information about you
how much of the extra space in the layout should be android:layout_centerInParent="true" and your company. You don't necessarily have to fill
allocated to the view This attribute will place the view in the center of the in all the details—just choose the ones you think
android:layout_x : This specifies the x-coordinate of parent. Since the parent in our example covers the should go on your certificate. A key will still be
the layout whole screen of mobile, so the view gets placed in generated, even without filling in each field of the
android:layout_y : This specifies the y-coordinate of the middle of the mobile screen, both horizontally certificate.
the layout and vertically. Finishing Up
Once you have filled in the details for the certificate, 27. Develop an IOS application to calculate static var previews: some View {
select OK. You will then be directed back to the simple interest. ContentView()
Generate Signed Bundle or APK screen. Ans: }
26. Briefly explain ios programming platform? import SwiftUIstruct ContentView: View { }
Ans: @State var intrest="" 28. What is Listview. Write a java class to add any 8
Apple iPhone and iPad products have become the @State var time = "" items within ListView.
standard of mobile smartphones and tablets. Apple @State var principal = "" Ans:
Watch is one of the most-sold smartwatches in the @State var result="0.00" Android ListView is a view which groups several
world. All of these Apple devices are powered by var body: some View { items and display them in vertical scrollable list. The
Apple’s operating system, iOS. VStack{ list items are automatically inserted to the list using
The most popular programming languages used to VStack{ an Adapter that pulls content from a source such as
develop iOS apps. Text("Simple Interest an array or database.
a. Objective-C:- Objective-C was developed by Tom Calculator!").font(.title).bold().padding() //activity_lab5a_listview.xml
Love and Brad Cox in 1984. Prior to Apple HStack{ <?xml version="1.0" encoding="utf-8"?>
launching Swift in 2014, Objective C was the primary Text("Result : <LinearLayout
language of Apple iOS mobile apps. Objective C is a ").font(/*@START_MENU_TOKEN@*/.title/*@END_ xmlns:android="http://schemas.android.com/apk/res/
general-purpose, object-oriented programming MENU_TOKEN@*/).bold() Image("icons8-us-dollar- android"
language that brings Smalltalk flavor to C 64") xmlns:app="http://schemas.android.com/apk/res-
programming language. Message passing among Text(result).font(.title).bold() auto"
objects is a key feature of Objective-C that became .background(Color.white) xmlns:tools="http://schemas.android.com/tools"
really useful for Apple iOS operating systems. .foregroundColor(.green) android:layout_width="match_parent"
Today, Swift has taken over Objective-C in popularity } .frame(alignment: .center) android:layout_height="match_parent"
and usefulness. } tools:context=".lab5a_listview"
Objective-C is a superset of the C programming VStack { android:orientation="vertical">
language and provides object-oriented capabilities TextField("Principal Amount($0.00)", text: $principal) <ListView
and a dynamic runtime. Objective-C inherits the .padding() android:layout_width="match_parent"
syntax, primitive types, and flow control statements .keyboardType(.decimalPad) android:layout_height="match_parent"
of C and adds syntax for defining classes and .background(LinearGradient(gradient: android:divider="@color/purple_200"
methods. It also adds language-level support for Gradient(colors: android:dividerHeight="2dp"
object graph management and object literals while [Color.white, Color.white]), startPoint: .topLeading, android:id="@+id/mylist"/>
providing dynamic typing and binding, deferring endPoint: .bottomTrailing)) </LinearLayout>
many responsibilities until runtime. .cornerRadius(5) //lab5a_list_item.xml
b. Swift:- Swift is the primary programming language .shadow(color: .gray, radius: 8).padding() <?xml version="1.0" encoding="utf-8"?>
of the iOS operating system. Swift was developed <LinearLayout
and launched by Apple in 2014. In Dec 2015, Apple TextField("Rate(%)", text: $intrest) xmlns:android="http://schemas.android.com/apk/res/
open-sourced Swift under the Apache License 2.0. .padding() android"
Besides iOS, Swift is also a programming language .keyboardType(.decimalPad) android:layout_width="match_parent"
of macOS, watchOS, tvOS, Linux and z/OS. Prior to .background(LinearGradient(gradient: android:layout_height="match_parent"
Swift, Objective-C was the primary language for iOS Gradient(colors: android:orientation="vertical">
development. Objective C being 30 years old, the [Color.white, Color.white]), startPoint: .topLeading, <TextView
language did not support modern needs. Swift is a endPoint: .bottomTrailing)) android:layout_width="match_parent"
modern programming language that provides .cornerRadius(5) android:layout_height="wrap_content"
modern language features such as dynamic, safe, .shadow(color: .gray, radius: 8).padding() android:textSize="20sp"
late binding, and extensibility. TextField("Time(Years)", text: $time) android:textStyle="bold"
c. C#:- The C# language was created by Anders .padding() android:layout_margin="10dp"
Hejlsberg at Microsoft and launched in 2000. C# is a .keyboardType(.decimalPad) android:id="@+id/listtext"/>
simple, modern, flexible, object-oriented, safe, and .background(LinearGradient(gradient: </LinearLayout>
open source programming language. C# is one of Gradient(colors: //lab5a_listview.java
the most versatile programming languages in the [Color.white, Color.white]), startPoint: .topLeading, package com.example.lab5;
world. endPoint: .bottomTrailing)) import androidx.appcompat.app.AppCompatActivity;
C# allows developers to build all kind of applications .cornerRadius(5) import android.os.Bundle;
including Windows clients, consoles, Web apps, .shadow(color: .gray, radius: 8).padding() import android.view.View;
mobile apps, and backend systems. } import android.widget.AdapterView;
C# developers can build native iOS and Android VStack{ import android.widget.ArrayAdapter;
mobile apps with the help of Xamarin. Xamarin is a HStack{ import android.widget.ListView;
tool as a part of Visual Studio which allows Button(action: Calculate) { import android.widget.Toast;
developers to write C# code that is compiled to Text("Calculate!" ).font(.title).padding() public class lab5a_listview extends
native iOS and native Android binaries. These .frame(width: 160, height: 55, alignment: .center) AppCompatActivity {
binaries work exactly as any native app written using .background(Color.green) ListView list;
other iOS and Android languages, such as Swift or .foregroundColor(.white) @Override
Kotlin. .clipShape(Capsule()) } protected void onCreate(Bundle
d. Python:- Python is one of the most popular Button(action: Reset) { savedInstanceState) {
programming languages of recent times. Python, Text("Reset!" ).font(.title).padding() super.onCreate(savedInstanceState);
created by Guido van Rossum in 1991, is an open- .frame(width: 160, height: 55, alignment: .center) setContentView(R.layout.activity_lab5a_listview);
source, high-level, general-purpose programming .background(Color.green) list=findViewById(R.id.mylist);
language. Python is a dynamic programming .foregroundColor(.white) String
language which supports object-oriented, imperative, .clipShape(Capsule()) } program[]={"C","C#","PHP","Python","Java","Kotlin","
functional and procedural development paradigms. } Ruby","ASP.NET"}; final ArrayAdapter adapter=new
Python is very popular in machine learning } ArrayAdapter<String>(this,R.layout.lab5a_list_item,R
programming. In iOS app development, Python can Spacer() .id.listtext,program);
be used to create libraries, functions, and back end } list.setAdapter(adapter);
processing tasks. } list.setOnItemClickListener(new
e. C++:- C++ is one of the oldest and most popular func Calculate() { AdapterView.OnItemClickListener() {
programming languages. In Android development, let timeData = Float(time) ?? 0.0 @Override
C++ is used to build APIs and backend tasks. There let intrestData = Float(intrest) ?? 0.0 public void onItemClick(AdapterView<?>
are several popular built-in C++ libraries available let principalData = Float(principal) ?? 0.0 adapterView, View view, int position, long l) { String
for iOS developers to use in their apps. val=(String) adapter.getItem(position);
f. HTML 5:- HTML 5 combines with CSS and other let resultData = principalData * ( 1 + ((timeData/100) Toast.makeText(lab5a_listview.this, "Listitem is
technologies can be used to build iOS hybrid apps. * intrestData)) result = String(format: "%.2f", clicked",
These apps are not native apps. Hybrid apps wrap resultData) Toast.LENGTH_SHORT).show();
around a browser control and use HTML and CSS }func Reset() { }
to render pages within the apps. principal = "" });
time = "" }
intrest="" }
result = String(format: "%.2f", 0.0)
}
}struct ContentView_Previews: PreviewProvider {
29. Develop an android application to String query="CREATE TABLE Student(id btn.setOnClickListener(new View.OnClickListener()
demonstrate basic CRUD operation using INTEGER PRIMARY KEY,name TEXT, address {
SQLLite. Ans: TEXT)"; @Override
activity_main.xml db.execSQL(query); public void onClick(View v) {
<?xml version="1.0" encoding="utf-8"?> } int id=Integer.parseInt(edtid.getText().toString());
<RelativeLayout @Override
xmlns:android="http://schemas.android.com/apk/res/ public void onUpgrade(SQLiteDatabase db, int db.insertData(id,edtname.getText().toString(),edtadd
android" oldVersion, int newVersion) { db.execSQL("DROP ress.getText().toString());
xmlns:app="http://schemas.android.com/apk/res- TABLE IF EXISTS "+ Database_name); Toast.makeText(MainActivity.this,"Inset
auto" onCreate(db);} successfully",Toast.LENGTH_LONG).show();
xmlns:tools="http://schemas.android.com/tools" public void insertData(int id,String name, String edtid.setText("");
android:layout_width="match_parent" address) edtname.setText("");
android:layout_height="match_parent" { edtaddress.setText("");
android:layout_margin="3dp" SQLiteDatabase db=this.getWritableDatabase(); } });
android:orientation="vertical" ContentValues contentValues=new btn1.setOnClickListener(new View.OnClickListener()
tools:context=".MainActivity"> ContentValues(); {
<EditText contentValues.put("id",id); @Override
android:id="@+id/idval" contentValues.put("name",name); public void onClick(View v) {
android:layout_width="match_parent" contentValues.put("address",address); int id=0;
android:layout_height="wrap_content" db.insert("Student",null,contentValues); String name="",address="";
android:hint="Enter id of student" db.close(); } Cursor cursor=db.SelectData();
android:inputType="number" public Cursor SelectData(){ while (cursor.moveToNext()){
/> SQLiteDatabase db=this.getReadableDatabase(); id=cursor.getInt(0);
<EditText String query="SELECT * FROM STUDENT"; name=cursor.getString(1);
android:id="@+id/nameval" Cursor cursor=db.rawQuery(query,null); address=cursor.getString(2);
android:layout_width="match_parent" return cursor; }
android:layout_height="wrap_content" }
android:hint="Enter name " public void updateData(String id, String name, res.setText("ID="+id+"Name="+name+"Address="+a
android:layout_below="@+id/idval" /> String address) ddress);
<EditText { }
android:id="@+id/addrval" SQLiteDatabase db=this.getWritableDatabase(); });
android:layout_width="match_parent" ContentValues contentValues=new btnupdate.setOnClickListener(new
android:layout_height="wrap_content" ContentValues(); View.OnClickListener() {
android:hint="Enter address" contentValues.put("name",name); @Override
android:layout_below="@+id/nameval" <Button contentValues.put("address",address); public void onClick(View v) {
android:id="@+id/insert" db.update("Student",contentValues,"id=?",new String id=edtid.getText().toString();
android:layout_width="wrap_content" String[]{id}); String name=edtname.getText().toString();
android:layout_height="wrap_content" } String address=edtaddress.getText().toString();
android:textSize="14sp" public void deleteData(String id) db.updateData(id,name,address);
android:layout_below="@+id/addrval" { Toast.makeText(MainActivity.this,"Update
android:text="Insert" SQLiteDatabase db=this.getWritableDatabase(); successfully",Toast.LENGTH_LONG).show(); }
/> db.delete("Student","id=?",new String[]{id}); } });
<Button } btndelete.setOnClickListener(new
android:id="@+id/select" //MainActivity.java View.OnClickListener() {
android:layout_width="wrap_content" public class MainActivity extends AppCompatActivity @Override
android:layout_height="wrap_content" { DatabaseHelper db; public void onClick(View v) {
android:textSize="14sp" EditText edtid,edtname,edtaddress; String id=edtid.getText().toString();
android:layout_below="@+id/addrval" Button btn, btn1,btnupdate,btndelete; db.deleteData(id);
android:layout_toRightOf="@+id/insert" TextView res; Toast.makeText(MainActivity.this,"delete
android:text="Select" @Override successfully",Toast.LENGTH_LONG).show(); }
/> protected void onCreate(Bundle });
<Button savedInstanceState) { }
android:id="@+id/update" super.onCreate(savedInstanceState); }
android:layout_width="wrap_content" setContentView(R.layout.activity_main); db=new
android:layout_height="wrap_content" DatabaseHelper(this); 30. Develop an android application to calculate
android:textSize="14sp“ edtid=findViewById(R.id.idval); simple interest. Your application should contains
android:layout_below="@+id/addrval" edtname=findViewById(R.id.nameval); fields to input principal, Rate and Time and
android:layout_toRightOf="@+id/select" edtaddress=findViewById(R.id.addrval); button for calculating Simple interest. Display
android:layout_centerHorizontal="false" btn=findViewById(R.id.insert); result in a Text View.
android:text="update" btn1=findViewById(R.id.select); Ans:
/> res=findViewById(R.id.Result); //Activity_main.xml File
<Button btnupdate=findViewById(R.id.update); <?xml version="1.0" encoding="utf-8"?>
android:id="@+id/delete" btndelete=findViewById(R.id.delete); <LinearLayout
android:layout_width="wrap_content" btn.setOnClickListener(new View.OnClickListener() xmlns:android="http://schemas.android.com/apk/res/
android:layout_height="wrap_content" { @Override android"
android:textSize="14sp" public void onClick(View v) { xmlns:app="http://schemas.android.com/apk/res-
android:layout_below="@+id/addrval" int id=Integer.parseInt(edtid.getText().toString()); auto"
android:layout_toRightOf="@+id/update" public class MainActivity extends AppCompatActivity xmlns:tools="http://schemas.android.com/tools"
android:text="del" { DatabaseHelper db; android:layout_width="match_parent"
/> EditText edtid,edtname,edtaddress; android:layout_height="match_parent"
<TextView Button btn, btn1,btnupdate,btndelete; android:orientation="vertical"
android:id="@+id/Result" TextView res; tools:context=".MainActivity">
android:layout_width="match_parent" @Override <TextView
android:layout_height="wrap_content" protected void onCreate(Bundle android:layout_width="fill_parent"
android:layout_below="@+id/insert" savedInstanceState) { android:layout_height="wrap_content"
android:textSize="20sp"/> super.onCreate(savedInstanceState); android:text="SImple Calculator"
</RelativeLayout> setContentView(R.layout.activity_main); db=new android:textAlignment="center"
//DatabaseHelper.java DatabaseHelper(this); android:textSize="30dp" />
public class DatabaseHelper extends edtid=findViewById(R.id.idval); <TextView
SQLiteOpenHelper { edtname=findViewById(R.id.nameval); android:layout_width="fill_parent"
private static final String Database_name="College"; edtaddress=findViewById(R.id.addrval); android:layout_height="wrap_content"
public DatabaseHelper(@Nullable Context context) { btn=findViewById(R.id.insert); android:text="------------------------------------------"
super(context, Database_name,null,1); btn1=findViewById(R.id.select); android:textAlignment="center"
} res=findViewById(R.id.Result); android:textSize="30dp" />
@Override btnupdate=findViewById(R.id.update); <EditText
public void onCreate(SQLiteDatabase db) { btndelete=findViewById(R.id.delete); android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Amount" 31. Develop an android application which gets android:layout_height="wrap_content"
android:id="@+id/amt" result back from child activity. Ans: android:text="Goto First"
android:textAlignment="center" //activity_first.xml android:textSize="20sp"
android:inputType="number"/> <?xml version="1.0" encoding="utf-8"?> android:layout_gravity="center"
<EditText <LinearLayout />
android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/ </LinearLayout>
android:layout_height="wrap_content" android" SecondActivity.java
android:hint="Enter Interest Rate (In %)" xmlns:app="http://schemas.android.com/apk/res- public class SecondActivity extends
android:id="@+id/interest" auto" AppCompatActivity {
android:textAlignment="center" xmlns:tools="http://schemas.android.com/tools" @Override
android:inputType="number"/> android:layout_width="match_parent" protected void onCreate(Bundle
android:layout_height="match_parent" savedInstanceState) {
<EditText android:orientation="vertical" super.onCreate(savedInstanceState);
android:layout_width="fill_parent" tools:context=".FirstActivty"> setContentView(R.layout.activity_second);
<TextView Button bt=(Button)findViewById(R.id.Btn_second);
android:layout_height="wrap_content" android:layout_width="wrap_content" bt.setOnClickListener(new View.OnClickListener() {
android:hint="Enter Time (in Year)" android:layout_height="wrap_content" @Override
android:id="@+id/tim" android:text="This is First activity" public void onClick(View v) {
android:textAlignment="center" android:layout_marginTop="100dp" Intent i= new Intent();
android:inputType="number" /> android:textSize="20sp" i.putExtra("message","Hello First activity, this is
<Button android:textStyle="bold" message from second"); setResult(2,i);
android:layout_width="wrap_content" android:layout_gravity="center" finish();
android:layout_height="wrap_content" android:id="@+id/text1"/> }
android:text="Calculate" <Button });
android:id="@+id/btn" /> android:id="@+id/Btn2" }
<TextView android:layout_width="wrap_content" 32. Develop an android application to calculate
android:layout_width="fill_parent" android:layout_height="wrap_content" simple interest (SI) in custom dialog box Ans:
android:layout_height="wrap_content" android:text="Go to Second" /activity_lab4c
android:id="@+id/txt1" android:textSize="20sp" <?xml version="1.0" encoding="utf-8"?>
android:textSize="30dp" /> android:layout_gravity="center"/> <LinearLayout
</LinearLayout> xmlns:android="http://schemas.android.com/apk/res/
<TextView //FirstActivity.java android"
android:layout_width="fill_parent" public class FirstActivty extends AppCompatActivity { xmlns:app="http://schemas.android.com/apk/res-
android:layout_height="wrap_content" Button b; auto"
android:id="@+id/txt2" TextView txt; xmlns:tools="http://schemas.android.com/tools"
android:textSize="20dp" /> @Override android:layout_width="match_parent"
</LinearLayout> protected void onCreate(Bundle android:layout_height="match_parent"
//MainActivity.Java File savedInstanceState) { tools:context=".lab4c">
package com.irawen.simpleinterest; super.onCreate(savedInstanceState); <Button
import android.support.v7.app.AppCompatActivity; setContentView(R.layout.activity_first); android:id="@+id/dialogbtn"
import android.os.Bundle; b=(Button) findViewById(R.id.Btn2); android:layout_width="wrap_content"
import android.view.View; txt=(TextView)findViewById(R.id.text1); android:layout_height="wrap_content"
import android.widget.Button; b.setOnClickListener(new View.OnClickListener() { android:text="Calculate Interest"
import android.widget.EditText; @Override android:textStyle="bold"
import android.widget.TextView; public void onClick(View v) { android:textSize="20sp"
public class MainActivity extends AppCompatActivity Intent i=new Intent(FirstActivty.this, android:layout_marginTop="40dp"
{ @Override protected void onCreate(Bundle SecondActivity.class); startActivityForResult(i,2); android:layout_gravity="center" />
savedInstanceState) { } </LinearLayout>
super.onCreate(savedInstanceState); }); //lab4c_second
setContentView(R.layout.activity_main); } <?xml version="1.0" encoding="utf-8"?>
OnCLick(); @Override <LinearLayout
} protected void onActivityResult(int requestCode, int xmlns:android="http://schemas.android.com/apk/res/
EditText amt,interest,time; resultCode, @Nullable Intent data) { android" android:layout_width="match_parent"
Button btn; super.onActivityResult(requestCode, resultCode, android:layout_height="match_parent"
TextView txt1,txt2; data); android:orientation="vertical">
public void OnCLick() if(requestCode==2) <EditText
{ { android:layout_width="match_parent"
amt=(EditText)findViewById(R.id.amt); String message=data.getStringExtra("message"); android:layout_height="wrap_content"
interest=(EditText)findViewById(R.id.interest); txt.setText(message); android:hint="Enter Principal"
time=(EditText)findViewById(R.id.tim); } android:inputType="number"
btn=(Button)findViewById(R.id.btn); } android:id="@+id/principal" />
txt1=(TextView)findViewById(R.id.txt1); } <EditText
txt2=(TextView)findViewById(R.id.txt2); //activity_second.xml android:layout_width="match_parent"
btn.setOnClickListener(new View.OnClickListener() <?xml version="1.0" encoding="utf-8"?> android:layout_height="wrap_content"
{ <LinearLayout android:hint="Enter Time"
@Override public void onClick(View v) { xmlns:android="http://schemas.android.com/apk/res/ android:inputType="number"
int a=Integer.parseInt(amt.getText().toString()); android" android:id="@+id/time" />
int b=Integer.parseInt(interest.getText().toString()); xmlns:app="http://schemas.android.com/apk/res- <EditText
int c=Integer.parseInt(time.getText().toString()); auto" android:layout_width="match_parent"
int d; xmlns:tools="http://schemas.android.com/tools" android:layout_height="wrap_content"
d=(a*b*c)/100; android:layout_width="match_parent" android:hint="Enter Rate"
int e=a+d; android:layout_height="match_parent" android:inputType="number"
txt1.setText("Total Interest Is :"+String.valueOf(d)); android:orientation="vertical" android:id="@+id/rate"
txt2.setText("Total Amount is : "+String.valueOf(e)); tools:context=".SecondActivity"> />
} <TextView <Button
}); android:id="@+id/rtext" android:layout_width="wrap_content"
} android:layout_width="wrap_content" android:layout_height="wrap_content"
} android:layout_height="wrap_content" android:layout_gravity="center"
android:text="This is Second Activity" android:text="Interest"
android:textStyle="bold" android:id="@+id/interest"/>
android:textSize="30sp" <TextView
android:layout_gravity="center" android:layout_width="wrap_content"
android:layout_marginTop="100dp" android:layout_height="wrap_content"
/> android:text="Result:"
<Button android:textSize="20sp"
android:id="@+id/Btn_second" android:layout_gravity="center"
android:layout_width="wrap_content" android:layout_marginTop="20dp"
android:id="@+id/result"/> android:layout_margin="5dp"
</LinearLayout> android:orientation="vertical" 34. Develop an android application to input your
//lab4c.java tools:context=".SendData"> Name, address, gender, hobbies, country and
package com.example.lab4; <EditText other personal information and display this
import androidx.appcompat.app.AlertDialog; android:id="@+id/edtid" message in toast message. . Ans:-
import androidx.appcompat.app.AppCompatActivity; android:layout_width="match_parent" //lab2c.xml
import android.os.Bundle; android:layout_height="wrap_content" <?xml version="1.0" encoding="utf-8"?>
import android.view.LayoutInflater; android:hint="Enter id" <RelativeLayout
import android.view.View; android:inputType="number"/> xmlns:android="http://schemas.android.com/apk/res/
import android.widget.Button; <EditText android" android:layout_width="match_parent"
import android.widget.EditText; android:id="@+id/edtname" android:layout_height="match_parent">
import android.widget.TextView; android:layout_width="match_parent" <TextView
public class lab4c extends AppCompatActivity { android:layout_height="wrap_content" android:layout_width="wrap_content"
Button b1, binterest; android:hint="Enter name" android:layout_height="wrap_content"
EditText t1,t2, t3; android:layout_below="@+id/edtid"/> android:textSize="20sp"
TextView result; android:text="Registration Form"
@Override <EditText android:layout_gravity="center"
protected void onCreate(Bundle android:id="@+id/edtaddress" android:textStyle="bold"
savedInstanceState) { android:layout_width="match_parent" android:layout_margin="10dp"
super.onCreate(savedInstanceState); android:layout_height="wrap_content" android:id="@+id/reg" />
setContentView(R.layout.activity_lab4c); android:hint="Enter address" <TextView
b1= findViewById(R.id.dialogbtn); android:layout_below="@+id/edtname"/> android:layout_width="wrap_content"
b1.setOnClickListener(new View.OnClickListener() { <Button android:layout_height="wrap_content"
@Override android:id="@+id/sendbtn" android:textSize="20sp"
public void onClick(View v) { android:layout_width="wrap_content" android:text="Name"
AlertDialog.Builder builder= new android:layout_height="wrap_content" android:layout_margin="10dp"
AlertDialog.Builder(lab4c.this); android:text="Submit" android:id="@+id/name"
builder.setTitle("Calculate Interest"); android:layout_below="@+id/edtaddress" android:layout_below="@id/reg"/> <EditText
builder.setCancelable(true); android:layout_centerHorizontal="true" android:layout_width="match_parent"
//inflate and set layout for the dialog /> android:layout_height="wrap_content"
LayoutInflater inflater=getLayoutInflater(); </RelativeLayout> android:textSize="20sp"
View view // SendData.java android:inputType="text"
=inflater.inflate(R.layout.lab4c_second,null); public class SendData extends AppCompatActivity { android:id="@+id/text1"
builder.setView(view); EditText edtId,edtName,edtAddress; android:layout_below="@id/reg"
t1=view.findViewById(R.id.principal); Button sendbtn; android:layout_toRightOf="@id/name"/> <TextView
t2=view.findViewById(R.id.time); @Override android:layout_width="wrap_content"
t3=view.findViewById(R.id.rate); protected void onCreate(Bundle android:layout_height="wrap_content"
result=view.findViewById(R.id.result); savedInstanceState) { android:textSize="20sp"
binterest=view.findViewById(R.id.interest); super.onCreate(savedInstanceState); android:text="Address"
binterest.setOnClickListener(new setContentView(R.layout.activity_send_data); android:layout_margin="10dp"
View.OnClickListener() { edtId=findViewById(R.id.edtid); android:id="@+id/address"
@Override edtName=findViewById(R.id.edtname); android:layout_below="@id/name"/> <EditText
public void onClick(View view) { edtAddress=findViewById(R.id.edtaddress); android:layout_width="match_parent"
int num1=Integer.parseInt(t1.getText().toString()); sendbtn=findViewById(R.id.sendbtn); android:layout_height="wrap_content"
int num2=Integer.parseInt(t2.getText().toString()); sendbtn.setOnClickListener(new android:inputType="text"
int num3=Integer.parseInt(t3.getText().toString()); View.OnClickListener() { @Override android:textSize="20sp"
int interest=(num1*num2*num3)/100; public void onClick(View v) { android:id="@+id/text2"
result.setText("Result="+interest); volleyRequest(); android:layout_below="@id/name"
} android:layout_toRightOf="@+id/address"/>
}); } <TextView
AlertDialog alert=builder.create(); }); android:layout_width="wrap_content"
alert.show(); } android:layout_height="wrap_content"
} public void volleyRequest() android:textSize="20sp"
}); { android:text="Email"
} RequestQueue queue= android:layout_margin="10dp"
} Volley.newRequestQueue(this); android:id="@+id/email"
33. Develop and android application to String url="http://10.0.2.2/JSONEX/setdata.php"; android:layout_below="@id/address"/> <EditText
demonstrate sending of content to remote StringRequest android:layout_width="match_parent"
server. Ans: stringRequest=newStringRequest(Request.Method.P android:layout_height="wrap_content"
//Setdata.php OST, url, new Response.Listener<String>() { android:inputType="text"
<?php android:textSize="20sp"
$id=$_POST['id']; @Override android:id="@+id/text3"
$name=$_POST['name']; public void onResponse(String response) { android:layout_below="@id/address"
$address=$_POST['address']; android:layout_toRightOf="@+id/email"/> <TextView
$conn=new mysqli("localhost","root","","College"); Toast.makeText(SendData.this,response,Toast.LEN android:layout_width="wrap_content"
if ($conn->connect_error) { GTH_LONG).show(); } android:layout_height="wrap_content"
die("Connection failed:".$conn->connect_error); }, new Response.ErrorListener() { android:text="Gender"
} @Override android:layout_margin="10dp"
$sql="INSERT INTO Student VALUES public void onErrorResponse(VolleyError error) { android:textSize="20sp"
('$id','$name','$address')"; Log.d("Exception",error.toString()); android:id="@+id/gender"
$result=$conn->query($sql); } android:layout_below="@id/email"/> <RadioGroup
if ($result>0) }){ android:layout_width="match_parent"
echo "Data insert successfully"; protected HashMap<String, String> getParams(){ android:layout_height="wrap_content"
else HashMap<String,String> params=new android:orientation="horizontal"
echo "Error in insertion data"; HashMap<>(); android:layout_below="@id/email"
$conn->close(); params.put("id",edtId.getText().toString()); android:layout_toRightOf="@+id/gender">
?> params.put("name",edtName.getText().toString()); <RadioButton
//Activity_senddata.xml android:layout_width="wrap_content"
<?xml version="1.0" encoding="utf-8"?> params.put("address",edtAddress.getText().toString( android:layout_height="wrap_content"
<RelativeLayout )); android:text="Male"
xmlns:android="http://schemas.android.com/apk/res/ return params; android:textStyle="normal"
android" } android:textSize="20sp"
xmlns:app="http://schemas.android.com/apk/res- }; android:id="@+id/radio1"/>
auto" queue.add(stringRequest); <RadioButton
xmlns:tools="http://schemas.android.com/tools" } android:layout_width="wrap_content"
android:layout_width="match_parent" } android:layout_height="wrap_content"
android:layout_height="match_parent" android:text="Female"
android:textStyle="normal" Toast.makeText(getApplicationContext(), <fragment
android:textSize="20sp" "registration successful", android:name="com.example.unit5.FirstFragment"
android:id="@+id/radio2"/> Toast.LENGTH_SHORT).show(); } android:layout_width="match_parent"
</RadioGroup> } android:layout_height="wrap_content"
<TextView 35. Develop an android app to add two fragment in android:layout_weight="1"
android:layout_width="match_parent" activity in statically and dynamically Ans: android:id="@+id/fragment1" />
android:layout_height="wrap_content" Statically <fragment
android:text="Hobbies" //fragment_first.xml
android:textSize="20sp" <?xml version="1.0" encoding="utf-8"?> android:name="com.example.unit5.SecondFragment
android:layout_margin="10dp" <LinearLayout " android:layout_width="match_parent"
android:id="@+id/hobby" xmlns:android="http://schemas.android.com/apk/res/ android:layout_height="wrap_content"
android:layout_below="@id/gender"/> <CheckBox android" android:layout_weight="1"
android:id="@+id/check1" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/fragment2"/>
android:layout_width="match_parent" android:layout_width="match_parent" </LinearLayout>
android:layout_height="wrap_content" android:layout_height="match_parent" //MainActivity.java
android:layout_below="@id/hobby" android:orientation="vertical" package com.example.unit5;
android:onClick="checkItem" tools:context=".FirstFragment"> import androidx.appcompat.app.AppCompatActivity;
android:text="playing" <TextView import androidx.fragment.app.Fragment;
android:textSize="20sp" android:layout_width="match_parent" import androidx.fragment.app.FragmentTransaction;
android:textStyle="normal" /> android:layout_height="match_parent" import android.os.Bundle;
<CheckBox android:text="This is first fragment." public class MainActivity extends AppCompatActivity
android:layout_width="match_parent" android:textColor="@color/teal_700" {
android:layout_height="wrap_content" android:background="@color/teal_200" @Override
android:text="travelling" android:textStyle="bold" protected void onCreate(Bundle
android:textSize="20sp" android:gravity="center"/> savedInstanceState) {
android:textStyle="normal" </LinearLayout> super.onCreate(savedInstanceState);
android:onClick="checkItem" //fragment_second.xml setContentView(R.layout.activity_main); }
android:id="@+id/check2" <?xml version="1.0" encoding="utf-8"?> }
android:layout_below="@id/check1"/> <CheckBox <LinearLayout Dynamically
android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/ //fragment_first.xml
android:layout_height="wrap_content" android" <?xml version="1.0" encoding="utf-8"?>
android:text="reading" xmlns:tools="http://schemas.android.com/tools" <LinearLayout
android:textSize="20sp" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/
android:textStyle="normal" android:layout_height="match_parent" android"
android:onClick="checkItem" android:orientation="vertical" xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/check3" tools:context=".SecondFragment"> android:layout_width="match_parent"
android:layout_below="@id/check2"/> <TextView <TextView android:layout_height="match_parent"
android:layout_width="wrap_content" android:layout_width="match_parent" android:orientation="vertical"
android:layout_height="wrap_content" android:layout_height="match_parent" tools:context=".FirstFragment">
android:text="Country" android:text="This is the second fragment." <TextView
android:textSize="20sp" android:textColor="@color/teal_700" android:layout_width="match_parent"
android:layout_margin="10dp" android:background="@color/purple_200" android:layout_height="match_parent"
android:id="@+id/country" android:textStyle="bold" android:text="This is first fragment."
android:layout_below="@id/check3"/> <Spinner android:gravity="center"/> android:textColor="@color/teal_700"
android:layout_width="wrap_content" </LinearLayout> android:background="@color/teal_200"
android:layout_height="wrap_content" //FirstFragment.java android:textStyle="bold"
android:entries="@array/country_name" package com.example.unit5; android:gravity="center"/>
android:spinnerMode="dropdown" import android.os.Bundle; </LinearLayout>
android:layout_margin="10dp" import androidx.fragment.app.Fragment; //fragent_second.xml
android:layout_toRightOf="@+id/country" import android.view.LayoutInflater; <?xml version="1.0" encoding="utf-8"?>
android:layout_below="@id/check3" import android.view.View; <LinearLayout
android:id="@+id/spinner"/> import android.view.ViewGroup; xmlns:android="http://schemas.android.com/apk/res/
<Button public class FirstFragment extends Fragment { android"
android:layout_width="wrap_content" @Override xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content" public View onCreateView(LayoutInflater inflater, android:layout_width="match_parent"
android:text="Register" ViewGroup container, Bundle savedInstanceState) { android:layout_height="match_parent"
android:textSize="20sp" // Inflate the layout for this fragment android:orientation="vertical"
android:layout_gravity="center" View v= inflater.inflate(R.layout.fragment_first, tools:context=".SecondFragment">
android:onClick="Register" container, false); return v; } <TextView
android:id="@+id/btn" } android:layout_width="match_parent"
android:layout_below="@+id/country"/> //SecondFragment.java android:layout_height="match_parent"
</RelativeLayout> package com.example.unit5; android:text="This is the second fragment."
//MainActivity.java import android.os.Bundle; android:textColor="@color/teal_700"
package com.example.lab; import androidx.fragment.app.Fragment; android:background="@color/purple_200"
import androidx.appcompat.app.AppCompatActivity; import android.view.LayoutInflater; android:textStyle="bold"
import android.os.Bundle; import android.view.View; android:gravity="center"/>
import android.view.View; import android.view.ViewGroup; </LinearLayout>
import android.widget.Button; public class SecondFragment extends Fragment { //FirstFragment.java
import android.widget.CheckBox; @Override package com.example.unit5;
import android.widget.EditText; public View onCreateView(LayoutInflater inflater, import android.os.Bundle;
import android.widget.TextView; ViewGroup container, Bundle savedInstanceState) { import androidx.fragment.app.Fragment;
import android.widget.Toast; // Inflate the layout for this fragment import android.view.LayoutInflater;
public class MainActivity extends AppCompatActivity View v1= inflater.inflate(R.layout.fragment_second, import android.view.View;
{ container, false); return v1; } import android.view.ViewGroup;
EditText t1, t2; } public class FirstFragment extends Fragment {
CheckBox c1, c2, c3; //activity_main.xml @Override
@Override <?xml version="1.0" encoding="utf-8"?> public View onCreateView(LayoutInflater inflater,
protected void onCreate(Bundle <LinearLayout ViewGroup container, Bundle savedInstanceState) {
savedInstanceState) { xmlns:android="http://schemas.android.com/apk/res/ // Inflate the layout for this fragment
super.onCreate(savedInstanceState); android" View v= inflater.inflate(R.layout.fragment_first,
setContentView(R.layout.lab2c); } xmlns:app="http://schemas.android.com/apk/res- container, false); return v; }
public void checkItem(View v) { auto" }
Toast.makeText(getApplicationContext(), "checkbox xmlns:tools="http://schemas.android.com/tools" //SecondFragment.java
selected", android:orientation="vertical" package com.example.unit5;
Toast.LENGTH_SHORT).show(); } android:layout_width="match_parent" import android.os.Bundle;
public void Register(View v) { android:layout_height="match_parent" import androidx.fragment.app.Fragment;
tools:context=".MainActivity"> import android.view.LayoutInflater;
import android.view.View; import gap analysis, the current quality management
import android.view.ViewGroup; com.google.android.gms.maps.SupportMapFragmen systems qms are assessed, becoming the old
public class SecondFragment extends Fragment { t; system and being compared to the new ISO 9001
@Override import com.google.android.gms.maps.model.LatLng; system.
public View onCreateView(LayoutInflater inflater, import Completing this analysis allows the business owner
ViewGroup container, Bundle savedInstanceState) { com.google.android.gms.maps.model.MarkerOptions and personnel to see the differences between their
// Inflate the layout for this fragment ; current system and the old; hence move toward their
View v1= inflater.inflate(R.layout.fragment_second, import goal of continual improvement. These assessments
container, false); return v1; } com.example.googlemap.databinding.ActivityMapsBi are done in the beginning stages of ISO 9001
} nding; implementation.
//activity_main.xml public class MapsActivity extends FragmentActivity Any business that wants to implement ISO 9001
<?xml version="1.0" encoding="utf-8"?> implements OnMapReadyCallback { private 2015 is required to conduct internal audits. Doing
<LinearLayout GoogleMap mMap; this helps you evaluate how well the new quality
xmlns:android="http://schemas.android.com/apk/res/ private ActivityMapsBinding binding; management system works and assess whether
android" @Override your business qualifies for certification. This is all
xmlns:app="http://schemas.android.com/apk/res- protected void onCreate(Bundle because ISO 9001 was designed to help business
auto" savedInstanceState) { owners take action towards better quality assurance
xmlns:tools="http://schemas.android.com/tools" super.onCreate(savedInstanceState); through the application of ISO. For additional
android:orientation="vertical" binding = opportunities for improvement that go beyond ISO
android:layout_width="match_parent" ActivityMapsBinding.inflate(getLayoutInflater()); 9001, you can use ISO 9004. However, the only
android:layout_height="match_parent" setContentView(binding.getRoot()); standard that has a certification body is ISO 9001.
tools:context=".MainActivity"> // Obtain the SupportMapFragment and get notified android SQLite database
<LinearLayout when the map is ready to be used. Contact.java
android:layout_width="match_parent" SupportMapFragment mapFragment = package example.javatpoint.com.sqlitetutorial;
android:layout_height="wrap_content" (SupportMapFragment)
android:orientation="vertical" getSupportFragmentManager() public class Contact {
android:layout_weight="1" .findFragmentById(R.id.map); int _id;
android:id="@+id/layout1"/> mapFragment.getMapAsync(this); String _name;
<LinearLayout } String _phone_number;
android:layout_width="match_parent" @Override public Contact(){ }
android:layout_height="wrap_content" public void onMapReady(GoogleMap googleMap) { public Contact(int id, String name, String
android:layout_weight="1" mMap = googleMap; _phone_number){
android:orientation="vertical" // Add a marker in Sydney and move the camera this._id = id;
android:id="@+id/layout2"/> LatLng location = new this._name = name;
</LinearLayout> LatLng(27.6794985,85.3143896); this._phone_number = _phone_number;
//MainActivity.java mMap.addMarker(new }
package com.example.unit5; MarkerOptions().position(location).title("
import androidx.appcompat.app.AppCompatActivity; Patandhoka")); public Contact(String name, String
import androidx.fragment.app.Fragment; mMap.moveCamera(CameraUpdateFactory.newLat _phone_number){
import androidx.fragment.app.FragmentTransaction; Lng(location)); this._name = name;
import android.os.Bundle; this._phone_number = _phone_number;
public class MainActivity extends AppCompatActivity mMap.animateCamera(CameraUpdateFactory.zoom }
{ To(12.0f)); public int getID(){
@Override } return this._id;
protected void onCreate(Bundle } }
savedInstanceState) { ISO 9000
super.onCreate(savedInstanceState); ISO 9000 is a quality system made up of a family of public void setID(int id){
setContentView(R.layout.activity_main); standards. There are many individual standards this._id = id;
FirstFragment f1= new FirstFragment(); grouped into this series, including ISO 9001. Its }
SecondFragment f2=new SecondFragment(); purpose is to define terminology found in the rest of
FragmentTransaction the standards. public String getName(){
ft=getSupportFragmentManager().beginTransaction() Not only does ISO 9000 describe the fundamentals return this._name;
; ft.replace(R.id.layout1,f1); of quality management, but it also includes the }
ft.replace(R.id.layout2,f2); quality management principles which the family of
ft.commit(); } standards is based on: public void setName(String name){
} • Customer focus – Companies should this._name = name;
36. Develop an android application that display understand their customers’ needs, meet their }
Google map. requirements, and exceed expectations.
Ans: • Leadership – A purpose and direction public String getPhoneNumber(){
//Activity_maps.xml need to be established in the company to help return this._phone_number;
<?xml version="1.0" encoding="utf-8"?> employees achieve the company’s objectives. }
<fragment • Peoples Involvement – Every employee
xmlns:android="http://schemas.android.com/apk/res/ in the company should be actively involved to benefit public void setPhoneNumber(String
android" the company entirely. phone_number){
xmlns:map="http://schemas.android.com/apk/res- •Process approach – When activities are viewed as a this._phone_number = phone_number;
auto" process, the desired result is achieved efficiently. }
xmlns:tools="http://schemas.android.com/tools" •System methodology to management – Identifying }
android:id="@+id/map" and understanding processes contributes to effective 1. DatabaseHandler.java
and efficient solutions. 2. package
android:name="com.google.android.gms.maps.Supp •Continual improvement – This should be a example.javatpoint.com.sqlitetutorial;
ortMapFragment" permanent objective of your company. 3.
android:layout_width="match_parent" •Factual approach to decision making – Companies 4. import android.content.ContentValues;
android:layout_height="match_parent" should make decisions after analysing data and 5. import android.content.Context;
tools:context=".MapsActivity" /> information. 6. import android.database.Cursor;
//MapsActivity.java •Equally valuable merchant relationships – After 7. import
package com.example.googlemap; everyone benefits, more value is created. android.database.sqlite.SQLiteDatabase;
import androidx.fragment.app.FragmentActivity; 8. import
import android.os.Bundle; ISO 9001 android.database.sqlite.SQLiteOpenHelper;
import ISO 9001 is an individual standard in the ISO 9000 9. import java.util.ArrayList;
com.google.android.gms.maps.CameraUpdateFacto family. It consists of quality management systems 10. import java.util.List;
ry; requirements for a business that is supplying valued 11.
import com.google.android.gms.maps.GoogleMap; products and services. Personnel will use this quality 12.
import management system qms to maintain a customer 13. public class DatabaseHandler extends
com.google.android.gms.maps.OnMapReadyCallbac focus. SQLiteOpenHelper {
k; To implement the quality management system, both 14. private static final int
a gap analysis and internal audits are required. Its DATABASE_VERSION = 1;
primary purpose is actions to be taken. During the
15. private static final String 71. // return contact 2. package
DATABASE_NAME = "contactsManager"; 72. return contact; example.javatpoint.com.sqlitetutorial;
16. private static final String 73. } 3.
TABLE_CONTACTS = "contacts"; 74. 4. import
17. private static final String KEY_ID = 75. // code to get all contacts in a list view android.support.v7.app.AppCompatActivity;
"id"; 76. public List<Contact> getAllContacts() { 5. import android.os.Bundle;
18. private static final String KEY_NAME = 77. List<Contact> contactList = new 6. import android.util.Log;
"name"; ArrayList<Contact>(); 7. import java.util.List;
19. private static final String KEY_PH_NO 78. // Select All Query 8.
= "phone_number"; 79. String selectQuery = "SELECT * 9. public class MainActivity extends
20. FROM " + TABLE_CONTACTS; AppCompatActivity {
21. public DatabaseHandler(Context 80. 10.
context) { 81. SQLiteDatabase db = 11. @Override
22. super(context, DATABASE_NAME, this.getWritableDatabase(); 12. protected void onCreate(Bundle
null, DATABASE_VERSION); 82. Cursor cursor = savedInstanceState) {
23. //3rd argument to be passed is db.rawQuery(selectQuery, null); 13.
CursorFactory instance 83. super.onCreate(savedInstanceState);
24. } 84. // looping through all rows and 14.
25. adding to list setContentView(R.layout.activity_main);
26. // Creating Tables 85. if (cursor.moveToFirst()) { 15. DatabaseHandler db = new
27. @Override 86. do { DatabaseHandler(this);
28. public void onCreate(SQLiteDatabase 87. Contact contact = new 16.
db) { Contact(); 17. // Inserting Contacts
29. String 88. 18. Log.d("Insert: ", "Inserting ..");
CREATE_CONTACTS_TABLE = "CREATE TABLE " contact.setID(Integer.parseInt(cursor.getString(0))); 19. db.addContact(new Contact("Ravi",
+ TABLE_CONTACTS + "(" 89. "9100000000"));
30. + KEY_ID + " INTEGER contact.setName(cursor.getString(1)); 20. db.addContact(new
PRIMARY KEY," + KEY_NAME + " TEXT," 90. Contact("Srinivas", "9199999999"));
31. + KEY_PH_NO + " TEXT" + contact.setPhoneNumber(cursor.getString(2)); 21. db.addContact(new
")"; 91. // Adding contact to list Contact("Tommy", "9522222222"));
32. 92. contactList.add(contact); 22. db.addContact(new
db.execSQL(CREATE_CONTACTS_TABLE); 93. } while (cursor.moveToNext()); Contact("Karthik", "9533333333"));
33. } 94. } 23.
34. 95. 24. // Reading all contacts
35. // Upgrading database 96. // return contact list 25. Log.d("Reading: ", "Reading all
36. @Override 97. return contactList; contacts..");
37. public void 98. } 26. List<Contact> contacts =
onUpgrade(SQLiteDatabase db, int oldVersion, int 99. db.getAllContacts();
newVersion) { 100. // code to update the single contact 27.
38. // Drop older table if existed 101. public int updateContact(Contact 28. for (Contact cn : contacts) {
39. db.execSQL("DROP TABLE IF contact) { 29. String log = "Id: " + cn.getID() + "
EXISTS " + TABLE_CONTACTS); 102. SQLiteDatabase db = ,Name: " + cn.getName() + " ,Phone: " +
40. this.getWritableDatabase(); 30. cn.getPhoneNumber();
41. // Create tables again 103. 31. // Writing Contacts to log
42. onCreate(db); 104. ContentValues values = new 32. Log.d("Name: ", log);
43. } ContentValues(); 33. }
44. 105. values.put(KEY_NAME, 34. }
45. // code to add the new contact contact.getName()); 35. }
46. void addContact(Contact contact) { 106. values.put(KEY_PH_NO,
47. SQLiteDatabase db = contact.getPhoneNumber());
this.getWritableDatabase(); 107.
48. 108. // updating row
49. ContentValues values = new 109. return
ContentValues(); db.update(TABLE_CONTACTS, values, KEY_ID + "
50. values.put(KEY_NAME, = ?",
contact.getName()); // Contact Name 110. new String[] {
51. values.put(KEY_PH_NO, String.valueOf(contact.getID()) });
contact.getPhoneNumber()); // Contact Phone 111. }
52. 112.
53. // Inserting Row 113. // Deleting single contact
54. db.insert(TABLE_CONTACTS, null, 114. public void deleteContact(Contact
values); contact) {
55. //2nd argument is String containing 115. SQLiteDatabase db =
nullColumnHack this.getWritableDatabase();
56. db.close(); // Closing database 116. db.delete(TABLE_CONTACTS,
connection KEY_ID + " = ?",
57. } 117. new String[] {
58. String.valueOf(contact.getID()) });
59. // code to get the single contact 118. db.close();
60. Contact getContact(int id) { 119. }
61. SQLiteDatabase db = 120.
this.getReadableDatabase(); 121. // Getting contacts Count
62. 122. public int getContactsCount() {
63. Cursor cursor = 123. String countQuery = "SELECT *
db.query(TABLE_CONTACTS, new String[] { FROM " + TABLE_CONTACTS;
KEY_ID, 124. SQLiteDatabase db =
64. KEY_NAME, this.getReadableDatabase();
KEY_PH_NO }, KEY_ID + "=?", 125. Cursor cursor =
65. new String[] { String.valueOf(id) db.rawQuery(countQuery, null);
}, null, null, null, null); 126. cursor.close();
66. if (cursor != null) 127.
67. cursor.moveToFirst(); 128. // return count
68. 129. return cursor.getCount();
69. Contact contact = new 130. }
Contact(Integer.parseInt(cursor.getString(0)), 131.
70. cursor.getString(1), 132. }
cursor.getString(2)); 1. MainActivity.java
Differences between SQL and SQLite { <Button
"type": "pricing", android:id="@+id/btn3"
"url": "http://example.com/pricing" android:layout_width="90dp"
} android:layout_height="80dp"
], android:background="#FAF2B0"
"contact": [ android:layout_marginRight="2pt"
{ android:text="7"
"FN": "APIs.json", android:textSize="30sp"
"email": "[email protected]", android:onClick="numberclick" />
"X-twitter": "apisjson"
} <Button
] android:id="@+id/btn4"
} android:layout_width="90dp"
], android:layout_height="80dp"
"include": [ android:background="#DCD06C"
{ android:layout_marginRight="1pt"
"name": "Another Example API", android:text="+"
"url": "http://example.com/apis.json" android:textSize="30sp"
} android:onClick="arithmetic" />
], </TableRow>
"maintainers": [ <TableRow
{ android:layout_width="match_parent"
"FN": "Kin Lane", android:layout_height="match_parent">
"X-twitter": "apievangelist", <Button
"email": "[email protected]" android:id="@+id/btn5"
} android:layout_width="90dp"
] android:layout_height="80dp"
} android:background="#FAF2B0"
android:text="6"
android:textSize="30sp"
1.Design a simple Calculator UI using Table- android:onClick="numberclick" />
Layout. <Button
Activity_main.xml android:id="@+id/btn6"
Example APIs.json
<?xml version="1.0" encoding="utf-8"?> android:layout_width="90dp"
{
<LinearLayout android:layout_height="80dp"
"name": "Example API",
xmlns:android="http://schemas.android.com/apk/res/ android:background="#FAF2B0"
"description": "This is an example
android" android:text="5"
APIs.json file, demonstrating what is possible with
xmlns:app="http://schemas.android.com/apk/res- android:textSize="30sp"
the API discovery specification.",
auto" android:onClick="numberclick" />
"image": "https://kinlane-
xmlns:tools="http://schemas.android.com/tools" <Button
productions.s3.amazonaws.com/apis-json/apis-json-
android:layout_width="match_parent" android:id="@+id/btn7"
logo.jpg",
android:layout_height="match_parent" android:layout_width="90dp"
"tags": [
android:orientation="vertical" android:layout_height="80dp"
"Application Programming Interface",
android:layout_gravity="center" android:background="#FAF2B0"
"API"
tools:context=".MainActivity"> android:text="4"
],
android:textSize="30sp"
"created": "2014-04-07",
<TextView android:onClick="numberclick" />
"modified": "2020-09-03",
android:id="@+id/edittext" <Button
"url": "http://example.com/apis.json",
android:layout_width="match_parent" android:id="@+id/btn8"
"specificationVersion": "0.14",
android:layout_height="wrap_content" android:layout_width="90dp"
"apis": [
android:layout_weight="1" android:layout_height="80dp"
{
android:background="#AFE0F6" android:background="#DCD06C"
"name": "Example API",
android:gravity="right|bottom" android:text="-"
"description": "This provides details
android:text="0" android:textSize="30sp"
about a specific API, telling what is possible.",
android:textSize="30sp" /> android:onClick="arithmetic"/>
"image": "https://kinlane-
<TableLayout </TableRow>
productions.s3.amazonaws.com/apis-json/apis-json-
android:id="@+id/tb1" <TableRow
logo.jpg",
android:layout_width="match_parent" android:layout_width="match_parent"
"humanURL": "http://example.com",
android:layout_height="wrap_content" android:layout_height="match_parent">
"baseURL": "http://api.example.com",
android:gravity="center" <Button
"tags": [
android:layout_marginRight="2pt" android:id="@+id/btn9"
"API",
android:layout_marginLeft="2pt"> android:layout_width="90dp"
"Application Programming Interface"
android:layout_height="80dp"
],
<TableRow android:background="#FAF2B0"
"properties": [
android:id="@+id/tR1" android:text="3"
{
android:layout_width="match_parent" android:textSize="30sp"
"type": "x-signup",
android:layout_height="147dp"> android:onClick="numberclick" />
"url": "https://example.com/signup"
<Button
},
<Button android:id="@+id/btn10"
{
android:id="@+id/btn1" android:layout_width="90dp"
"type": "x-documentation",
android:layout_width="90dp" android:layout_height="80dp"
"url":
android:layout_height="80dp" android:background="#FAF2B0"
"https://example.com/documentation"
android:background="#FAF2B0" android:text="2"
},
android:text="9" android:textSize="30sp"
{
android:textSize="30sp" android:onClick="numberclick" />
"type": "x-openapi",
android:onClick="numberclick" /> <Button
"url":
android:id="@+id/btn11"
"http://example.com/openapi.json"
<Button android:layout_width="90dp"
},
android:id="@+id/btn2" android:layout_height="80dp"
{
android:layout_width="90dp" android:background="#FAF2B0"
"type": "x-json-schema",
android:layout_height="80dp" android:text="1"
"url": "http://example.com/json-
android:background="#FAF2B0" android:textSize="30sp"
schema.json"
android:layout_marginRight="2pt" android:onClick="numberclick" />
},
android:text="8" <Button
{
android:textSize="30sp" android:id="@+id/btn12"
"type": "x-blog",
android:onClick="numberclick" /> android:layout_width="90dp"
"url": "http://example.com/blog"
android:layout_height="80dp"
},
android:background="#DCD06C" </TableLayout> {
android:text="%" </LinearLayout> String anotherNumber=ed.getText().toString();
android:textSize="30sp" MainActivity.java double answer=0.0;
android:onClick="arithmetic" /> package com.example.calculator; switch (operatorused)
</TableRow> {
import androidx.appcompat.app.AppCompatActivity; case "+":
<TableRow answer=Double.parseDouble(Number)+Double.pars
android:layout_width="match_parent" import android.os.Bundle; eDouble(anotherNumber); break;
android:layout_height="match_parent"> import android.view.View; case "-":
import android.widget.TextView; answer=Double.parseDouble(Number)-
<Button Double.parseDouble(anotherNumber); break;
android:id="@+id/btn13" public class MainActivity extends AppCompatActivity case "/":
android:layout_width="90dp" { answer=Double.parseDouble(Number)/Double.parse
android:layout_height="80dp" private TextView ed; Double(anotherNumber); break;
android:background="#FAF2B0" boolean newvalue=true; case "X":
android:text="+/-" String operatorused="+"; answer=Double.parseDouble(Number)*Double.parse
android:textSize="30sp" String Number=""; Double(anotherNumber); break;
android:onClick="numberclick" /> }
@Override ed.setText(answer+"");
<Button protected void onCreate(Bundle }
android:id="@+id/btn14" savedInstanceState) { public void clear(View view)
android:layout_width="90dp" super.onCreate(savedInstanceState); {
android:layout_height="80dp" setContentView(R.layout.activity_main); ed.setText("0");
android:background="#FAF2B0" ed=findViewById(R.id.edittext); newvalue=true;
android:text="0" } }
android:textSize="30sp" public void numberclick(View view) }
android:onClick="numberclick" /> { OUTPUT
if(newvalue)
<Button { 2. Develop an android application which get
android:id="@+id/btn15" ed.setText(""); result back from a child activity.
android:layout_width="90dp" } Activity_main.xml
android:layout_height="80dp" newvalue=false;
android:background="#FAF2B0" String input= ed.getText().toString(); <?xml version="1.0" encoding="utf-8"?>
android:text="." switch (view.getId()) <LinearLayout
android:textSize="30sp" { xmlns:android="http://schemas.android.com/apk/res/
android:onClick="numberclick" /> case R.id.btn1: android"
input=input+"9"; xmlns:app="http://schemas.android.com/apk/res-
<Button break; auto"
android:id="@+id/btn16" case R.id.btn2: xmlns:tools="http://schemas.android.com/tools"
android:layout_width="90dp" input=input+"8"; android:layout_width="match_parent"
android:layout_height="80dp" break; android:layout_height="match_parent"
android:background="#DCD06C" case R.id.btn3: android:gravity="center"
android:text="=" input=input+"7"; android:orientation="vertical"
android:textSize="30sp" break; android:padding="16dp"
android:onClick="equalevent" /> case R.id.btn5: tools:context=".MainActivity">
</TableRow> input=input+"6";
break; <EditText
<TableRow case R.id.btn6: android:id="@+id/edit_text_number1"
android:layout_width="match_parent" input=input+"5"; android:layout_width="match_parent"
android:layout_height="match_parent"> break; android:layout_height="wrap_content"
case R.id.btn7: android:hint="Number 1"
<Button input=input+"4"; android:inputType="number" />
android:id="@+id/btn17" break;
android:layout_width="90dp" case R.id.btn9: <EditText
android:layout_height="80dp" input=input+"3"; android:id="@+id/edit_text_number2"
android:onClick="clear" break; android:layout_width="match_parent"
android:background="#FAF2B0" case R.id.btn10: android:layout_height="wrap_content"
android:text="C" input=input+"2"; android:hint="Number 2"
android:textSize="30sp" /> break; android:inputType="number" />
case R.id.btn11:
<Button input=input+"1"; <TextView
android:id="@+id/btn18" break; android:id="@+id/text_view_result"
android:layout_width="90dp" case R.id.btn14: android:layout_width="match_parent"
android:layout_height="80dp" input=input+"0"; android:layout_height="wrap_content"
android:onClick="numberclick" break; android:text="Result"
android:background="#FAF2B0" case R.id.btn15: android:textSize="30sp" />
android:text="()" input=input+".";
android:textSize="30sp" /> break; <Button
case R.id.btn13: android:id="@+id/button_open_activity2"
<Button input="-"+input; android:layout_width="wrap_content"
android:id="@+id/btn19" break; android:layout_height="wrap_content"
android:layout_width="90dp" } android:text="open activity 2" />
android:layout_height="80dp" ed.setText(input);
android:onClick="arithmetic" } </LinearLayout>
android:background="#FAF2B0" public void arithmetic(View view)
android:text="/" { activity_2.xml
android:textSize="30sp" /> newvalue=true;
Number=ed.getText().toString(); <?xml version="1.0" encoding="utf-8"?>
<Button switch(view.getId()) <LinearLayout
android:id="@+id/btn20" { xmlns:android="http://schemas.android.com/apk/res/
android:layout_width="90dp" case R.id.btn4: operatorused ="+"; break; android"
android:layout_height="80dp" case R.id.btn8: operatorused="-"; break; xmlns:app="http://schemas.android.com/apk/res-
android:onClick="arithmetic" case R.id.btn19: operatorused="/"; break; auto"
android:background="#DCD06C" case R.id.btn20: operatorused="X"; break; xmlns:tools="http://schemas.android.com/tools"
android:text="X" } android:layout_width="match_parent"
android:textSize="30sp" /> } android:layout_height="match_parent"
</TableRow> public void equalevent(View view) tools:context=".Activity2"
android:gravity="center" } 3. Design a signup form using any layout of your
android:orientation="vertical" choice.
android:padding="16dp"> @Override a. Your design must include important widgets like
protected void onActivityResult(int requestCode, TextView, EditText, Button,
<TextView int resultCode, Intent data) { RadioButton, CheckBox, Spinner etc.
android:id="@+id/text_view_numbers" super.onActivityResult(requestCode, b. When user click a Button display inputted data in a
android:layout_width="match_parent" resultCode, data); TextView.
android:layout_height="wrap_content" Activity_main.xml
android:text="Numbers: " if (requestCode == 1) {
android:textSize="30sp" /> if (resultCode == RESULT_OK) { <?xml version="1.0" encoding="utf-8"?>
int result = data.getIntExtra("result", 0); <LinearLayout
<Button mTextViewResult.setText("" + result); xmlns:android="http://schemas.android.com/apk/res/
android:id="@+id/button_add" } android"
android:layout_width="wrap_content" if (resultCode == RESULT_CANCELED) { android:orientation="vertical"
android:layout_height="wrap_content" mTextViewResult.setText("Nothing android:layout_width="match_parent"
android:text="add" /> selected"); android:layout_height="match_parent">
} <TextView
<Button } android:layout_width="wrap_content"
android:id="@+id/button_subtract" } android:layout_height="wrap_content"
android:layout_width="wrap_content" } android:text="Registration Form"
android:layout_height="wrap_content" Activity2.java android:textStyle="bold"
android:text="subtract" /> android:textAlignment="center"/>
package com.example.resultfromchildactivity;
</LinearLayout> <EditText
import android.content.Intent; android:id="@+id/firstname"
MainActivity.java import android.os.Bundle; android:layout_width="wrap_content"
import android.view.View; android:layout_height="wrap_content"
package com.example.resultfromchildactivity; import android.widget.Button; android:text="Enter First Name"
import android.widget.TextView; android:ems="10"/>
import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; <EditText
import android.os.Bundle; android:id="@+id/lastname"
import android.view.View; public class Activity2 extends AppCompatActivity { android:layout_width="wrap_content"
import android.widget.Button; android:layout_height="wrap_content"
import android.widget.EditText; @Override android:text="Enter Last Name"
import android.widget.TextView; protected void onCreate(Bundle android:ems="10"/>
import android.widget.Toast; savedInstanceState) { <EditText
import androidx.appcompat.app.AppCompatActivity; super.onCreate(savedInstanceState); android:id="@+id/number"
setContentView(R.layout.activity_2); android:layout_width="wrap_content"
public class MainActivity extends AppCompatActivity android:layout_height="wrap_content"
{ setTitle("Activity 2"); android:text="Enter Mobile Number"
private TextView mTextViewResult; android:ems="10"/>
private EditText mEditTextNumber1; Intent intent = getIntent();
private EditText mEditTextNumber2; final int number1 = <TextView
intent.getIntExtra("number1", 0); android:layout_width="wrap_content"
@Override final int number2 = android:layout_height="wrap_content"
protected void onCreate(Bundle intent.getIntExtra("number2", 0); android:textSize="20dp"
savedInstanceState) { android:text="Gender"
super.onCreate(savedInstanceState); TextView textViewNumbers = android:textStyle="bold"
setContentView(R.layout.activity_main); findViewById(R.id.text_view_numbers); android:paddingTop="10dp"
textViewNumbers.setText("Numbers: " + android:id="@+id/txtView"/>
mTextViewResult = number1 + ", " + number2); <RadioButton
findViewById(R.id.text_view_result); android:id="@+id/rdbMale"
mEditTextNumber1 = Button buttonAdd = android:layout_width="wrap_content"
findViewById(R.id.edit_text_number1); findViewById(R.id.button_add); android:layout_height="wrap_content"
mEditTextNumber2 = Button buttonSubtract = android:text="Male"
findViewById(R.id.edit_text_number2); findViewById(R.id.button_subtract); android:onClick="onRadioButtonClicked"/>
<RadioButton
Button buttonOpenActivity2 = buttonAdd.setOnClickListener(new android:id="@+id/rdbFemale"
findViewById(R.id.button_open_activity2); View.OnClickListener() { android:layout_width="wrap_content"
buttonOpenActivity2.setOnClickListener(new @Override android:layout_height="wrap_content"
View.OnClickListener() { public void onClick(View v) { android:text="Female"
@Override int result = number1 + number2; android:onClick="onRadioButtonClicked"/>
public void onClick(View v) {
if Intent resultIntent = new Intent(); <TextView
(mEditTextNumber1.getText().toString().equals("") resultIntent.putExtra("result", result); android:id="@+id/txtVw"
|| android:layout_width="wrap_content"
mEditTextNumber2.getText().toString().equals("")) { setResult(RESULT_OK, resultIntent); android:layout_height="wrap_content"
Toast.makeText(MainActivity.this, finish(); android:text="Select Course:"
"Please insert numbers", } android:paddingTop="20dp"
Toast.LENGTH_SHORT).show(); }); android:textStyle="bold"
} else { android:textSize="15dp" />
buttonSubtract.setOnClickListener(new
int number1 = View.OnClickListener() { <Spinner
Integer.parseInt(mEditTextNumber1.getText().toStrin @Override android:id="@+id/spinner1"
g()); public void onClick(View v) { android:layout_width="wrap_content"
int number2 = int result = number1 - number2; android:layout_height="wrap_content"
Integer.parseInt(mEditTextNumber2.getText().toStrin android:layout_alignBottom="@+id/txtVw"
g()); Intent resultIntent = new Intent(); android:layout_toRightOf="@+id/txtVw" />
resultIntent.putExtra("result", result);
Intent intent = new <CheckBox
Intent(MainActivity.this, Activity2.class); setResult(RESULT_OK, resultIntent); android:id="@+id/chkJava"
intent.putExtra("number1", number1); finish(); android:layout_width="wrap_content"
intent.putExtra("number2", number2); } android:layout_height="wrap_content"
startActivityForResult(intent, 1); }); android:paddingTop="20dp"
} } android:text="I accept the terms and conditions"
} } android:onClick="onCheckboxClicked"/>
});
<Button </LinearLayout>
android:id="@+id/getName" MainActivity.xml
android:layout_width="wrap_content"
android:layout_height="wrap_content" Button button1 = new Button(this); package com.example.simpleinterest;
android:text="Sign Up" /> button1.setText("Add Name");
LinearLayout linearLayout = new import android.os.Bundle;
</LinearLayout> LinearLayout(this); import android.view.View;
linearLayout.addView(textView1); import android.widget.Button;
Strings.xml linearLayout.addView(editText1); import android.widget.EditText;
linearLayout.addView(button1); import android.widget.TextView;
<resources> setContentView(linearLayout);
<string name="app_name">SignupForm</string> } import androidx.appcompat.app.AppCompatActivity;
</resources> 4. Develop an android application to calculate
simple interest. import com.example.simpleinterest.R;
MainActivity.java
Activity_main.xml public class MainActivity extends AppCompatActivity
package com.example.signupform; {
<?xml version="1.0" encoding="utf-8"?>
import android.os.Bundle; <LinearLayout @Override protected void onCreate(Bundle
import android.view.View; xmlns:android="http://schemas.android.com/apk/res/ savedInstanceState) {
import android.widget.AdapterView; android" super.onCreate(savedInstanceState);
import android.widget.ArrayAdapter; xmlns:app="http://schemas.android.com/apk/res- setContentView(R.layout.activity_main);
import android.widget.Button; auto"
import android.widget.EditText; xmlns:tools="http://schemas.android.com/tools" OnCLick();
import android.widget.RadioButton; android:layout_width="match_parent" }
import android.widget.Spinner; android:layout_height="match_parent"
import android.widget.TextView; android:orientation="vertical" EditText amt,interest,time;
import android.widget.Toast; tools:context=".MainActivity"> Button btn;
TextView txt1,txt2;
import androidx.appcompat.app.AppCompatActivity; <TextView
android:layout_width="fill_parent" public void OnCLick()
public class MainActivity<textView1, editText1, android:layout_height="wrap_content" {
button1, adapter> extends AppCompatActivity { android:text="SImple Calculator" amt=(EditText)findViewById(R.id.amt);
android:textAlignment="center" interest=(EditText)findViewById(R.id.interest);
RadioButton male, female; android:textSize="30dp" /> time=(EditText)findViewById(R.id.tim);
String[] Courses = { "Java", "Python", "MERN",}; btn=(Button)findViewById(R.id.btn);
private Object v; <TextView txt1=(TextView)findViewById(R.id.txt1);
android:layout_width="fill_parent" txt2=(TextView)findViewById(R.id.txt2);
protected void onCreate(Bundle android:layout_height="wrap_content"
savedInstanceState) { android:text="------------------------------------------" btn.setOnClickListener(new
super.onCreate(savedInstanceState); android:textAlignment="center" View.OnClickListener() {
setContentView(R.layout.activity_main); android:textSize="30dp" /> @Override public void onClick(View v)
TextView textView1 = new TextView(this); {
textView1.setText("Register Form"); <EditText int
EditText editText1 = new EditText(this); android:layout_width="fill_parent" a=Integer.parseInt(amt.getText().toString());
editText1.setText("Enter First Name"); android:layout_height="wrap_content" int
EditText editText2 = new EditText(this); android:hint="Enter Amount" b=Integer.parseInt(interest.getText().toString());
editText1.setText("Enter Last Name"); android:id="@+id/amt" int
EditText editText3 = new EditText(this); android:textAlignment="center" c=Integer.parseInt(time.getText().toString());
editText1.setText("Enter Mobile Number"); android:inputType="number"/> int d;
d=(a*b*c)/100;
male = <EditText int e=a+d;
(RadioButton)findViewById(R.id.rdbMale); android:layout_width="fill_parent"
female = android:layout_height="wrap_content" txt1.setText("Total Interest Is
(RadioButton)findViewById(R.id.rdbFemale); android:hint="Enter Interest Rate (In %)" :"+String.valueOf(d));
{ android:id="@+id/interest" txt2.setText("Total Amount is :
String result = "Selected Course: "; android:textAlignment="center" "+String.valueOf(e));
result += (((male.isChecked()) ? "Male" : android:inputType="number"/>
(female.isChecked()) ? "Female" : "")); }
Toast.makeText(getApplicationContext(), });
result, Toast.LENGTH_SHORT).show(); <EditText }
} android:layout_width="fill_parent" }
}; android:layout_height="wrap_content" OUTPUT
Spinner spin = (Spinner) android:hint="Enter Time (in Year)"
findViewById(R.id.spinner1); android:id="@+id/tim"
private int courses; android:textAlignment="center"
ArrayAdapter<String> adapter = new android:inputType="number" /> 5. Develop an android application to calculate
ArrayAdapter<String>(this, area and perimeter of rectangle. Your application
android.R.layout.simple_spinner_item, courses); <Button must calculate and display area in one fragment
android:layout_width="wrap_content" and perimeter in another fragment.
adapter.setDropDownViewResource(android.R.layou android:layout_height="wrap_content"
t.simple_spinner_dropdown_item); android:text="Calculate" Develop on android application to calculate area in
spin.setAdapter(adapter); android:id="@+id/btn" /> one frogment and penimter in another frogment.
spin.setOnItemSelectedListener(this);
#activity_main.xml
<TextView
public void onItemSelected(AdapterView<?> arg0, android:layout_width="fill_parent" <?xml version="1.0" encoding="utf-8" ?>
View arg1, int position, long id) { android:layout_height="wrap_content" xmlns:android ["http://schemas.android.com/apk/
Toast.makeText(getApplicationContext(), android:id="@+id/txt1"
"Selected User: "+users[position] android:textSize="30dp" /> <LinearLayout
,Toast.LENGTH_SHORT).show();
} <TextView res/android"
android:layout_width="fill_parent"
public void onNothingSelected(AdapterView<?> android:layout_height="wrap_content" android:layout_width="match_parent"
arg0) { android:id="@+id/txt2"
// TODO - Custom Code android:textSize="20dp" /> android:layout_height="moth-content match.parent
} android:orientation="vertical" >
this. context = context;
<Button } my DbHelper updateData (id, name, Address);
@override Toast.makeText(getApplication Context()," Data
android:layout_coldth="match_parent" Upda Hed!!!" Toast.LENGTH_SHORT).show();
android:layout_height="wrap_content" public viewHolder onCreateViewHolder (ViewGrap
android:id="@idt/ win first android:text= parent, int viewType) &
"Fragment"/> }});
(@youtInflater, layoutInflater = (ayoutInflater form <TextView
<Button (context);
android:id="@+id/tetData"
android:layout_width="match_parent" View listItem-layoutInflater inflate(R.layout. recycles
android:layout_height="wrap_content" view-items, parent, false); ViewHolder viewHolder= android:textSelected Data:"
android:id="@+id/btnSecond" new ViewHolder(listItem);
android:layout_below="@+id/bioselect'' />
and hoid:text="fragment2" /> return viewHolder;
} <Button
<fragment @override
android:id="@id/btnSelect"
android:id="@+id/my fragment" public void onBindViewHolder (ViewHolder holder,
android:layout_width="match_parent int android:layout_below="@+id/edt Address!
android:layout_height="match_parent" > android:text="select"
position) & holder.txtName.setText (name [position]);
<I Linear layout> android:layout-toRight-of="@+id/btnInsert" />
holder.txtAddress.setText(address [position]); holder.
#Frogment.java imageView.setImageResource(image (position)); 4. # Creating Activity #SQ+eExampe.java
}
public class Fragment 1 extends Frogment & public @override public class Solite Example extends
view onCreateview (layoutInflater infliter, AppCompatActivity EditText edtid, edt Name,
public int getItem Count () & return neme.length; ed+Address; Button btnInsert, btnSelect, btn Update,
@Override } binDelete;
public static class ViewHolder extends
ViewGroup container, Bundle savedInstan RecyclerView. TextView +x+Data; MyDbHelper myDb Helper,
View holder {
cestate) & @Override
binDelete setOnClickListener(new
View view = inflater view.OnClickListener(){ @Override protected void onCreate(Bundle b) {

SetContentView(R.layout. fragment 1) Super.onCreate(b);

onclick(); public void onClick (view view) { String SetContentView(R.layout.Sqlite-example);


} id=edt.getText().toString() myDbHelper.deleteData myDbнeper = new MyDb Helper (this);
lid),
EditText length, Breadth; edt Name:findViewById(R.id.ed+Name); edt
Toast makeText(getApplication Context(),Data Address-findViewById(R.id.ed+ Address); btnInsert
Button btn; TextView +x+Result; inserted" findViewById(R.id. btnInsert); =

public void onClick() ε LENGTH_SHORT).show(); d edtId = findViewById(R.id.edthe);


+x+Data=findViewById(R.id.txt Data);
length= findViewById(R.layout. length); breadth = }} );
find viewById (R.layout. breadth); btn = findview By btnSelect findViewById(R.id.btnSelect); btn Update =
Id (R.layout. btn); +x+Result= findViewById(R.layout. public void on Click (view view)§ findViewById(R.id.btnUpdate),
+x+Result); btn.SetonClickListener(new
View.OnClickListeners int id Integer.parseInt(echid.getText().toString()); btn Delete indview By Id (R.id.btnDelete);"
String name-ed+Name.getText().toString(), String
@override Address ed+Adohress getText().toString(); btnInsert setOnClickListener(new
View.OnClickListener U{
public void onClick(View v) { inta mybbHeper insert Data (id, name, address);
Integer.parseInt(length.getText().toString()); @override
Toast.makeText(get Application Context(), 'Data
breadth Inseated"); Toast LENGTH SHORT. Show();
3.Designing UI
int b = Integer.parseInt (tength, getText().toString(); btnSelect.setOnClickListener(new
View.OnClickListener() #sqlite example.xml
int c; c= axb
@overade int id:0; <RelativeLayout
+x+Result.setText("Total area of rectangle is!"
+String.value of (c)), String name=" "address" "; <?xml version="1.0" encoding="utf-8"?>
} }); }} xmlns:android="http://schemas.android.com/apk/
Cursor cursor myDbHelper. Select Data(), Cohile
RecyclerView Adapter, java public class (cursor.moveToNext()){ res/android"
RecyclerViewAdapter extends Recyclerview
ids cursor.getInt(0); android:layout_width="match_parent" android;
Adapter<RecyclerviewAdapter.ViewHolder> & orientation vertical"
name= cursor.getString(1); address-cursor.getString android:layout_height="match_parent">
Activity context; (2);
<EditText
int[] image; Stringt) name, +x+ Data setText("Id="+id
"+Name+name+1+Address =1+ address); android:id="@+idledtid"
Stringt) address;
btnUpdate.setOnClickListener(new Android: hint =" EnterId"
Public RecyclerViewAdeplex (Activity context, View.OnClickListeners @ovembe android:inputType="number" />
String13 nome, stringt) address, int image) &
public void onClick(View view) § String id edt android:id="@+id/edtName" android:hint = "Enter
this name name; this address = address, Id.geText().toString(); Name" android:layout_below="@+id/edtId"/>

this image image, String name-edt Name.getText().toString(); String <EditText android:id="@+id/edt


address=edt Address getText().toString();
Address" android: hint="Enter Address" app:layout_constraintTop_toTopOf="parent" /> }
android:layout_below="@+id/ed+Name" /> }
</androidx.constraintlayout.widget.ConstraintLayout
<Button > 7. Develop an android application to calculate
area and perimeter of a rectangle in a dialog.
android:id="@+id/btnInsert" android:text="Insert" Strings.xml <?xml version="1.0" encoding"utf-8"?>
<resources> <LinearLayout
android:layout_below="@+id/btnInsert"/> <string name="app_name">AlertDialog</string>
<string name="dialog_message">Welcome to xmlns:android="http://schemas.android.com/apk/res
<Button Alert Dialog</string> landroid android:orientation="vertical"
<string name="dialog_title">Javatpoint Alert android:layout_width="match_parent"
android:id="@+id/btnUpdate" Dialog</string> android:layout_height="match_parent">
</resources> <Edittext
android:text="Edit" MainActivity.java android:layout_width="match_parent"
android:layout_height="wrap_content" android: hint =
android:layout_toRight of="@+id/btnInsert" /> package com.example.alertdialog; "enter length" android:inputType="number",
android:id="@+id/eatFirst" />
<Button import androidx.appcompat.app.AlertDialog; <Edittext
import androidx.appcompat.app.AppCompatActivity; " android:layout_width="match_parent"
android:id="@+id/Delete" android:text="Delete" android:layout_height="wrap_content" android: hint =
import android.content.DialogInterface; "Enter Breadth" android:inputType="number"
android:layout_toRight of="@+id/btn update"> import android.os.Bundle; android:id="@+id/ed+Second" />
import android.view.View;
import android.widget.Button; <BUTTON
Content values.put("address", address), //inserting import android.widget.Toast;
ou db. Insert ("mytable", null, contentValues); android:layout_width=""corap_content"
public class MainActivity extends AppCompatActivity android:layout_height="wrap_content"
db close(); {
Button closeButton; android:layout_gravity="center" android,
& AlertDialog.Builder builder; text="Calculate" android:id="@+id/b+nCalculate" />
@Override
code to select data protected void onCreate(Bundle <TextView
savedInstanceState) {
Public Cursor SelectData()$ Solite Database db = super.onCreate(savedInstanceState); android:layout_width="wrap_content"
this.getReadable Database; String query = "SELECT setContentView(R.layout.activity_main); android:layout_height="" corap_content"
* FROM mytable", Cursor Cursorsdb.rawQuery
(query.null); retum Cursor; closeButton = (Button) android:text="Area of Rectangle"
findViewById(R.id.button); android:textSize="20sp"
/code to update data public void updateData(String builder = new AlertDialog.Builder(this);
id, string name string address) closeButton.setOnClickListener(new android:layout_gravity="center" 200p,
View.OnClickListener() { android:layout_marginTop="@++/txtArea
SoLiteDatabase db = this.getWriteable Database(); @Override android:id="@+id/txtArea" />
public void onClick(View v) {
ContentValues content values = new
contentValues(); //Uncomment the below code to Set the <TextView
message and title from the strings.xml file
ContentValues.put("name", name); android:layout_width="corop_content"
builder.setMessage(R.string.dialog_message)
content Values.put("address", address); .setTitle(R.string.dialog_title); android

//updating row db.update (myTable, content Values //Setting message manually and :layout_height=""corap_content"
(id=?,new String CJ (id); performing action on button click android:text="Perimeter of Rectangle
builder.setMessage("Do you want to close
db.close(); this application ?") android:textSize="20sp"
.setCancelable(false)
//code to delete dala .setPositiveButton("Yes", new android:layout_gravity="center"
DialogInterface.OnClickListener() { android:layout_marginTop="20dp",
public void deleteData (String id) { Soute Database public void onClick(DialogInterface android:id="@+id/txt perimeter"/>
db= this.getWriteable Database(); /deleting roo dialog, int id) {
finish(); </LinearLayout>
db.delete ("myrable", "id=?", new String[] Side)
Toast.makeText(getApplicationContext(),"you activity-main.xml.
} choose yes action for alertbox",
6. Develop an android application to demonstrate <?xml version="1.0" encoding="utf-8"?>
alert dialog. Toast.LENGTH_SHORT).show(); <RelativeLayout
Activity_main.xml }
}) xmlns:android="http://schemas.android.com/apk/res/
<?xml version="1.0" encoding="utf-8"?> .setNegativeButton("No", new android" android:layout_height="match_parent",
<androidx.constraintlayout.widget.ConstraintLayoutx DialogInterface.OnClickListener() { android:layout_width="match_parent">
mlns:android="http://schemas.android.com/apk/res/a public void onClick(DialogInterface
ndroid" dialog, int id) { <Button
xmlns:app="http://schemas.android.com/apk/res- // Action for 'NO' Button android:layout_coldth=""corap_content"
auto" dialog.cancel(); android:layout_height="wrapcontent.
xmlns:tools="http://schemas.android.com/tools" android:text="Show Dialog
android:layout_width="match_parent" Toast.makeText(getApplicationContext(),"you android:layout_centerHorizontal="true"
android:layout_height="match_parent" choose no action for alertbox", android:layout_marginTop="20sp"
tools:context=".MainActivity"> android:id="@id/btnclick"
Toast.LENGTH_SHORT).show();
<Button } android:textSize="20sp" />
android:layout_width="wrap_content" });
android:layout_height="wrap_content" //Creating dialog box *main Activity.java
android:id="@+id/button" AlertDialog alert = builder.create();
android:text="Close app" //Setting the title manually AppCompat public class FirstActivity extends,
alert.setTitle("AlertDialogExample"); Activity { Edit Text ed+First, eatSecond; Button
app:layout_constraintBottom_toBottomOf="parent" alert.show(); btnclick, bin calculate;
app:layout_constraintLeft_toLeftOf="parent" }
app:layout_constraintRight_toRightOf="parent" }); Textview +x+ Area txt Perimeter;
setContentView(R.layout.activity_main);
@overoide <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/ RecyclerView recyclerContact =
protected void onCreate(Bundle savedInstanceState android" findViewById(R.id.recyclerContact);
Super.onCreate (savedInstanceState); xmlns:app="http://schemas.android.com/apk/res- recyclerContact.setLayoutManager(new
SetContent(R.layout.activity_main); btnclick= auto" LinearLayoutManager(this));
findViewById(R.id.btn click); android:layout_width="match_parent"
android:layout_height="wrap_content" arrContact.add(new
android:gravity="center" > ContactModel(R.drawable.ic_baseline_contact_phon
binclick setOnClickListener (new e_24,
View.OnClickListener(){ <androidx.cardview.widget.CardView "Salina Pokhrel", "9851258639"));
android:layout_width="match_parent" arrContact.add(new
@override android:layout_height="wrap_content" ContactModel(R.drawable.ic_baseline_contact_phon
app:cardCornerRadius="7dp" e_24,
public void onClick(View view) { app:cardUseCompatPadding="true" > "Salina meow 2", "9851258639"));
arrContact.add(new
ShowDialog(); }}); <LinearLayout ContactModel(R.drawable.ic_baseline_contact_phon
} android:id="@+id/llRow" e_24,
android:layout_width="match_parent" "Rabi Shrestha 3", "9851258639"));
public void showDialog()S AlertDialog.Builder builder android:layout_height="wrap_content" arrContact.add(new
= newAlertDialog.Builder android:layout_gravity="center_vertical" ContactModel(R.drawable.ic_baseline_contact_phon
android:padding="11dp" e_24,
(Activity Main this) android:orientation="horizontal"> "Aman Rauniyar 4", "9851258639"));
arrContact.add(new
builder.setTitle ("Calculate Ameo & perimeter of <ImageView ContactModel(R.drawable.ic_baseline_contact_phon
rectangle"), builder. SetCancelable (tave); android:id="@+id/imgContact" e_24,
android:layout_width="70dp" "Pramod Shrestha", "9851258639"));
LayoutInflater inflater.getLayoutInflater(); View view- android:layout_height="70dp" arrContact.add(new
inflater.inflate(R.layout.custom_dialegnol builder. android:background="#C6F492" ContactModel(R.drawable.ic_baseline_contact_phon
setview (view); e_24,
android:src="@drawable/ic_baseline_contact_phone "Zakki Uddin2", "9851258639"));
edtfirst view.findViewById(R.id.edt First); eatSecond _24" arrContact.add(new
= view.findViewById(R.id.ed+second); android:contentDescription="Contact ContactModel(R.drawable.ic_baseline_contact_phon
btocalculate=view.findViewById(R.id.btnCalculate); Image" /> e_24,
txt Area: vieco.findViewById(R.id. txtArea); "Pareshna Khadka 3", "9851258639"));
+x+Perimeter- <LinearLayout arrContact.add(new
vieco.findViewById(R.id.+x+perimeter); android:layout_width="match_parent" ContactModel(R.drawable.ic_baseline_contact_phon
android:layout_height="wrap_content" e_24,
btnCalculate.setOnClickListener(new android:layout_marginLeft="11dp" "Ayush Thapa4", "9851258639"));
View.OnClickListene android:layout_marginStart="11dp" arrContact.add(new
android:orientation="vertical"> ContactModel(R.drawable.ic_baseline_contact_phon
@Override e_24,
<TextView "Aarav Shrestha", "9851258639"));
public void onClick(View view) { length breadth android:id="@+id/txtName" arrContact.add(new
android:layout_width="match_parent" ContactModel(R.drawable.ic_baseline_contact_phon
int fast, second, ult, perimeter; length android:layout_height="wrap_content" e_24,
Integer.parseInt(edtfingt.getText().toString() breadth= android:text="Contact" "Susan Tamang2", "9851258639"));
Integer.parseInt (edt Eirst.getText().toString()) android:textSize="22sp" arrContact.add(new
android:textStyle="bold" /> ContactModel(R.drawable.ic_baseline_contact_phon
Area = length breadth, e_24,
<TextView "Aakanshya Prajapati3", "9851258639"));
perimeter = 2* (length + breadth); +xtArea SetText android:id="@+id/txtNumber" arrContact.add(new
("Area =" + Area); +xt Perimeter.setText("Perimeter android:layout_width="match_parent" ContactModel(R.drawable.ic_baseline_contact_phon
=" + perimeter); android:layout_height="wrap_content" e_24,
android:text="Contact No" "Anup Gautam 4", "9851258639"));
}}); AlertDialog alert = builder.create(); alert.show(); android:textSize="16sp" arrContact.add(new
android:textStyle="bold" /> ContactModel(R.drawable.ic_baseline_contact_phon
}} e_24,
</LinearLayout> "Siraj Maharjan", "9851258639"));
8. android application to demonstrate Recycler view. </LinearLayout> arrContact.add(new
Activity_main.xml ContactModel(R.drawable.ic_baseline_contact_phon
<?xml version="1.0" encoding="utf-8"?> e_24,
<androidx.constraintlayout.widget.ConstraintLayout </androidx.cardview.widget.CardView> "Sarika Kumal 2", "9851258639"));
xmlns:android="http://schemas.android.com/apk/res/ arrContact.add(new
android" </LinearLayout> ContactModel(R.drawable.ic_baseline_contact_phon
xmlns:app="http://schemas.android.com/apk/res- MainActivity.java e_24,
auto" "Anup Poudel 3", "9851258639"));
xmlns:tools="http://schemas.android.com/tools" package com.example.recyclerview; arrContact.add(new
android:layout_width="match_parent" ContactModel(R.drawable.ic_baseline_contact_phon
android:layout_height="match_parent" import androidx.appcompat.app.AppCompatActivity; e_24,
tools:context=".MainActivity"> import "Atit Dallakoti4", "9851258639"));
androidx.recyclerview.widget.LinearLayoutManager;
<androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView; RecyclerContactAdapter adapter = new
android:id="@+id/recyclerContact" RecyclerContactAdapter(this, arrContact);
android:layout_width="409dp" import android.os.Bundle; recyclerContact.setAdapter(adapter);
android:layout_height="729dp" }
import java.util.ArrayList; }
app:layout_constraintBottom_toBottomOf="parent" contactmodel.java
app:layout_constraintEnd_toEndOf="parent" public class MainActivity extends AppCompatActivity
app:layout_constraintStart_toStartOf="parent" { package com.example.recyclerview;
app:layout_constraintTop_toTopOf="parent" /> ArrayList<ContactModel> arrContact = new
ArrayList<ContactModel>(); public class ContactModel {
</androidx.constraintlayout.widget.ConstraintLayout int img;
> @Override String name, number;
Contantrow.xml protected void onCreate(Bundle
savedInstanceState) { public ContactModel(int img, String name, String
<?xml version="1.0" encoding="utf-8"?> super.onCreate(savedInstanceState); number){
this.img = img;
this.name = name; db.close();
this.number = number; 9. Android app to demonstrate use of solite }
} Database
} //code to delete dala
RecyclerContactAdapter.java creating Database Tables #MyDbHelper.java public
class MybbHelper extends SolitsOpenHelpers public void deleteData (String id) { Soute Database
package com.example.recyclerview; db= this.getWriteable Database, /deleting roo
Database version private static final in DATABASE-
import android.content.Context; VERSION=1; db.delete ("myrable", "id=?", new String[] Side))
import android.view.LayoutInflater;
import android.view.View; //Database Name private static final String }
import android.view.ViewGroup; DATABASE_NAME = "mydb"; public MybbHelper
import android.widget.ImageView; (context context) { Super (context,
import android.widget.TextView; DATABASE_NAME, null, DATABASE_VERSION) 3. Designing UI
}
import androidx.annotation.NonNull; Creating Tables #sqlite example.xml
import androidx.recyclerview.widget.RecyclerView;
@override <RelativeLayout
import java.util.ArrayList;
public void onCreate (SoLiteDatabase db) { <?xml version="1.0" encoding="utf-8"?>
public class RecyclerContactAdapter extends xmlns:android="http://schemas.android.com/apk/
create notes table
RecyclerView.Adapter<RecyclerContactAdapter.Vie res/androld"
wHolder> { Staing createQuery= "CREATE TABLE mytable (id <EditText
Context context; INTEGER PRIMARY KEY, name TEXT, address android:layout_width="match_parent"
ArrayList<ContactModel> arrContacts; TEXT)"; android:orientation="vertical"
android:layout_height="match_parent">
RecyclerContactAdapter(Context context, ab.execSOL (Create Query);
ArrayList<ContactModel> arrContacts){ } android:id="@+idledtid"
this.context = context; Upgrading database
this.arrContacts = arrContacts; @override Android: hint =" EnterId"
} android:inputType="number" />
public void on Upgrade (SoliteDatabase, intold
@NonNull Version, int <EditText
@Override
public ViewHolder onCreateViewHolder(@NonNull { android:id="@+id/ed+Name" android: hint = "Enter
ViewGroup parent, int viewType) { Name" android:layout_below="@+id/edtId"/>
View view = new Version);
LayoutInflater.from(context).inflate(R.layout.contact_ <EditText
row, parent, Drop older table it created db.execSoul" Drop tabe IF
false); EXISTS"+ DATABASE_NAME); android:id="@+id/edt Address" android: hint = "Enter
ViewHolder viewHolder = new Address" android:layout_below="@+id/ed+Name" />
ViewHolder(view); Create table again
OnCreate (db); <Button
return viewHolder; }}
} android:id="@+id/btnInsert" android:text="Insert"
2 . Data Manupulation
@Override android:layout_below="@+id/btnInsert"/>
public void onBindViewHolder(@NonNull Icode to insert data public void insert Data Lintid,
ViewHolder holder, int position) { String name, String address SQLiteDatabase db= <Button
this, getwriteable Database(); Content Values
holder.imgContact.setImageResource(arrContacts.g contenvalues: new contentValues(); android:id="@+id/btnUpdate"
et(position).img);
content values.put("id", id); Contentvalues put android:text="Edit"
holder.txtName.setText(arrContacts.get(position).na ("name", name);
me); android:layout_toRight of="@+id/btnInsert" />

holder.txtNumber.setText(arrContacts.get(position).n <Button
umber); Content values.put("address", address), Winserting
} ou db. Insert ("myTable", null, contentValues); android:id="@+id/Delete" android:text="Delete"

@Override db close(); android:layout_toRight of="@+id/btn update">


public int getItemCount() { }
return arrContacts.size();
} code to select data
<TextView
public class ViewHolder extends Public Cursor SelectData()$ Solite Database db=
RecyclerView.ViewHolder{ this.getReadable Database; String query = "SELECT android:id="@+id/txtData"
TextView txtName, txtNumber; * FROM myTable", Cursor Cursorsdb.rawQuery
ImageView imgContact; (query.null); retum Cursor; android:textSelected Data:"
}
public ViewHolder(View itemView) { android:layout_below="@+id/btnSelect" />
super(itemView); /code to update data public void updateDatal String
txtName = id, string name String address) <Button
itemView.findViewById(R.id.txtName);
txtNumber = SoLiteDatabase db = this.getWriteable Database(); android:"@id/btnSelect"
itemView.findViewById(R.id.txtNumber);
imgContact = ContentValues content values = new android:layout_below="@+id/edt Address!
itemView.findViewById(R.id.imgContact); contentValues(); android:text="select"
}
} ContentValues.put("name", name); android:layout-toRight-of="@+id/btnInsert" />
}
OUTPUT content Values.put("address", address); 4 . # Creating Activity #SQ+eExampe.java

//updating row db.update (myTable, content Values public class Solite Example extends
(id=?, new String CJ (id); AppCompatActivityS EditText edtid, edt Name,
ed+Address; Button btnInsert, btnSelect, btn Update, !!!, LENGTH_SHORT).show();
btnDelete;
}});
TextView +x+Data; MyDbHelper my Db Helper, }}

@Override

protected void onCreate(Bundle b) {

Super.onCreate(b);

SetContentView(R.layout.Sqlite-example), myDb
Helper = new MyDb Helper (this)

edt Address findViewById(R.id.ed+ Address); bin


Insert = findViewById(R.id. btnInsert);

d edtId = findViewById(R.id.ed there); edt


Name:findViewById(R.id.ed+Name);
+x+Data=findViewById(R.id.txt Data);

btnSelect findViewById(R.id.btnSelect); btn Update =


findViewById(R.id.btnUpdate);

btn Delete indview By Id (R.id.btnDelete); =

binInsert setOnClickListener(new
View.OnClickListener US

@override
public void on Click (view view){

int id: Integer.parseInt(echid.getText().toString());


String name-ed+Name.getText().toString(); String
Address ed+Adbhress getText().toString());

mybbHeper insert Data (id, name, address);

Toast.makeText(get Application Context(), 'Deita


Inseated"); Toast LENGTH SHORT. Show();
}});

btnSelect.setOnClickListener(new
View.OnClickListener($

@overide int id:0;

String name=" "address" ";

Cursor cursor my DbHelper. Select Data(); Cohile


(cursor.moveToNext()){

id= cursor.getInt(0);

name= cursor.getString(1); address-


cursor.getString(2);

++ Data setText("Id="+id "+Name+name+1+Address


="+address);
}});

btnUpdate.setOnClickListener(new
View.OnClickListenerus
@overide

public void onClick(View view) { String id:


edtid.geText().toString();

String name edt Name.getText().toString(); String


address = edt Address getText().toString();

my DbHelper updateData (id,name, Address);


Toast.makeText(getApplication Context()," Data
Upda Hed!!! Toast.LENGTH_SHORT) Show);
}
});

binDelete setOnClickListener(new view.


OnclickListener(){ @Override

public void onClick (view view) { String


id=edt.getText().toString() myDbHelper.deleteData
lid),

Toast makeText(getApplication Context(),"Data


Deleted"

You might also like