Thursday, 11 October 2018

Activity Lifecycle in Android

Activity Lifecycle: Activity is one of the building blocks of Android OS. In simple words Activity is a screen that user interact with. Every Activity in android has lifecycle like created, started, resumed, paused, stopped or destroyed. These different states are known as Activity Lifecycle. In other words we can say Activity is a class pre-written in Java Programming.
Below is Activity Lifecycle Table:
Short description of Activity Lifecycle example:
onCreate() – Called when the activity is first created


onStart() – Called just after it’s creation or by restart method after onStop(). Here Activity start becoming visible to user


onResume() – Called when Activity is visible to user and user can interact with it


onPause() – Called when Activity content is not visible because user resume previous activity
onStop() – Called when activity is not visible to user because some other activity takes place of it


onRestart() – Called when user comes on screen or resume the activity which was stopped



onDestroy() – Called when Activity is not in background
Below Activity Lifecycle Diagram Shows Different States:

Different Types of Activity Lifecycle States:
Activity have different states or it’s known as Activity life cycle. All life cycle methods aren’t required to override but it’s quite important to understand them. Lifecycles methods can be overridden according to requirements.


LIST OF ACTIVITY LIFECYCLE METHODS OR STATES:
Activity Created: onCreate(Bundle savedInstanceState):
onCreate() method is called when activity gets memory in the OS. To use create state we need to override onCreate(Bundle savedInstanceState) method. Now there will be question in mind what is Bundle here, so Bundle is a data repository object that can store any kind of primitive data and this object will be null until some data isn’t saved in that.


When an Activity first call or launched then onCreate(Bundle savedInstanceState) method is responsible to create the activity.
When ever orientation(i.e. from horizontal to vertical or vertical to horizontal) of activity gets changed or when an Activity gets forcefully terminated by any Operating System then savedInstanceState i.e. object of Bundle Class will save the state of an Activity.
It is best place to put initialization code.


Activity Started: onStart():
onStart() method is called just after it’s creation. In other case Activity can also be started by calling restart method i.e after activity stop. So this means onStart() gets called by Android OS when user switch between applications. For example, if a user was using Application A and then a notification comes and user clicked on notification and moved to Application B, in this case Application A will be paused. And again if a user again click on app icon of Application A then Application A which was stopped will again gets started.


Activity Resumed:.onResume():
Activity resumed is that situation when it is actually visible to user means the data displayed in the activity is visible to user. In lifecycle it always gets called after activity start and in most use case after activity paused (onPause).

Activity Paused: onPause():
Activity is called paused when it’s content is not visible to user, in most case onPause() method called by Android OS when user press Home button (Center Button on Device) to make hide.
Activity also gets paused before stop called in case user press the back navigation button. The activity will go in paused state for these reasons also if a notification or some other dialog is overlaying any part (top or bottom) of the activity (screen). Similarly, if the other screen or dialog is transparent then user can see the screen but cannot interact with it. For example, if a call or notification comes in, the user will get the opportunity to take the call or ignore it.
Activity Stopped: onStop():
Activity is called stopped when it’s not visible to user. Any activity gets stopped in case some other activity takes place of it. For example, if a user was on screen 1 and click on some button and moves to screen 2. In this case Activity displaying content for screen 1 will be stopped.
Every activity gets stopped before destroy in case of when user press back navigation button. So Activity will be in stopped state when hidden or replaced by other activities that have been launched or switched by user. In this case application will not present anything useful to the user directly as it’s going to stop.

Activity Restarted: onRestart():
Activity is called in restart state after stop state. So activity’s onRestart() function gets called when user comes on screen or resume the activity which was stopped. In other words, when Operating System starts the activity for the first time onRestart() never gets called. It gets called only in case when activity is resumes after stopped state.
Activity Destroyed: onDestroy():
Any activity is known as in destroyed state when it’s not in background. There can different cases at what time activity get destroyed.
First is if user pressed the back navigation button then activity will be destroyed after completing the lifecycle of pause and stop.


In case if user press the home button and app moves to background. User is not using it no more and it’s being shown in recent apps list. So in this case if system required resources need to use somewhere else then OS can destroy the Activity.
After the Activity is destroyed if user again click the app icon, in this case activity will be recreated and follow the same lifecycle again. Another use case is with Splash Screens if there is

call to finish() method from onCreate() of an activity then OS can directly call onDestroy() with calling onPause() and onStop().


Activity Lifecycle Example:
In the below example we have used the below JAVA and Android topics:
JAVA Topics Used: Method Overriding, static variable, package, Inheritance, method and class.
Android Topic Used: We have used Log class which is used to printout message in Logcat. One of the important use of Log is in debugging.


First we will create a new Android Project and name the activity as HomeActivity. In our case we have named our App project as Activity Lifecycle Example.
We will initialize a static String variable with the name of the underlying class using getSimpleName() method. In our case HOME_ACTIVITY_TAG is the name of the String variable which store class name HomeActivity.
Now we will create a new method which will print message in Logcat.
Now we will override all activity lifecycle method in Android and use showLog() method which we creating for printing message in Logcat.
Complete JAVA code of HomeActivity.java:

When creating an Activity we need to register this in AndroidManifest.xml file. Now question is why need to register? It's actually because manifest file has the information which Android OS read very first. When registering an activity other information can also be defined within manifest like Launcher Activity (An activity that should start when user click on app icon).
Here is declaration example in AndroidManifest.xml file

Output Of Activity Lifecycle:
When you will run the above program you will notice a blank white screen will open up in Emulator. You might be wondering where is default Hello world screen. Actually we have removed it by overriding onCreate() method. Below is the blank white screen that will pop up.
 



Now go to Logcat present inside Android Monitor: Scroll up and you will notice three methods which were called: Activity Created, Activity started and Activity resumed.
 So this clears:
first onCreate() method was called when activity was created
second onStart() method was called when activity start becoming visible to user
Finally onResume() method was called when activity is visible to user and user can interact with it
Now press the back button on the Emulator and exit the App:

Go to Logcat again and scroll down to bottom. You will see 3 more methods were called: Activity paused, Activity stopped and Activity is being destroyed.
 So this clears:
  • onPause() method was called when user resume previous activity
  • onStop() method was called when activity is not visible to user
  • Last onDestroy() method was called when Activity is not in background


Important Note: In the above example onRestart() won’t be called because there was no situation when we can resume the onStart() method again. In future example we will show you onRestart() in action as well.


Importance Of Activity Life Cycle:
Activity is the main component of Android Application, as every screen is an activity so to create any simple app first we have to start with Activities. Every lifecycle method is quite important to implement according to requirements, However onCreate(Bundle state) is always needed to implement to show or display some content on screen

Wednesday, 10 October 2018

XML in Android


XML stands for Extensible Markup Language. XML is a markup language much like HTML used to describe data.  XML tags are not predefined in XML. We must define our own Tags. Xml as itself is well readable both by human and machine. Also, it is scalable and simple to develop. In Android we use xml for designing our layouts because xml is lightweight language so it doesn’t make our layout heavy.
In this article we will go through the basic concepts of xml in Android and different XML files used for different purpose in Android. This will help you in writing a UI code to design your desired user interface.
Basics Of User Interface:
The whole concept of Android User Interface is defined using the hierarchy of View and ViewGroup objects. A ViewGroup is an invisible container that organizes child views. These child views are other widgets which are used to make the different parts of UI. One ViewGroup can have another ViewGroup as an child element as shown in the figure given below:
Here in above Diagram ViewGroup (Linear Layout) contains one ViewGroup (i.e. Relative Layout)and two View(Button and TextView). Further two more View (i.e. 2 EditText ) are nested inside Relative Layout ViewGroup. It is important to note that one layout can be nested in another layout.
The below code snippet will explain the above image in better way. Paste it in activity_main.xml:
Every Android application screen has some components like button, Text or images. These are contained inside the ViewGroup. Layouts are the best examples for ViewGroups. The different types of layout in android are Linear Layout, Relative Layout, Absolute Layout, Table Layout and Frame Layout.
Different XML Files Used in Android:
In Android there are several xml files used for several different purposes. Below we define each and every one.
1. Layout XML Files: Layout xml files are used to define the actual UI(User interface) of our application. It holds all the elements(views) or the tools that we want to use in our application. Like the TextView’s, Button’s and other UI elements.
Location in Android Studio:
You will find out this file inside the res folder and inside it there is another folder named layout where you will get all the layout files for their respective activities or fragments.
Basic Layout XML Code:
Below we show activity_main.xml file in which we have two TextView’s.
2. Manifest xml File(Mainfest.xml): This xml is used to define all the components of our application. It includes the names of our application packages, our Activities, receivers, services  and the permissions that our application needs. For Example – Suppose we need to use internet in our app then we need to define Internet permission in this file.
Location in Android Studio:
It is located inside app > manifests folder
Defining Internet Permission in AndroidManifest.xml
Below we show the AndroidManifest.xml file and define the Internet Permission in that file.
3. Strings xml File(strings.xml): This xml file is used to replace the Hard-coded strings with a single string. We define all the strings in this xml file and then access them in our app(Activity or in  Layout XML files) from this file. This file enhance the reusability of the code.
Location in Android Studio:
 Below we show strings.xml file and define a string in the file.

4. Styles xml File(styles.xml): This xml is used to define different styles and looks for the UI(User Interface) of application. We define our custom themes and styles in this file.
Location in Android Studio:
Below we show the style.xml file.
 5. Drawable xml Files: These are those xml files that are used to provide various graphics to the elements or views of application. When we need to create a custom UI we use drawable xml files. Suppose if we need to define a gradient color in the background of Button or any custom shape for a view then we create a Drawable xml file and set it in the background of View.
Below we show custom_drawable.xml file and create a gradient background color using style attribute.
6. Color xml File (colors.xml): This file is used to define the color codes that we used in our app. We simply define the color’s in this file and used them in our app from this file.
Location in Android Studio
Below we show the colors.xml file in which we define green and white color.
 7. Dimension xml File(dimens.xml): This xml file is used to define the dimensions of the View’s. Suppose we need a Button with 50dp(density pixel) height then we define the value 50dp in dimens.xml file and then use it in our app from this file.
Location in Android Studio:
Below we show the dimens.xml file in which we define 50dp  dimension for Button height.

Data Management : Repeats in R Languages

Repeats
  • Command rep is used to replicates the values in a vector.
  • Syntax rep (x) replicates the values in a vector x.
  • rep (x, times=n )  # Repeat x as a whole n times
  • rep (x, each=n )  # Repeat each cell n times
Help for the command rep

> help  ("rep")



rep { base }

      Replicate Element of Vectors and Lists

Description

rep replicates the values in x. It is generic function, and the (internal) default method is described here.
rep.int and rep-len are faster simplified versions for two common cases.
They are not generic.

Usage

rep (x, ......)
rep.int (x,  times)
rep_len (x, length.out)

The command rep

Repeat an object n-times:

> rep (3.5,  times = 10)

[1]     3.5    3.5    3.5   3.5    3.5    3.5   3.5    3.5    3.5     3.5

> rep ( 1 :4,  2)
   [1]   1   2    3    4     1    2    3    4




Repeat an object n-times

rep (x, times  = n)

Repeat each cell n-times:

rep (x, each = n)

> x <- 1 : 3
> x
 [1]   1  2  3

>  rep (x,  times = 3)
  [1]  1   2   3  1    2   3   1   2   3

> rep (x, each = 3 )
   [1]  1    1   1    2    2   2   3     3    3

Every object is repeated several times successively:

> rep (1 : 4,   each  =  2)
   [1]   1    1   2   2   3   3   4   4

> rep ( 1 : 4,  each = 2 ,  times = 3)
 [1]   1  1   2   2    3    3   4   4   1   1   2   2    3   3   4   4   1   1   2   2    3    3   4    4


Every object is repeated a different number of times:

> rep  (1 : 4,  2 :  5)
  [1]   1   1   2   2    2    3    3   3   3   4    4    4   4    4




Popular Posts

Categories

100 Python Programs for Beginner (49) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (929) Python Coding Challenge (351) Python Quiz (21) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses