Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 73

Android Programming

Lecture 11, 12
Contents
• Intents in Android
• Toast in android
• Introduction to Gradle
• Context
• Bundle
• Memory Leaks in Android
Intent in Android
• Android uses Intent for communicating between the components of
an Application and also from one application to another application.
• Intent are the objects which is used in android for passing the
information among Activities in an Application and from one app to
another also. Intent are used for communicating between the
Application components and it also provides the connectivity
between two apps.
Example
• For example: Intent facilitate you to redirect your activity to another
activity on occurrence of any event. By calling, startActivity() you can
perform this task.

• In the above example, foreground activity is getting redirected to


another activity i.e. SecondActivity.java. getApplicationContext()
returns the context for your foreground activity.
Functions of Intent
• Some of the general functions of intent are:
• Start service
• Launch Activity
• Display web page
• Display contact list
• Message broadcasting
Functions of Intent

Methods Description

This is to launch a new activity or get an existing activity


Context.startActivity() to be action.

This is to start a new service or deliver instructions for an


Context.startService() existing service.

Context.sendBroadcast() This is to deliver the message to broadcast receivers.


Types of Intents:

Intent Types
Implicit Intent

Explicit Intent
Implicit Intent:
• In Implicit Intents we do need to specify the name of the component.
We just specify the Action which has to be performed and further this
action is handled by the component of another application.
• The basic example of implicit Intent is to open any web page
• Let’s take an example to understand Implicit Intents more clearly. We
have to open a website using intent in your application. See the code
snippet given below

• Unlike Explicit Intent you do not use any class name to pass through
Intent(). In this example we has just specified an action. Now when
we will run this code then Android will automatically start your web
browser and it will open home page of mentioned website.
Explicit Intent:
• Explicit Intents are used to connect the application internally.
• In Explicit we use the name of component which will be affected by
Intent. For Example: If we know class name then we can navigate the
app from One Activity to another activity using Intent. In the similar
way we can start a service to download a file in background process.
Explicit Intent:
• Explicit Intent work internally within an application to perform
navigation and data transfer. The below given code snippet will help
you understand the concept of Explicit Intents

• Here SecondActivity is the JAVA class name where the activity will
now be navigated.
Task: Intents in Android practice
• Create a project in Android Studio and named it “Intents”. Make an
activity, which would consists Java file; MainActivity.java and an xml
file for User interface which would be activity_main.xml
Implicit Intent
• Using implicit Intent, components can’t be specified. An action to be
performed is declared by implicit intent. Then android operating
system will filter out components that will respond to the action. For
Example,
• In the above example, no component is specified, instead, an action is
performed i.e. a webpage is going to be opened. As you type the
name of your desired webpage and click on the ‘CLICK’ button. Your
webpage is opened.
Step by Step Implementation
Creating an Android App to Open a Webpage Using Implicit Intent
Step 1: Create a New Project in Android Studio
• To create a new project and select empty activity in Android Studio
Step 2: Working with the XML Files
• Next, go to the activity_main.xml file, which represents the UI of the
project. Below is the code for the activity_main.xml file. Comments
are added inside the code to understand the code in more detail.
Code
• Refer to this URL to get code for both files xml and java

PRACTICE CODES
Java Code Explanation of important Terms
• onCreate(Bundle savedInstanceState): This is a lifecycle method in
Android activities. It is called when the activity is first created. Here,
we override this method to perform initialization tasks, such as setting
up the layout of the activity and initializing UI components.
• super.onCreate(savedInstanceState): This line calls the onCreate()
method of the superclass (AppCompatActivity). It's essential to call
this method as the first statement in the overridden onCreate()
method to ensure that the activity is properly initialized.
Java Code Explanation of important Terms
• setContentView(int layoutResID): This method sets the layout
resource file for the activity. It defines the user interface of the
activity using an XML layout file. In the provided code,
setContentView(R.layout.activity_main) sets the layout of the activity
to the XML layout file named activity_main.xml.
• findViewById(int id): This method is used to find a view (such as a
button or text field) that was defined in the XML layout file by its ID. It
returns the view object that corresponds to the specified ID. In the
code, findViewById(R.id.btn) finds the button with the ID btn.
Java Code Explanation of important Terms
• setOnClickListener(View.OnClickListener listener): This method sets an
OnClickListener for the view, which listens for clicks on the view. When
the view is clicked, the onClick() method of the OnClickListener is called.
In the code, we set an OnClickListener for the button to handle clicks.
• Intent: An Intent is a messaging object that is used to request an action
from another app component. It can be used to start an activity, deliver a
broadcast, or start a service. In the code, we use an Intent with the action
Intent.ACTION_VIEW to open a web browser to view the specified URL.
• Uri: A Uri (Uniform Resource Identifier) identifies a resource on the
internet or within an app. In the code, we use Uri.parse(url) to parse the
URL string and create a Uri object that represents the URL.
Find View by id

• findViewById(int id) is a method used in Android development to find a


View object (such as a Button, TextView, or any other UI component)
from the current layout hierarchy by its unique identifier.
Here's how it works:

• Parameter: It takes an integer parameter id, which corresponds to the


unique identifier assigned to the View in the XML layout file.
• Return Value: It returns the View object if found, or null if no view with
the specified ID is found.
Example
• XML • In the corresponding Java code
(such as in an Activity class), you
can find this Button using its ID
like this:
Onclick listener
• An OnClickListener is an interface in Android used to handle the click events of a view. It is a way to
register a callback function that will be invoked when the view is clicked.

• Here's how it works:

• Interface: OnClickListener is an interface provided by the Android framework, located in the


android.view.View.OnClickListener package.

• Method: The interface contains a single method onClick(View v), which is called when the view is
clicked.

• Implementation: To use an OnClickListener, you typically create an instance of it and override the
onClick() method with the desired behavior. This is usually done inline with an anonymous inner class
or using a lambda expression.
• In this example:

• We find the Button with the ID my_button using findViewById().


• We then call setOnClickListener() on the Button and pass in an instance of
View.OnClickListener.
• Inside the onClick() method, we define the actions to be performed when the
Button is clicked. In this case, we show a Toast message saying "Button
Clicked!".
• Using OnClickListener, you can define custom behavior for different views
when they are clicked, such as navigating to another activity, performing
calculations, updating UI elements, etc.
Explicit Intent Implementation
• Explicit Intent
• Using explicit intent any
other component can be
specified. In other words,
the targeted component is
specified by explicit
intent. So only the
specified target
component will be
invoked. For Example:
• In the above example, There are two activities (FirstActivity, and
SecondActivity). When you click on the ‘GO TO OTHER ACTIVITY’
button in the first activity, then you move to the second activity.
When you click on the ‘GO TO HOME ACTIVITY’ button in the second
activity, then you move to the first activity. This is getting done
through Explicit Intent.
Step by Step Implementation
• How to create an Android App to move to the next activity using
Explicit Intent(with Example)
• Step 1: Create a New Project in Android Studio
• Step 2: Working with the activity_main.xml File
• Next, go to the activity_main.xml file, which represents the UI of the
project. Code for the activity_main.xml file and java file is available in
google doc. Comments are added inside the code to understand the
code in more detail.
Step by Step Implementation
• Step 3: Working with the MainActivity File
• Now, we will create the Backend of the App. For this, Open the
MainActivity file and instantiate the component (Button, TextView)
created in the XML file using the findViewById() method. This method
binds the created object to the UI Components with the help of the
assigned ID.
Step by Step Implementation
• Step 4: Working with the
activity_main2.xml File
• Inside
resources>layoutfolder>newfle
>activity_main2.xml
• In tis case you need two java
files and two xml files
• Code: https://
docs.google.com/document/d/
e/2PACX-1vRbRcSKM7TFsohspK
aRt3eWnR905TgqaiOPowrDp4k
ZXX5npHbn4a4ioWJTHmF-23G
m241J9zti8lV7/pub
What is Toast in Android?
• A Toast is a feedback message. It takes a very little space for
displaying while the overall activity is interactive and visible to the
user. It disappears after a few seconds. It disappears automatically. If
the user wants a permanently visible message, a Notification can be
used. Another type of Toast is custom Toast, in which images can be
used instead of a simple message.
Constants of Toast class

Constants Description

public static final int LENGTH_LONG displays for a long time

public static final int LENGTH_SHORT displays for a short time


Methods of Toast Class

Methods Description

public static Toast makeText(Context makes the toast message consist of text
context, CharSequence text, int duration) and time duration

public void show() displays a toast message

public void setMargin (float changes the horizontal and vertical


horizontalMargin, float verticalMargin) differences
How to Create an Android App to Show a
Toast Message?
• In this example “This a simple toast
message” is a Toast
message which is displayed by
clicking on the ‘CLICK’ button.
Every time when you click your
toast message appears.
Task : 1
• Create an Android app which is capable of display “good morning” to
the user
• In MainActivity.Java add the • In XML File just drag and
following code drop a text view and set
id to text , here is sample
code

• This line of code is typically


found in Android app
development and is used to
display a short-lived notification
called a "toast" to the user.
Here's what each part does:
Toast in Android
• This line of code is typically found in Android app development and is used to
display a short-lived notification called a "toast" to the user. Here's what each
part does:
• Toast: Toast is a class in Android that allows you to display small messages to
the user for a short duration.

• makeText(): makeText() is a static method of the Toast class used to create a


new Toast object.

• this: In the context of an activity or fragment, this refers to the current


instance of the class.
Toast in Android
• "Hi, Good Morning": This is the message you want to display in the
toast. In this case, it's "Hi, Good Morning".
• Toast.LENGTH_SHORT: This specifies the duration for which the toast
message will be displayed. Toast.LENGTH_SHORT is a constant
representing a short duration, typically around 2 seconds.
• show(): show() is a method of the Toast class that makes the toast
message visible to the user.
• So, when this line of code is executed, it creates a toast with the
message "Hi, Good Morning", displays it for a short duration, and
then hides it automatically.
Gradle in Android
• Gradle is an excellent open-source construction tool that is capable of
the development of any kind of software.
• It is an automation tool that is based on Apache Ant and Apache
Maven. This tool is capable of developing applications with industry
standards and supports a variety of languages including Groovy, C++,
Java, Scala, and C.
• Gradle also is capable of controlling the development tasks with
compilation and packaging to testing, deployment, and publishing
Working of Gradle
• The Gradle project when constructed it consists of one or more than
one project. These projects consist of tasks. Let us understand the
basics of both terms.
• 1. Gradle Projects: The projects created by Gradle are a web
application or a JAR file. These projects are a combination of one or
more tasks. These projects are capable to be deployed on the various
development life cycles. A Gradle project can be described as building
a wall with bricks N in number which can be termed as tasks.
Working of Gradle
2. Gradle Tasks: The tasks are the functions which are responsible for a specific
role. These tasks are responsible for the creating of classes, Javadoc, or publish
archives into the repository which makes the whole development of the Gradle
project. These tasks help Gradle decide what input is to be processed for a
specific output. Again tasks can be categorized into two different ways:
• Default Task: These are the predefined tasks that are provided to users by the
Gradle. These are provided to users prior which executes when the users do not
declare any task on his own. For example, init and wrapper the default tasks
provided to users into a Gradle project
• Custom Task: Custom tasks are the tasks that are developed by the developer
to perform a user-defined task. These are developed to run a specific role in a
project. Let’s take a look at how to develop a Custom Task below.
• Example: Printing Welcome to Mobile app development! with a task
in Gradle.
build.gradle : task hello
{
doLast
{
println 'Welcome to Mobile App Development!'
}
}
Features of Gradle:
• IDE support: Gradle supports a variety of IDE (Integrated
Development Environment). This is a built tool that supports multiple
development environments.
• Familiar with Java: Gradle projects need Java environment JVM to run.
Features of Gradle are also similar to Java. It also supports the API’s
which are supported by Java and it is the biggest advantage for
developers and it makes it versatile.
• Builds: Gradle provides build’s for necessary tasks only as if it only
compiles the changes which are done previous the last build. It
reduces the load time.
Features of Gradle:
• Free and Open Source: Gradle is an open-source built tool that makes it user friendly and it is
licensed under ASL (Apache License).
• Multiple Design Build Support: Gradle built tools implements multiple builds supports as while
designing a root project it may contain several sub-projects and these projects can have multiple
more projects. With the help of Gradle, one can easily build the layout.
• Dependency Management: Gradle provides a powerful dependency management system that makes
it easy to manage project dependencies and ensures that all dependencies are resolved and
downloaded automatically.
• Scripting: Gradle uses a Groovy-based domain-specific language (DSL) for scripting build
configurations, which provides a flexible and intuitive way to define build tasks and workflows.
• Incremental Builds: Gradle supports incremental builds, which means that it only builds the parts of
the project that have changed since the last build. This helps to reduce build times and improve
productivity.
• Plugins: Gradle provides a rich set of plugins that can be used to extend its functionality and add
support for various languages and technologies, including Java, C++, Android, and more.
Features of Gradle:
• Extensibility: Gradle is highly extensible, which means that it can be
easily customized and adapted to meet the specific needs of a project.
It also provides APIs for integrating with other tools and systems.
• Build Caching: Gradle provides a build caching feature that allows it to
cache the results of previous builds and reuse them when building the
project again. This helps to further reduce build times and improve
performance.
• Test Automation: Gradle supports test automation through its
integration with testing frameworks like JUnit, TestNG, and Spock. It
also provides support for code coverage analysis and reporting.
What is Context in Android?
• The Context tells us about the surrounding information.
• It is very important to understand the environment which we want to
understand.
• when we talk about Android Programming Context can be understood
as something which gives us the Context of the current state of our
application
Uses of Context in Android?
• It allows us to access resources.
• It allows us to interact with other Android components by sending
messages.
• It gives you information about your app environment.
How Does this Work?
• 1. It is the Context of the current/active state of the application.
• Usually, the app got multiple screens like display/inquiry/add/delete
screens(A general requirement of a basic app). So when the user is
searching for something, the Context is an inquiry screen in this case.
• 2. It is used to get information about the activity and application.
• The inquiry screen’s Context specifies that the user is in inquiry
activity, and he/she can submit queries related to the app
How Does this Work?
• 3. It is used to get access to resources, databases, shared preferences,
etc.
• Via Rest services, API calls can be consumed in android apps. Rest
Services usually hold database data and provide the output in JSON
format to the android app. The Context for the respective screen helps
to get hold of database data and the shared data across screens
• 4. Both the Activity and Application classes extend the Context class.
• In android, Context is the main important concept and the wrong usage
of it leads to memory leakage. Activity refers to an individual screen and
Application refers to the whole app and both extend the Context class.
Types of Context
• There are mainly two types of Context that are available in Android.
• Application Context and
• Activity Context
• The Overall view of the App hierarchy looks like the following:
Types of Context
1. Application Context
• This Context is tied to the Lifecycle of an Application. Mainly it is an instance
that is a singleton and can be accessed via getApplicationContext().
Some use cases of Application Context are:
• If it is necessary to create a singleton object
• During the necessity of a library in an activity

• A singleton object is a design pattern used in software engineering to ensure


that a class has only one instance and provides a global point of access to
that instance
• getApplicationContext():
• It is used to return the Context which is linked to the Application
which holds all activities running inside it. When we call a method or
a constructor, we often have to pass a Context and often we
use “this” to pass the activity Context or “getApplicationContext” to
pass the application Context.
• This method is generally used for the application level and can be
used to refer to all the activities. For example, if we want to access a
variable throughout the android app, one has to use it
via getApplicationContext()
• So, whenever the variable scope is required throughout the application,
we can get it by means of getApplicationContext(). Following is a list of
functionalities of Application Context.
• List of functionalities of Application Context:
• Load Resource Values
• Start a Service
• Bind to a Service
• Send a Broadcast
• Register BroadcastReceiver
2. Activity Context
• It is the activity Context meaning each and every screen got an activity.
For example, EnquiryActivity refers to EnquiryActivity only and
AddActivity refers to AddActivity only. It is tied to the life cycle of
activity. It is used for the current Context. The method of invoking the
Activity Context is getContext().
Some use cases of Activity Context are:
• The user is creating an object whose lifecycle is attached to an activity.
• Whenever inside an activity for UI related kind of operations like toast,
dialogue, etc.,
• getContext():
• It returns the Context which is linked to the Activity from which it is
called. This is useful when we want to call the Context from only the
current running activity.
List of Functionalities of Activity Context:
• Load Resource Values
• Start an Activity
• Show a Dialog
• Start a Service
• Bind to a Service
• Send a Broadcast
• Register BroadcastReceiver
Difference B/W Both Contexts
• From the functionalities of both Application and Activity, we can see
that the difference is that the Application Context is not related to UI.
It should be used only to start a service or load resource values etc.
Apart from getApplicationContext()
Bundle in Android with Example

• It is known that Intents are used in Android to pass to the data from
one activity to another. But there is one another way, that can be
used to pass the data from one activity to another in a better way and
less code space ie by using Bundles in Android.
Bundle in Android with Example

• Android Bundles are generally used for passing data from one activity
to another. Basically here concept of key-value pair is used where the
data that one wants to pass is the value of the map, which can be
later retrieved by using the key.
• Bundles are used with intent and values are sent and retrieved in the
same fashion, as it is done in the case of Intent. It depends on the
user what type of values the user wants to pass, but A Bundle can
hold various types of data, including primitive types, arrays, and
serializable objects.
• Creating a Bundle:

• Putting data into a Bundle:

• Replace XXX with the appropriate data type like String, Int, Parcelable,
etc. For example:
• Getting data from a Bundle:

• Again, replace XXX with the appropriate data type. For example:
Memory Leaks in Android
• Memory leaks in Android occur when objects that are no longer
needed are not properly released from memory. This can lead to an
increase in memory usage over time, potentially causing the app to
slow down, become unresponsive, or even crash. Memory leaks are a
common issue in Android development, and they often happen due
to the following reasons:
Causes of Memory Leaks and Their
Solutions
• Memory leaks are a common issue in Android development, and they
often happen due to the following reasons:
• 1. Using Static Views: One should not use static views while
developing the application, as static views are never destroyed.
Memory Leaks Reasons
2. Using Static Context
• One should never use the Context as static, because that context will
be available through the life of the application, and will not be
restricted to the particular activity.
• 3. Using Code Abstraction Frequently
• Developers often take the advantage of the abstraction property
because it provides the code maintenance and flexibility in code, but
using abstraction might cost a bit to the developer, as while using
abstraction one needs to write more code, more code means more
time to execute the space and more RAM. So whenever one can avoid
the abstraction in the code, it is code as it can lead to fewer memory
leaks.
• 4. Unregistered Listeners
• When the developer uses any kind of listener in his application code,
then the developer should not forget to unregister the listener.
• 5. Unregistered Receivers
• Many times the developer needs to register the local broadcast
receiver in an activity. However, if the developer does not unregisters
the broadcast receiver there is a strong chance that our app can lead
to the memory leak problem as the receiver will hold a strong
reference to the activity. So even if the activity is of no use, it will
prevent the garbage collector to collect the activity for garbage
collection, which will ultimately cause the memory leak.
• 6. Inner class Reference
• An inner class is often used by the android developers within their
code. However, the nonstatic class will hold the implicit reference of
the parent class which can cause the memory leak problem. So there
can be two solutions that can be proposed to solve this problem:
• One can make the inner class static
• If one wants to pass the reference of the non-static inner class, then it
can be passed using weak reference.
• Use Memory Profiling Tools: Android Studio provides memory
profiling tools such as the Memory Profiler and Allocation Tracker,
which can help you identify memory leaks by analyzing the memory
usage of your app.

You might also like