Unit II

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

UNIT II

UNIT II - NATIVE APP DEVELOPMENT USING JAVA

Native Web App, Benefits of Native App, Scenarios to create Native App, Tools for creating
Native App, Cons of Native App, Popular Native App Development Frameworks, Java &
Kotlin for Android, Swift & Objective-C for iOS, Basics of React Native, Native
Components, JSX, State, Props.

I. NATIVE WEB APP

Web Native is an approach to cross-platform mobile application development that uses


web technologies to create native mobile applications for iOS and Android, as well as
mobile-optimized Progressive Web Apps.

Web Native apps are built utilizing modern web technologies and the web platform while
embracing the full native functionality available on modern mobile devices. Web Native apps
look and feel like other native apps because they fully support the UI patterns of each
platform they run on.

Web Native is a term coined by the Ionic team to characterize the development approach
used when building apps with Capacitor, an open source cross-platform native bridge built
and maintained by the Ionic team. Capacitor is used as the foundation for all apps built with
the Ionic SDK. Capacitor is also a popular choice for web developers building apps outside of
the Ionic ecosystem, using their web-based UI library of choice.

The primary advantages of Web Native development are:

 Excellent native mobile performance


 Faster time to develop an application
 Use of familiar web technologies, frameworks, and languages
 Complete customization of the UI layer of the application
How is “Web Native” different from “Hybrid”?
Hybrid apps have come to be associated with apps built using PhoneGap/Cordova, a
project created in 2009. PhoneGap/Cordova focused on implementing experimental Web
APIs before browsers did, by extending native Web View components available on
iOS/Android/etc. And creating essentially a more capable “browser” for each platform.
The expressed goal of PhoneGap/Cordova was to “cease to exist” by having these
experimental Web APIs be replaced with browser functionality in the Web View once
vendors caught up. Thus, PhoneGap was true to its name in bridging the gap between mobile
and web.

1
Additionally, PhoneGap/Cordova was created in a previous generation of web
technologies where there was not a proliferation of powerful app frameworks or UI libraries
focused on bringing native mobile experiences to the web.
In contrast, Web Native centers around using the full power of modern web
technologies and the ecosystem around them to build high-quality mobile apps utilizing the
full native functionality available on each platform.
Web Native apps do not attempt to abstract away the details of each platform. Rather,
they utilize tools like Capacitor that make it relatively trivial to extend a modern web app
with rich native functionality when necessary.
Web Native apps look and feel like any other native app because they utilize powerful
APIs and native functionality available to them, focus on rich and fluid animations, and fully
match the UI systems native to each platform.
Truly Native
Web Native apps are truly native, in the sense that they are downloaded from the app
stores and installed as an IPA or APK file on a mobile device. They have full access to the
native operating system and can access any native device API. Most Web Native runtimes,
like Capacitor, include a library of prewritten native APIs for accessing common device
functionality. You can also drop into the native platform and write your own custom APIs to
interface with any feature available on the device - the same way as traditional native
development. There is literally nothing that you can’t access so Web Native apps are indeed
truly native.
Truly Web
At the same time, Web Native apps are fully web-based. The UI layer of your Web
Native app executes in a web browser on the mobile device, known as a Web View control.
This means that anything you can do in a web application can be done in a Web Native app.
Want to use ag-grid for data visualization? You can do that in a Web Native app! Have other
web libraries you want to take advantage of? Anything that runs on the web can be
incorporated into a Web Native app. The same goes for web UI libraries like Material UI or
Bootstrap. And if you’d like to customize the look and feel to match your brand colors, fonts,
or other stylings, you can do that easily using the same CSS customizations that you’re
already familiar with. The short story is that if you’re a web developer looking to build
mobile apps, you’ll be right at home using a Web Native approach.

2
Why Web Native?
Native Mobile and Web in One Codebase
Web Native apps embrace the “build once, run everywhere” mantra. Since they are
built using web technologies - aka “web-first” development - this provides the best
opportunity to reach the most platforms.

Using Web Libraries


Since a Web Native app is a web application at its core, any web library can be used.
With thousands of them available, and many that you’ve likely used previously in desktop
web apps you’ve built, the opportunities to reuse existing work are endless.
Using Web UI Components
Much of the work in building Web Native applications consists of building interactive
user interfaces. Teams typically spend most of their time making sure it works well on mobile
form factors and has a mobile UI experience that users expect (UI frameworks like Ionic
Framework provide this experience out of the box).
Custom CSS Styling
With modern CSS practices applied, it’s easy to create a Web Native app that matches your
brand or theme. This includes support for dark mode, CSS variables (reference a value in
multiple places, change CSS dynamically at runtime, etc.), and encapsulation of styles in UI
components with Shadow DOM.
How does Web Native work?
Web to Native Communication via the Native Runtime and Bridge
The Web View accesses native functionality by passing messages over the native
bridge through to the native runtime. After the runtime has executed native code, a message
containing data and the result of the call (success/failure) is sent back to the Web View.
Native Bridge
The Web View needs a way to access native functionality, interact with OS level native
controls, and access custom native code or 3rd party plugins. It does that using the native
bridge inside of Capacitor.
The native bridge is where Capacitor’s runtime JS API, including all known native
plugins and their methods, are exported to the Web View. Capacitor loads all known plugins
that have been installed or coded directly into the native project, and then exports

3
window.Capacitor.Plugins containing every loaded plugin and every known method that
plugin has exported to the Web View.
Finally, the bridge manages message passing and tracking native invocations between
the Web View and the native runtime.
Native Runtime
Calls to native plugins and custom native code are routed from the Web View to the
native runtime. When the Web Native app first starts, the runtime loads any installed plugins
and custom native plugins. The runtime also initializes the Web View and injects the
JavaScript Symbols for all known plugins into the Web View.
When plugins are invoked, the runtime processes each invocation as a message,
constructs a method call to the corresponding plugin, and executes it.
All calls in Capacitor are asynchronous, so the runtime manages a set of “active” calls
that have yet to be completed. These calls might be as simple as calling a Native API, or as
complicated as opening an intent and processing the result of another app (such as the
Camera on Android).
Once those calls are complete, a message is constructed and sent back to the Web
View, which ultimately causes the original plugin call in your app to resolve.
Web UI Layer
The web UI layer runs the web application, consisting of HTML, CSS, and JavaScript. All
visual interactivity, animations/gestures, and UI components are found here. Open source UI
libraries like Ionic Framework are available to make sure the app looks and feels the way you
would expect from a native mobile app, including mobile-optimized navigation, gestures, and
animations.
Accessing Native Device Features
Unsurprisingly, native code needs to be written to access native features. However,
this is abstracted away from the web developer via plugins, packages of code that
communicate with the native platform. The web developer makes calls to JavaScript APIs
exposed by the plugin, and Capacitor executes the underlying native code. Besides the benefit
of not needing to learn the iOS and Android-specific programming languages, Capacitor
seamlessly calls web code when required and native code when available using the exact
same API. As an example, instead of three separate APIs to open a device’s camera
(getPhotoWeb, getPhotoiOS, getPhotoAndroid), it’s just one: getPhoto.

4
Capacitor apps are native apps. The project files used to build the native iOS and
Android binaries are a plain iOS app for Xcode and a plain Android app using Gradle. This
means teams can add arbitrary native code to the app and invoke it from the Web View
through the Capacitor Plugin API. Teams with web and native developers can work alongside
each other, shipping new features faster than ever.
Web View Component
A Web View is a native browser control that is used to display web content. It’s a lightweight
instance due to being chrome-less (standard browser UI shell elements including the address
bar, tabs, and navigation buttons aren’t included). Thus, visually, there’s not much to it - only
the browser engine is available, and the developer decides which content to display to the end
user.
You’ve likely interacted with a Web View and didn’t know it, as they are used in
native apps all the time. Beyond Web Native apps, one common use case is in-app browsing,
where a website is loaded (with limited navigation controls) within the app. This is useful for
content that changes regularly, such as customer support documentation. Teams can update
the documentation at their leisure, and native app users always get the latest information.
Another example is 3rd party authentication, such as logging users in with social media or
various email providers. The user is directed to the 3rd party, signs into that service, then is
redirected back to the native app with only the data needed to securely authenticate them.
Another Web View use case is advertising. Since ads change dynamically based on the user
viewing them, loading them from the web is the easiest way to manage and deploy them.
Deploying to App Stores
Because Web Native apps are normal native apps at the end of the day, the way they
are deployed to the App Stores is just like any other native app. Developers use the native
integrated development environments (IDEs) - Android Studio and Xcode - to build and
compile each native app version. The app files (APK and IPA) are signed with a private key
representing the developer/company, then are uploaded to the app stores. The last mile of app
store deployment is managed within the app store portals, including release management,
marketing and promotional materials, user reviews, and more.
Deploying as a Mobile Web App or PWA
Web Native apps are simply web apps, so normal deployment capabilities and rules
apply. When you’re ready to publish your Progressive Web App and share it with the world,

5
just upload the contents of your web directory (for example, the www/ or build/ folder) to
your hosting provider of choice.
II. SCENARIOS TO CREATE NATIVE APP

iOS Native App Development:


1. Define Requirements:
Understand the purpose and requirements of the app.
Define features, functionalities, and target audience.
2. Choose Development Tools:
Install Xcode: Apple's integrated development environment (IDE) for macOS.
Familiarize yourself with Swift or Objective-C, the primary programming languages for iOS
development.
3. Design UI/UX:
Sketch out app wireframes and designs.
Use tools like Sketch, Adobe XD, or Figma for designing.
4. Development:
Start coding according to the defined requirements using Swift or Objective-C.
Implement UI elements using Interface Builder or programmatically.
Utilize iOS frameworks such as UIKit, CoreData, etc., for various functionalities.
5. Testing:
Perform unit tests, integration tests, and UI tests using XCTest or third-party testing
frameworks like Appium or EarlGrey.
Beta testing with TestFlight for gathering feedback from users.
6. Debugging and Optimization:
Use Xcode's debugging tools to identify and fix issues.
Optimize app performance and memory usage.
7. Submission:
Register for an Apple Developer account.
Create App IDs, provisioning profiles, and certificates.
Submit the app to the App Store via App Store Connect.
8. Release and Maintenance:
Monitor user feedback and analytics.
Release updates with bug fixes and new features.

6
Android Native App Development:
1. Requirements Gathering:
Define the purpose, features, and target audience of the app.
2. Setup Development Environment:
Install Android Studio: Google's official IDE for Android development.
Familiarize yourself with Java or Kotlin, the primary programming languages for Android
development.
3. Design UI/UX:
Create wireframes and designs using tools like Adobe XD, Sketch, or Figma.
4. Development:
Start coding according to the defined requirements using Java or Kotlin.
Design UI using XML layout files or programmatically.
Utilize Android SDK and frameworks like Android Jetpack, Room, Retrofit, etc.
5. Testing:
Perform unit tests, integration tests, and UI tests using JUnit, Espresso, or Robolectric.
Test on various devices and screen sizes using emulators or physical devices.
6. Debugging and Optimization:
Use Android Studio's debugging tools to identify and fix issues.
Optimize app performance and battery usage.
7. Publication:
Create a developer account on Google Play Console.
Generate signing keys and build release APKs.
Upload the APK and necessary metadata to Google Play Console.
8. Release and Maintenance:
Monitor app performance, reviews, and analytics.
Release updates as needed, addressing user feedback and adding new features.

III. TOOLS FOR CREATING NATIVE APP


Here is a list of top 11 Mobile App Development Tools:
 React Native
 Flutter
 Xamarin

7
 Ionic
 jQuery Mobile
 Sencha Ext JS
 Framework 7
 Onsen UI
 Unity
 Qt-Creator
 JetBrains Rider
When you conduct a research to know the top tools for Mobile App Development, you
arrive at these names. Mobile apps need to house several key functionalities so that they
provide businesses with operational efficiencies, drive profitability, improve resource
productivity, and assure consistent performance. All this is achievable with a mobile app
when you build it using the finest mobile app development tools. Let’s take a closer look at
top 11 mobile app development tools using which you can build your dream mobile apps.
1. React Native
A popular JavaScript-based mobile app development framework, React Native is
distinguished by its ability to assist in the simultaneous development of apps for iOS and
Android. While Java and Swift or Obj-C are bare minimum requirements for Android and
iOS respectively. However, React Native uses one common codebase to overcome this
limitation and helps build multi-platform applications.
It was launched in 2015 by Facebook and has continued to grow stronger and stronger
since then. Today, ask any professional software development company, and you would find
it using React Native. It has been used by top names such as Facebook and Uber, which
proves its authenticity as one of the top mobile app development tools.
Why Choose React Native?
 Constantly growing community that comprises app developers from esteemed
organizations such as Facebook.
 State management, React hooks, and component logic can be reused
 For both iOS and Android apps, the code can be effectively reused.
 Excellent third-party integration, supporting integration with JavaScript modules and
Native modules, and libraries.

8
 Supported by hot and live reloading functionality, developers can execute code
changes in real time.
 Gives developers the ability to remain UI-focused during the development process.
2. Flutter
Based on the Dart programming language, Flutter is an open-source SDK (software
development kit) that was developed by Google. Because of its affordability, development
speed, and extensive feature set, Flutter SDK not only satisfies the needs of large
corporations but also seamlessly integrates into the startup environment.
Like React Native, Flutter, too, helps in simultaneously building apps for iOS and
Android, and so is one of the most-used app development frameworks by app developers.
Why Choose Flutter?
 Unique feature called ‘Hot reload’ allows developers to render changes fast, making
changes instantly reflect on the UI.
 Provides ability to root out bugs in the development cycle itself.
 Complex widgets can be developed and adjusted as per the needs of the application.
 You can leverage existing Swift, Java, and Objective-C codes to access native
functionalities such as location and camera.
 Developers have backend support from Google Firebase that strengthens their
confidence to build scalable apps.
3. Xamarin
There is nothing better than Xamarin to build native apps. Since it is a Microsoft
product, you will always be safe against unexpected termination of service, critical security
threats, and technology updates.
More than 1.4 million developers use Xamarin, which means talent scarcity will not
be a challenge for you when it comes to building your own mobile app development team.
Why Choose Xamarin?
 Mono framework that exposes 100% of the native APIs to allow full use of device
capabilities
 Platform-specific IntelliSense makes coding easier
 Application indexing and deep linking
 Easy cycle of build, test, deploy, and repeat using C++ programming language

9
 Possible to use enterprise or social authentication, push notifications, offline sync
features
 Ability to create high-performance shared libraries.
 It’s one of the tools favored by software development companies that build enterprise
apps and software.
4. Ionic
Since Ionic has a complete open-source SDK, it is widely used to build hybrid
applications using CSS, HTML5, and SASS-like technologies. By building a mobile
application on Ionic, app developers can directly send the release update to the users.
Automating app delivery is much easier with Ionic. Equipped with these capabilities,
developers can easily deploy features and fixes to increase the speed of mobile app
development.

Why Choose Ionic?


 Deliver app updates, bug fixes, and content changes without requiring MDM approval
or waiting for app store approval
 Ability to automate workflow, from native binary builds to QA
 Native app binaries can be created in the cloud with Ionic package
 Central, shared dashboard with live activity feeds
 Industry-specific defaults and pre-built workflows to automate development tasks
5. jQuery Mobile
jQuery Mobile is an HTML5-based UI system that has been built on jQuery,
providing a range of UI elements and features specifically for mobile apps. If you are looking
for a tool to develop cutting-edge web apps for mobile and tablets, then undoubtedly, jQuery
Mobile is the tool you must use.
With jQuery Mobile, we can enrich web pages by adding touch-friendly form inputs,
enabling quicker page loading, and offering expanded device support. This efficiency of
jQuery can be attributed to its lightweight code that offers flexible designs.
Why Choose jQuery Mobile?
 With little to no JavaScript code, developers can create the entire application
interfaces in HTML.
 Ajax helps resolve complex large code structures into a few lines of code.

10
 Excellent support to both high-end as well as less capable devices – those that do not
support JS.
 Apps are accessible over a wide range of devices and browsers.
 The transition from the currently active page to the new page can be animated using
jQuery Mobile transition events easily
 The framework also includes many kinds of simply styled and touch-friendly form
elements.
 Ability to determine ownership over application styling, cross-platform widgets, and
Themeroller take UI and Theming to the next level.
6. Sencha Ext JS
Sencha is for rapid mobile app development. If you want to create a native app that is
compatible with the latest versions of iOS and Android, Sencha should be your ideal choice.
It is one of the most suitable app development tools for building enterprise applications..

It is an MVC-based JavaScript framework that enables the developers to use it


through a touch of fingertips, which also helps in increasing the responsiveness of the
application. HTML5 mobile app developers well-versed in Sencha can use it for Android as
well as iOS applications without any hassles.
Why Choose Sencha?
 More than 115 fully supported components can be integrated with a wide range of
frameworks such as Angular, FOSS, and more
 Commercially supported UI widgets for menus, toolbars, and lists
 End-to-end testing solution for Ext JS
 Reduce dependencies on multiple libraries and versions.
 Single code paradigm across all components
 Good community strength
7. Framework 7
Framework 7 is used to create native iPhone applications. Although, recently they have
started providing support for Android apps.
This open-source, mobile HTML framework is easy to understand and builds native apps
faster. As a result, you will find an esteemed iPhone app development company using
Framework 7 in its mobile app development projects.

11
Why Choose Framework 7?
 It works in a simple HTML layout attached with CSS framework and JS files
 iOS-specific UI elements visualization, animations, and touch interaction
 A wide range of ready-to-use UI elements and widgets such as list views, media lists,
modals, popups, form elements, and more
 Support iOS swipe-back action from the left border of the screen
 Ability to introduce custom styles to your applications
 Enhanced video ad experience by partnering with vi (Video Intelligence)
8. Onsen UI
When you want to build Progressive Web Apps (PWAs) and hybrid apps for your
mobile devices, Onsen UI is one tool that must be on the list of your tools. As the name
suggests, it houses a large range of UI components specially for mobile devices.

The best thing about Onsen UI is that developers have the independence to build apps
with or without JavaScript. This framework-agnostic character of Onsen UI makes it a
favorite of mobile app developers.
Why Choose Onsen UI?
 Offers an easy learning track, so developers can pick it up fast.
 Can be set up very easily, since it is based on HTML, CSS, and JS.
 Ready-to-use and easy-to-implement UI components such as toolbar, side menus,
tabs, lists, forms, etc.
 No strict rule to install Android SDK or iOS – just begin coding and start building
applications.
 Excellent support for command-line tools like Monaca, which helps build hybrid
apps.
 Supports integration with AngularJS, React, Vue, and jQuery.
9. Unity
Unity’s fame as a game development app tool is widely acknowledged. Millions of
developers use the Unity game engine to build gaming apps for all kinds of platforms,
including Android, Windows, iOS, etc. Supported by its streamlined workflow and
impeccable user interface (UI), as well as its extensive set of features, it is one of the most
widely used game engines on the Android platform.

12
Even while Unity is primarily designed for building gaming apps, it can be effectively
used to build non-gaming apps for businesses, utilities, etc.
Why Choose Unity?
 Quick and easy development support that speeds the app development process
 C#-based development that simplifies coding complexities
 Excellent code support helps in quickly increasing the app size.
 Ability to scale the app to different devices
 Optimal performance with large apps
 A very powerful community with developers from industry stalwarts such as Disney,
NASA, Ubisoft, Microsoft, Electronic Arts, and Warner Bros.
10. Qt-Creator
A cross-platform IDE (integrated development environment), Qt-Creator offers
various tools for different tasks. For instance, it has a source code editor, a testing tool, an
Integrated GUI layout, and a visual debugging tool for monitoring the app.
Qt is based on a combination of C++, JavaScript, and QML (Qt Modelling
Language), though C++ forms most of Qt. The beauty of Qt is that it is based on the idea of a
custom rendering engine approach that reuses not just the app’s logic but also the UI.
Why choose Qt-Creator?
 Quick integration with external SDKs such as AWS and PayPal.
 Declarative syntax offers flexibility to compose complex user interfaces
 Simple-to-implement property binding approach that simplifies making changes.
 Comes with a range of features such as touch-based inputs, shader effects, controls,
and animations.
 Powered by C++, developers can interact with native APIs.
 Equipped with necessary tools, Qt Quick test framework speeds up testing.
11. JetBrains Rider
Based on IntelliJ Platform and ReSharper, JetBrains Rider is a cross-platform.NET
IDE that is quick and packed with features. It has a thorough understanding of all.NET
languages and technologies, and so is used by millions of developers across the globe.
A fundamental goal of all JetBrains products is to increase developer productivity.
Further, Rider demonstrates its value as a wonderful tool for a software development
company and a business that wants to develop a next-gen mobile app.

13
Why choose JetBrains Rider?
 Developers can build .Net, Xamarin, and Unity apps for different platforms.
 Rich editing and code insight for various programming languages.
 Uses many useful and powerful features of the IntelliJ platform.
 Instantly detects errors in compilation and runtime operations.
 Promotes optimal design and development methods that minimize redundancy and
enhance coding.
 With numerous intelligent navigation and search options, developers may quickly get
to any section of their code.
 Rich plugin repository that comes with a wide array of plugins.
Conclusion
Choosing mobile app development tools from a plethora of options available in the
market is tough, only when you are not fully aware of your requirements.
So, before you venture out to seek the best mobile application development tool for
your project, create a set of your requirements and compare it with the features of the
tools.Whether you are looking to build cross-platform app with Flutter or a .NET application
development company with expertise in Xamarin, or native apps using Java app development
or iOS, Besides, you can always consult a reliable mobile app development company to better
understand the tools.

IV.CONS OF NATIVE APP


1. Platform-specific Development:
Cons: Developing separate codebases for each platform (iOS and Android) can be time-
consuming and resource-intensive. It requires expertise in different programming languages,
frameworks, and development environments.
Impact: This increases development costs and can extend the time to market. Maintaining
two separate codebases also requires additional effort for updates, bug fixes, and feature
enhancements.
2. Higher Development Cost:
Cons: Native app development often involves higher upfront costs compared to cross-
platform or web app development. This is primarily due to the need for specialized skills,
longer development cycles, and multiple codebases.

14
Impact: For businesses or startups with limited budgets, native app development may pose
financial challenges. It may require more significant investment upfront, potentially affecting
the overall project budget and ROI.
3. Longer Development Time:
Cons: Building native apps for multiple platforms requires separate development efforts,
resulting in longer development cycles. Each platform has its own set of design guidelines,
APIs, and development processes, leading to increased complexity and time requirements.
Impact: Longer development times can delay the app's launch, impacting time-sensitive
projects or market opportunities. It may also increase the risk of competitors launching
similar apps ahead of schedule.
4. Limited Audience Reach:
Cons: Native apps are platform-specific, meaning they can only run on the operating systems
for which they were developed (iOS or Android). This limits the potential audience reach
compared to cross-platform or web apps, which can be accessed across multiple devices and
platforms.
Impact: Businesses targeting a diverse audience may need to develop separate native apps
for each platform to reach all users effectively. This increases development costs and
maintenance efforts, especially for smaller businesses or startups.
5. App Store Approval Process:
Cons: Submitting native apps to app stores (e.g., Apple App Store, Google Play Store)
requires adherence to strict guidelines and review processes. Apps must comply with
platform-specific policies regarding content, functionality, security, and user privacy.
Impact: The app store approval process can introduce delays in releasing updates or new
features. Apps that fail to meet the guidelines may be rejected or removed from the app store,
requiring developers to make revisions and resubmit, further extending the timeline.
6. Updates and Maintenance:
Cons: Maintaining multiple native apps requires ongoing updates, bug fixes, and
compatibility testing for each platform. This can be challenging and time-consuming,
especially as new OS versions, devices, or hardware features are introduced.
Impact: Continuous maintenance and support are essential to ensure optimal performance,
security, and user experience. Neglecting updates or failing to address compatibility issues
may result in user dissatisfaction, negative reviews, and loss of market share.

15
V. JAVA AND KOTLIN FOR ANDROID

Introduction:

Java: Java is a high-level, object-oriented programming language developed by Sun


Microsystems (now owned by Oracle). It's known for its platform independence, which
means Java code can run on any device that has a Java Virtual Machine (JVM).

Why Java for Android?:

Official Language: Java was the first official programming language for Android app
development, supported by Google's Android SDK (Software Development Kit).

Mature Ecosystem: Java has a mature ecosystem with extensive documentation, libraries, and
community support, making it well-suited for building complex and feature-rich Android
apps.

Performance: Java offers good performance on Android devices, and developers have fine-
grained control over memory management and system resources.

Interoperability: Java code can easily interact with Android's native APIs and libraries,
allowing developers to access device features like camera, sensors, and GPS.

Key Features of Java for Android:

Object-Oriented: Java follows an object-oriented programming paradigm, which facilitates


code organization, reuse, and maintenance.

Platform Independence: While Android runs Java bytecode on its Dalvik or ART virtual
machines, developers write code in Java, which can be compiled to bytecode and executed on
any platform with a compatible JVM.

Rich Standard Library: Java comes with a rich standard library that provides classes and
methods for common programming tasks such as input/output, networking, data structures,
and more.

Exception Handling: Java has robust exception handling mechanisms, allowing developers
to handle errors and exceptions gracefully, which is crucial for building stable and reliable
Android apps.

Garbage Collection: Java features automatic garbage collection, which manages memory
allocation and deallocation, simplifying memory management for developers.

Development Tools:

Android Studio: Android Studio is the official Integrated Development Environment (IDE)
for Android app development. It provides advanced features like code completion,
debugging, and project management tailored specifically for Android development.

16
SDK Tools: The Android SDK includes tools for compiling, debugging, and packaging
Android apps. Developers use tools like ADB (Android Debug Bridge), SDK Manager, and
AVD Manager for various development tasks.

Android App is mostly developed in JAVA language using Android SDK (Software
Development Kit). Other languages like C, C++, Scala etc. can also be used for developing
Android App, but JAVA is most preferred and mostly used programming language for
Android App Development. So if you are a beginner in Android then JAVA language and
complete knowleadge of OOPS concepts is the first thing you need to learn before beginning
Android Development.

Introduction To JAVA

JAVA is a programming language which is used in Android App Development. It is


class based and object oriented programming whose syntax is influenced by C++. The
primary goals of JAVA is to be simple, object-oriented, robust, secure and high level.

JAVA application runs on JVM (JAVA Virtual Machine) but Android has it’s own
virtual machine called Dalvik Virtual Machine (DVM) optimized for mobile devices.

Prerequisites For JAVA:

Eclipse:

Being a JAVA programmer you will need some tools or software to code and run it.
Lots of tools are available over the web but we recommend you to use Eclipse for learning
JAVA since it is the most common tool used for Android Development alongwith Android
Studio. So getting habitual with Eclipse and its shortcuts will be bonus in your Android
journey. Other then Eclipse you can also prefer IntelliJ or netbeans for learning JAVA.

Other Tools: IntelliJ and Netbeans

Android Studio? Are you thinking of using Android Studio for learning JAVA? Then
Android Studio is solely meant for Android programming. IntelliJ, Eclipse and Netbeans are
for real Java codings.

VARIABLES:

Variables is something that makes computer program very useful by storing


information in memory. When you think of variables think of boxes which is used to store
something. In computer world you can have hundreds, thousands or more number of boxes
(mean variables) each containing their own pieces of information. That box is called variables
in JAVA.

While creating variables in JAVA we need to assign two things. First is the type of
information we want to store and second is the name of the variable. Below is an example of
variable where int is a type of information (integer in this case) and x is the name:
17
Object-Oriented Language: Java is an object-oriented programming language,
which means it revolves around the concept of classes and objects. Everything in Java is
either a class or an object.

Main Method: Every Java program starts with a main method, which serves as the
entry point for the program. In Android, the main method is not explicitly used; instead, the
entry point for the app is the onCreate() method of the main activity.

Classes and Objects: Classes are blueprints for objects. They define the properties
(fields) and behaviors (methods) of objects. You can create instances of a class, called
objects, and work with them.

Packages: Java classes are organized into packages. Packages help in organizing your
code and avoiding naming conflicts. In Android, packages are used to organize components
of an app.

Variables and Data Types: Java supports various data types, including int, float,
double, boolean, etc. Variables are used to store data of a specific type. Android developers
often work with data types such as Strings, integers, floats, etc., to manage application data.

Control Flow Statements: Java supports control flow statements like if-else, switch-
case, loops (for, while, do-while) to control the flow of execution in a program. These are
used extensively in Android programming to make decisions and iterate through data
structures.

Inheritance and Polymorphism: Java supports inheritance, where a class can inherit
properties and behaviors from another class. Polymorphism allows objects of different classes
to be treated as objects of a common superclass.

Interfaces and Abstract Classes: Interfaces define a contract for classes to


implement, while abstract classes provide a partial implementation that subclasses can
extend. Both are essential concepts in Java and are used in Android development for defining
contracts and providing reusable implementations.

Exception Handling: Java provides mechanisms for handling errors and exceptions
gracefully. This is crucial in Android development to ensure the stability of the app, as
unexpected errors can occur during runtime.

Collections Framework: Java provides a rich set of data structures through its
Collections Framework, including lists, sets, maps, etc. These are extensively used in
Android development for managing and manipulating data efficiently.

18
Example:

// MainActivity.java

// Importing necessary Android libraries

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.widget.TextView;

// MainActivity class definition, extending AppCompatActivity

public class MainActivity extends AppCompatActivity {

// Overriding the onCreate method

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main); // Setting the layout for the activity

// Finding the TextView widget defined in the layout

TextView textView = findViewById(R.id.textView);

// Setting the text of the TextView widget to "Hello, World!"

textView.setText("Hello, World!");

We create a class MainActivity that extends AppCompatActivity, which is a base


class for activities in Android.

We override the onCreate method, which is called when the activity is first created.

Inside onCreate, we call setContentView to set the layout for the activity. The layout
is defined in an XML file (activity_main.xml), which typically resides in the res/layout
directory of the Android project.

We find the TextView widget with the id textView using findViewById.

Finally, we set the text of the TextView to "Hello, World!" using the setText method.

19
To accompany this code, you would also need to define the layout in an XML file named
activity_main.xml. Here's an example of what that XML might look like:

<!-- activity_main.xml -->

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="24sp"

android:textStyle="bold"

android:layout_centerInParent="true"

android:text="Hello, World!" />

</RelativeLayout>

This XML layout file defines a RelativeLayout containing a single TextView with the
id textView, which will be used to display the "Hello, World!" message.

KOTLIN FOR JAVA


Why Kotlin For Android?

Since Android took the world by storm, developers have had few alternatives to Java
for app development. Java was the programming language that the most advanced phones
were using to run their native apps on their proprietary operating systems. For example,
Nokia’s Symbian had Java ME apps. Although its usage is widespread, Java comes with a lot
of historical baggage.

Java 8 solved some language issues and even more were corrected with Java 9 and 10.
Unfortunately, you have to set the minimum SDK to Android 24 to use all of Java 8’s
features, which isn’t an option for many developers. The fragmentation of the Android
20
ecosystem makes it impossible to leave out users with older devices. For most developers,
Java 9 and 10 aren’t even on the radar.

Kotlin is the modern programming language solution for Android. There are a few
things that make Kotlin a great fit for Android:

Compatibility: It’s compatible with JDK 6, so older devices aren’t left behind.
Performance: It’s on par with Java.
Interoperability: It’s 100% interoperable with Java including annotations.
Footprint: The runtime library for Kotlin is tiny.
Compilation Time: There’s a little overhead on clean builds but it’s way faster with
incremental builds.

Learning Curve: It’s easy to learn, especially for people used to modern languages. The Java
to Kotlin converter in IntelliJ and Android Studio makes it even easier. You can also use a
mix of Kotlin and Java in a project, so take your time learning Kotlin and add it in when you
feel comfortable.

While Java 8 is now supported on recent Android releases, recent developer surveys say that
Kotlin is gaining ground. The Realm team notes that ”Kotlin is about to change the whole
Android ecosystem.” Kotlin is now one of the most loved programming languages out there.
It’s poised to dominate Android app development. Above all, it’s a new language! What
could be more exciting? iOS developers had their fun in 2014 with Swift. Now, it’s your turn.
:]

Getting Started

For this tutorial, you’ll explore Kotlin by working with an app that allows users to
search for books, see book covers and share books with friends.

Download the materials using the Download Materials button at the top or at the
bottom of this page. Extract and open the starter project in Android Studio 3.3 or later.

It contains three source code files written in Java:

MainActivity.java: An Activity that displays the screen for searching and displaying a list
of books.

DetailActivity.java: An Activity that displays the book cover for the ID passed to it.

JSONAdapter.java: A custom BaseAdapter that transforms a JSON object into a list view
item.

Kotlin is a statically typed, general-purpose programming language developed by


JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It
21
was first introduced by JetBrains in 2011 and a new language for the JVM. Kotlin is object-
oriented language, and a “better language” than Java, but still be fully interoperable with
Java code.
Kotlin is sponsored by Google, announced as one of the official languages
for Android Development in 2017.
Example of Kotlin –

fun main()
{
println("Hello Geeks");
}

Key Features of Kotlin:


1. Statically typed – Statically typed is a programming language characteristic that
means the type of every variable and expression is known at compile time. Although it is
statically typed language, it does not require you to explicitly specify the type of every
variable you declare.
2. Data Classes– In Kotlin, there are Data Classes which lead to auto-generation of
boilerplate like equals, hashCode, toString, getters/setters and much more.
Consider the following example –

/* Java Code */
class Book {
private String title;
private Author author;
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public Author getAuthor()

22
{
return author;
}
public void setAuthor(Author author)
{
this.author = author;
}
}

But in Kotlin only one line used to define the above class –
/* Kotlin Code */
data class Book(var title:String, var author:Author)
3. Concise – It drastically reduces the extra code written in other object-oriented
programming languages.
4. Safe – It provides the safety from most annoying and irritating
NullPointerExceptions by supporting nullability as part of its system.
Every variable in Kotlin is non-null by default.
5. String s = "Hello Geeks" // Non-null
If we try to assign s null value then it gives compile time error.So,
s = null // compile time error
To assign null value to any string string it should be declared as nullable.
String nullableStr? = null // compiles successfully
length() function also disabled on the nullable strings.
6. Interoperable with Java – Kotlin runs on Java Virtual Machine(JVM) so it is
totally interoperable with java. We can easily access use java code from kotlin and kotlin
code from java.
7. Functional and Object Oriented Capabilities – Kotlin has rich set of many useful
methods which includes higher-order functions, lambda expressions, operator
overloading, lazy evaluation, operator overloading and much more.
Higher order function is a function which accepts function as a parameter or returns a
function or can do both.
Example of higher-order function –
fun myFun(company: String,product: String, fn: (String,String) -> String): Unit {
23
val result = fn(company,product)
println(result)
}

fun main(args: Array){


val fn:(String,String)->String={org,portal->"$org develops $portal"}
myFun("JetBrains","Kotlin",fn)
}
Output:
JetBrains develops Kotlin
Smart Cast – It explicitly typecasts the immutable values and inserts the value in its safe
cast automatically.
If we try to access a nullable type of String ( String? = “BYE”) without safe cast it will
generate a compile error.
fun main(args: Array){
var string: String? = "BYE"
print(string.length) // compile time error
}
}
fun main(args: Array){
var string: String? = "BYE"
if(string != null) { // smart cast
print(string.length)
}
}
Compilation time – It has higher performance and fast compilation time.
Tool- Friendly – It has excellent tooling support. Any of the Java IDEs – IntelliJ IDEA,
Eclipse and Android Studio can be used for Kotlin. We can also be run Kotlin program from
command line.
Advantages of Kotlin language:
 Easy to learn – Basic is almost similar to java.If anybody worked in java then easily
understand in no time.

24
 Kotlin is multi-platform – Kotlin is supported by all IDEs of java so you can write
your program and execute them on any machine which supports JVM.
 It’s much safer than Java.
 It allows using the Java frameworks and libraries in your new Kotlin projects by
using advanced frameworks without any need to change the whole project in Java.
 Kotlin programming language, including the compiler, libraries and all the tooling is
completely free and open source and available on github. Here is the link for

Applications of Kotlin language:


 You can use Kotlin to build Android Application.
 Kotlin can also compile to JavaScript, and making it available for the frontend.
 It is also designed to work well for web development and server-side development.

Kotlin is a statically typed programming language that runs on the Java Virtual Machine
(JVM) and can be used for Android app development. It was developed by JetBrains and
officially supported by Google as a first-class language for Android development. Kotlin is
concise, expressive, and interoperable with Java, making it an excellent choice for building
Android apps.
Here are the basics of Kotlin:
Null Safety: Kotlin addresses the notorious NullPointerException (NPE) issue by
making all types non-nullable by default. If you want to allow null values, you must
explicitly declare a variable as nullable.
Extension Functions: Kotlin allows you to extend existing classes with new
functionality without inheriting from them. This is achieved using extension functions.
Smart Casts: Kotlin's type system includes smart casts, which eliminate the need for
explicit casting when checking types.
Data Classes: Kotlin provides a concise way to create classes that are only meant to
hold data. These data classes automatically generate equals(), hashCode(), toString(), and
copy() methods.
Coroutines: Kotlin introduced coroutines to handle asynchronous programming.
Coroutines simplify asynchronous code by providing a structured way to write asynchronous
code sequentially.
25
Immutable Collections: Kotlin provides immutable collections such as List, Set, and
Map by default. These collections cannot be modified after creation, which helps prevent
unexpected changes.
Interoperability with Java: Kotlin is fully interoperable with Java, meaning you can
use Kotlin code in existing Java projects and vice versa. This makes migration from Java to
Kotlin or mixing both languages in a project seamless.

Now, let's create a simple Android app using Kotlin:


Step 1: Create a New Project
Start by creating a new Android project in Android Studio. Choose "Empty Activity"
template.
Step 2: Write Kotlin Code
In the MainActivity.kt file, replace its content with the following code:
package com.example.myfirstkotlinapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Setting the text of the TextView widget to "Hello, World!" using Kotlin Android
Extensions
textView.text = "Hello, World!"
}
}
Step 3: Layout File
In the res/layout directory, find the activity_main.xml file and define the UI elements. Here's
an example layout:
<!-- activity_main.xml -->
26
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textStyle="bold"
android:layout_centerInParent="true"
android:text="Hello, World!" />
</RelativeLayout>
Step 4: Build and Run
Now, build and run your app. You'll see a "Hello, World!" message displayed on
the screen when the app launches.
In this example, we've created a simple Android app using Kotlin, demonstrating
how concise and expressive Kotlin can be for Android development.
VI. SWIFT OVERVIEW
Swift is a programming language developed by Apple. It was first announced in
2014 and released to the public in 2015.
Swift is easy to read and write and more resilient to errors than other languages. It
is an open-source language and can be used on many different platforms. It is compatible
with Objective-C and can be used to develop software for iOS, macOS, tvOS, watchOS,
and Linux.
Swift features
Swift, an advanced development on C-based codes, has some distinguishing features
that make it easier to read and write. A few of Swift's features include a powerful error
handling system, generics that are easy to use, a fast and concise iteration over a range of
collections, a functional programming pattern, tuples, multiple return values, and power
flow control.
27
 Automatic memory management system. With Swift’s Automatic Reference
Counting (ARC) feature that automatically handles memory management, a
programmer does not have to waste time and effort thinking about the memory a
project takes.
 Swift is easy to learn. Swift’s features make it one of the easiest codes to learn,
even for people without coding experience. Swift also has a playground where
beginners can easily and independently learn how to use Swift.
 Concise code syntax. Swift has a concise code syntax that enables developers to
perform much with few codes. It reduces the number of codes required for
repetitive statements and string manipulatio n.
 Swift is fast. Swift has an optimized compiler that generates faster code across
the board and relieves you of the burden and stress of bookkeeping.
 Safe programming language. The Swift programming language reduces the
possibility of making an error. Swift also eliminates tendencies of bugs by
triggering a runtime crash that compels programmers to fix the issue
immediately.
Swift advantages
A few key advantages of Swift include:
 Swift is fast. Swift's simple and direct syntax makes it over two times fast er
than Objective-C. Unlike Objective-C, Swift has new features that enable coders
to have a swift and seamless coding experience.
 Swift has an Automatic Reference Counting feature. The ARC feature helps
programmers manage an app's memory usage, which protects programmers from
wasting time.
 Swift's codes are easy to read and write. Swift algorithms are easy to read and
write, similar to Java, JavaScript, and other C languages. Swift is a modern
programming language with a relatively simplified and concise syntax.
 Swift has an open-source community. An open-source community is a
community of people who come together to build projects and share ideas about
their common area of interest. Swift has a publicly accessible open-source
community where you can learn new ideas about Swift.
 Swift offers playgrounds. Swift has an interactive playgrounds application you
can download on your iPhone, iPad, or Mac to learn how to use the Swift
28
algorithm and codes. Use these playgrounds to accelerate your learning of Swift
programming, even as a beginner.
 Swift is safe and less prone to error. Swift is designed in such a way that it
eliminates classes of unsafe code. It has a compiler feature that makes code
writing safer and prevents a series of runtime crashes in your apps.
Swift disadvantages
The Swift programming language has a few drawbacks.
 The language is still new. Unlike Objective C, which has existed since the
1980s, Swift is a new language created in 2014. Swift is a new programming
language and undergoes frequent updates, making it incompatible with previous
iOS versions.
 Backward compatibility issues. Backward compatibility refers to a software
feature that allows new updates to work with interfaces and data from earlier
system versions. Swift evolves, making new versions of Swift incompatible with
older versions of the iOS operating system. Swift supports projects that run on
iOS7 and macOS 10.9 or higher, thus driving developers who need to maintain
or build apps for older versions to use Objective-C.
 Interoperability with third-party tools and IDEs. Due to constant updates and
Swift’s lack of backward compatibility, finding third-party tools and Integrated
Development Environment (IDE) that communicate and function with Swift
isn’t easy. You can, however, use IDEs like Atom, App code, and Swift libraries
for Swift.
OBJECTIVE-C OVERVIEW
The Objective-C programming language is an object-oriented language used to
develop various apps and software, including iOS and OS X. It’s a superset of the C
programming language, meaning it can do everything C can. One of the main benefits of
Objective-C is its ability to dynamically load code, meaning you can use it to create
small, lightweight programs or large, complex programs.
The Objective-C programming language was invented in the 1980s by Brad Cox
and Tom Love. They both had prior knowledge of Smalltalk while at ITT Corporation's
Programming Technology Center, which further equipped them to develop Objective-C.
After creating the Objective-C programming language with class libraries, Cox and Love
created the PPI, which they intended to use to aid the commercialization of their product.
29
NeXT took over the Objective-C operation from StepStone and used it until Apple
acquired it in 1996.
Features of Objective-C
The Objective-C programming language has many appealing features, making it
invaluable in developing Apple's operating system and applications. These are:
 Data hiding. The Objective-C programming language uses data hiding as its
safety feature, significantly protecting data from unwanted access. The d ata
hiding safety feature aids in the prevention of deliberate or accidental changes
to the program and ensures that data access is restricted.
 Encapsulation. With the encapsulation feature on Objective-C, programmers
find it easier to limit other users from having direct access to the state values of
every object variable. This Objective-C feature further makes it easy to hide
data, adapt to new requirements, and flexibly set variables as either write-only
or read.
 Inheritance. As a user of Objective-C, you may want to create classes while
having an existing one. The inheritance feature of the Objective-C programming
language helps you achieve that. Besides creating classes, the inheritance
feature enables you to reuse code, autonomously prolong the origina l program
using accessible classes and interfaces, and design a modification while
preserving the same features.
 Fast program. The wish of every software developer is to engage in coding
without any unnecessary delay from the programming software or langua ge in
use. With the fast program feature of Objective-C, you can have this wish
granted as the programming language's design helps make programming more
efficient and quick.
 Polymorphism. The polymorphism feature of the Objective-C programming
language enables users to access different objects through the same interface.
The polymorphism feature has two types: static and dynamic.
Advantages of Objective-C
Objective-C as a programming language has countless benefits. A few of them are:
 Simple and efficient. The core grammar used to build the Objective-C language
is fairly straightforward to learn. The nature of Objective-C programming
language makes it easy to understand and facilitates a programmer's ability to
30
rebuild or develop a new application. It’s no wonder Objective-C is frequently
used as an introductory language to teach programming to students.
 An abundance of tools. Due to its over 30 years of use, Objective-C has a
wealth of tools. These include the XCode and Cocoa framework provided by
NeXT, third-party contributors, and Apple. These numerous tools play a
remarkable role in the smooth running of Apple's operating system and in
making developers feel more comfortable using it.
 Compatible with virtually any available version of iOS. Compared with Swift,
which can only work with iOS produced in recent times, the Objective -C
programming language is more compatible with nearly all versions of iOS. This
compatibility is due to its long years of existence and usage in producing many
Apple applications.
 Ability to extend. The Objective-C programming language was designed so a
program can be extended quickly and easily. As a result, programmers can
easily add new functions to existing software with just a few alterations, if any.
 Function-rich libraries. Objective-C designers equipped the programming
language with a sizable collection of libraries with many built -in features that
make programming simpler. Opportunities are also made for programmers to
develop their user-designed features and include them in t he library.
Disadvantages of Objective-C
Despite its numerous strengths, Objective-C still has a few key shortcomings.
 Time-consuming. Compared with modern programming languages like Swift,
Objective-C takes more time to program. The time-consuming factor of
Objective-C code can, in turn, cost programmers more and delay the launching
of their software applications.
 Syntax is complicated and tedious. Compared to other modern programming
languages like Swift, whose syntax resembles plain modern English, Objective-
C's syntax is more tedious and difficult to write.
Swift vs. Objective-C: the differences
Swift is newer than Objective-C and has many features that Objective-C does not.
Consider these key differences.
 Type inference. Swift has type inference, allowing the compiler to automatically
infer the type of a variable based on its value. This means that you don't have to
31
explicitly declare the type of a variable, which can save time and make your
code more concise.
 Polymorphism. Swift's protocols enable you to write code that can be applied to
any type that conforms to the protocol without knowing the specific type. In
contrast, Objective-C's categories run directly in compile time and can only be
used to extend the functionality of a specific type.
 Type safety. Swift uses value types instead of reference types, which means
variables are assigned a new copy of the data whenever they are modified. This
can help prevent aliasing issues.
 Dynamically typed. Objective-C is a dynamically typed language; hence
variables can hold values of any type. Swift's variables can only hold values of a
specific type. However, Swift has dynamic libraries that help boost the iOS app
development performance.
Which to use?
There are many reasons to choose Swift over Objective C. For starters, Swift is
easier to read and write than Objective-C. Swift also has a more concise syntax that
makes it easier to understand code at a glance.
In addition, Swift is more type-safe than Objective-C, meaning that it is less likely to
produce unexpected results due to type mismatches. A type-safe option like Swift can
make code more reliable and easier to debug.
Swift has better memory management features than Objective-C, which can help
improve performance. It uses lazy initialization, reducing memory usage since unused
variables do not initialize—making it faster, easier to read and write, and safer.
Read on to learn more about features, pros, and cons of Objective-C and Swift
languages.
VII . BASICS OF REACT NATIVE:
React Native is a popular framework for building cross-platform mobile applications
using JavaScript and React. Here are some basics to get you started:
1. Cross-Platform: React Native allows you to write code once and deploy it on both
iOS and Android platforms, saving development time and effort.
2. Components: React Native uses components to build user interfaces. These
components are similar to React components but are specifically designed for mobile
platforms.
32
3. JSX: JSX is a syntax extension for JavaScript that allows you to write HTML-like
code within your JavaScript files. It makes it easier to create UI components in React Native.
4. Native Components: React Native provides a set of built-in components that map directly to
native UI components on each platform. This allows your app to have a native look and feel.
5. Styling: You can style your React Native components using a subset of CSS. React Native
uses Flexbox for layout, which makes it easy to create responsive designs.
6. State and Props: React Native components can have state and props, just like React
components. State is used for managing component-specific data, while props are used for
passing data from parent to child components.
7. Lifecycle Methods: React Native components have lifecycle methods that allow you
to hook into various stages of a component's life, such as when it is first mounted or when it
is about to be unmounted.
8. Debugging: React Native provides tools for debugging your app, such as the React
Native Debugger, which allows you to inspect the state and props of your components.
9. Community and Ecosystem: React Native has a large and active community, which
means there are plenty of third-party libraries and tools available to help you build your app.
10. Performance: While React Native offers good performance for most applications, it
may not be suitable for highly complex or performance-critical apps. In such cases, you may
need to use native code for certain parts of your app.
These are just some of the basics of React Native. As you start building apps with React
Native, you'll learn more about its features and how to use them effectively.

Native Components
React Native provides a set of built-in components that map directly to native UI components
on iOS and Android. These components allow you to create a native look and feel for your
mobile applications. Some of the key native components in React Native include:
1. View: The View component is like a <div> in web development. It is a container that
supports layout with flexbox, style, touch handling, and accessibility controls.
2. Text: The Text component is used to display text in your app. It supports nesting,
styling, and text manipulation.
3. Image: The Image component is used to display images in your app. It supports
various image sources, resizing, and caching.

33
4. TextInput: The TextInput component is used to accept user input. It supports single-
line and multi-line inputs, as well as secure text entry for passwords.
5. ScrollView: The ScrollView component is used to create scrollable content. It
supports vertical and horizontal scrolling, as well as pull-to-refresh and paging.
6. FlatList and SectionList: These components are used to render lists of data. FlatList
is a simple list, while SectionList supports section headers.
7. TouchableOpacity: The TouchableOpacity component is used to provide touchable
feedback to users. It provides a visual effect when the user touches it.
8. ActivityIndicator: The ActivityIndicator component is used to show a loading
indicator while content is loading.
9. Modal: The Modal component is used to present content modally over the rest of the
application.
10. TouchableHighlight and TouchableWithoutFeedback: These components are used
to provide custom touch feedback to users.

In React Native, JSX, state, and props work similarly to how they work in React for web.
Here's a brief overview of each:
1. JSX (JavaScript XML): JSX is a syntax extension for JavaScript that allows you to
write HTML-like code within your JavaScript files. It provides a way to describe the UI
components of your application. JSX gets compiled into regular JavaScript function calls that
create React elements.
Example:
import React from 'react';
import { Text, View } from 'react-native';

const App = () => {


return (
<View>
<Text>Hello, React Native!</Text>
</View>
);
};

34
export default App;
State: State is a built-in feature in React that allows components to manage their own data.
State is mutable and can be updated using the setState method. State should be used for data
that can change over time and affects the component's rendering.
Example:
import React, { useState } from 'react';
import { Text, Button, View } from 'react-native';

const App = () => {


const [count, setCount] = useState(0);

const increment = () => {


setCount(count + 1); };
return (
<View>
<Text>Count: {count}</Text>
<Button title="Increment" onPress={increment} />
</View>
);
};
export default App;
Props: Props (short for properties) are used to pass data from a parent component to a child
component. Props are immutable and are passed down from the parent component. They are
used to configure a component and can include any type of data, including functions.
Example:
import React from 'react';
import { Text, View } from 'react-native';
const Greeting = (props) => {
return <Text>Hello, {props.name}!</Text>;
};
const App = () => {
return (
<View>
35
<Greeting name="Alice" />
<Greeting name="Bob" />
</View>
);
};
export default App;
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write
HTML-like code within your JavaScript files. In the context of React Native, JSX is used to
describe the UI components of your mobile application. JSX makes it easier to create and
manage complex UI structures by providing a familiar HTML-like syntax.

Here are some key points about JSX in React Native:


1. UI Component Declarations: JSX allows you to declare UI components in a way
that closely resembles HTML. For example, to create a <Text> component that displays
some text, you would write:
<Text>Hello, React Native!</Text>
Embedding Expressions: JSX allows you to embed JavaScript expressions
within curly braces {}. This allows you to dynamically generate content based on variables or
state. For example:
const name = 'Alice';
<Text>Hello, {name}!</Text>
Component Composition: JSX allows you to compose complex UIs by nesting
components within each other. This makes it easy to create reusable and modular UI
components. For example:
const Header = () => <Text>Welcome to my App!</Text>;

const App = () => {


return (
<View>
<Header />
<Text>Hello, React Native!</Text>
36
</View>
);
};
Event Handling: JSX allows you to attach event handlers to components using props. For
example, to handle a button click event:
const handlePress = () => {
console.log('Button pressed!');
};

<Button title="Press Me" onPress={handlePress} />


Styling: JSX allows you to apply styles to components using inline styles or StyleSheet
objects. Inline styles are similar to CSS but use camelCase property names. For example:
<Text style={{ color: 'red', fontSize: 20 }}>Styled Text</Text>
Overall, JSX is a powerful tool in React Native that simplifies the creation of mobile UIs by
providing a familiar and expressive syntax for defining components and their behavior.
Example:
Here's a simple example of JSX in React Native. This example creates a basic component that
displays a greeting message:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const Greeting = ({ name }) => {
return (
<View style={styles.container}>
<Text style={styles.text}>Hello, {name}!</Text>
</View>
);
};
const App = () => {
return <Greeting name="React Native" />;
};
const styles = StyleSheet.create({
container: {
flex: 1,
37
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f0f0f0',
},
text: {
fontSize: 24,
fontWeight: 'bold',
color: 'blue',
},
});
export default App;
In this example, we have two components: Greeting and App. The Greeting component
takes a name prop and displays a greeting message using that prop. The App component
renders the Greeting component with the name "React Native".
The StyleSheet.create method is used to define styles for the components. These styles are
applied using the style prop in the JSX elements. The View component is used as a container
to style the layout of the Text component.
When you run this example, you should see a screen with the text "Hello, React Native!"
displayed in the center, styled with a blue color and a bold font.

STATE example
State
 Definition: State is a built-in feature in React that allows components to manage their
own data. It is mutable and can be updated using the setState method.
 When to Use State: Use state for data that can change over time and affects the
component's rendering.

Here's a simple example of using state in a React Native component. This example creates a
counter component that allows the user to increment and decrement a counter value:
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

const Counter = () => {


38
const [count, setCount] = useState(0);

const increment = () => {


setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
return (
<View style={styles.container}>
<Text style={styles.text}>Counter: {count}</Text>
<View style={styles.buttonContainer}>
<Button title="Increment" onPress={increment} />
<Button title="Decrement" onPress={decrement} />
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f0f0f0',
},
text: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
39
width: '80%',
},
});
export default Counter;
In this example, the useState hook is used to create a state variable count initialized to 0.
The increment and decrement functions update the count state by incrementing and
decrementing its value, respectively.
The Counter component renders the current value of count along with two buttons to
increment and decrement the counter. Each button press triggers the corresponding function
to update the count state, which causes the component to re-render with the new value.

Example for probs


Props
 Definition: Props (short for properties) are used to pass data from a parent component to a
child component. They are immutable and are passed down from the parent component.
 When to Use Props: Use props to configure a component and provide it with data.
 Example:

Here's a simple example of using props in React Native. This example creates a Greeting
component that takes a name prop and displays a greeting message:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const Greeting = ({ name }) => {
return (
<View style={styles.container}>
<Text style={styles.text}>Hello, {name}!</Text>
</View>
);
};
const App = () => {
return (
<View style={styles.container}>
<Greeting name="Alice" />
40
<Greeting name="Bob" />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f0f0f0',
},
text: {
fontSize: 24,
fontWeight: 'bold',
color: 'blue',
},
});
export default App;
In this example, the Greeting component takes a name prop and uses it to display a
personalized greeting message. The App component renders two Greeting components with
different names ("Alice" and "Bob"), demonstrating how props can be used to pass data from
a parent component to a child co mponent.

41

You might also like