Draw A Diagram For Activity Life Cycle and Explain It.: IMP Question
Draw A Diagram For Activity Life Cycle and Explain It.: IMP Question
Draw A Diagram For Activity Life Cycle and Explain It.: IMP Question
Activity Lifecycle
As the user begins to leave the activity, the system calls methods to dismantle the activity.
In some cases, this dismantlement is only partial; the activity still resides in memory (such as when the user
switches to another app), and can still come back to the foreground.
If the user returns to that activity, the activity resumes from where the user left off.
Lifecycle Methods
onCreate()
You must implement this callback, which fires when the system first creates the activity.
On activity creation, the activity enters the Created state.
In the onCreate() method, you perform basic application startup logic that should happen only once for the
entire life of the activity.
For example, your implementation of onCreate() might bind data to lists, initialize background threads, and
instantiate some class-scope variables.
This method receives the parameter savedInstanceState, which is a Bundle object containing the activity's
previously saved state.
If the activity has never existed before, the value of the Bundle object is null.
Your activity does not reside in the Created state. After the onCreate() method finishes execution, the activity
enters the Started state, and the system calls the onStart() and onResume() methods in quick succession.
onStart()
When the activity enters the Started state, the system invokes this callback.
The onStart() call makes the activity visible to the user, as the app prepares for the activity to enter the
foreground and become interactive.
For example, this method is where the app initializes the code that maintains the UI.
The onStart() method completes very quickly and, as with the Created state, the activity does not stay resident
in the Started state.
Once this callback finishes, the activity enters the Resumed state, and the system invokes the onResume()
method.
onResume()
When the activity enters the Resumed state, it comes to the foreground, and then the system invokes the
onResume() callback.
This is the state in which the app interacts with the user.
The app stays in this state until something happens to take focus away from the app.
Such an event might be, for instance, receiving a phone call, the user’s navigating to another activity, or the device
screen’s turning off.
When an interruptive event occurs, the activity enters the Paused state, and the system invokes the onPause()
callback.
If the activity returns to the Resumed state from the Paused state, the system once again calls onResume()
method.
For this reason, you should implement onResume() to initialize components that you release during
onPause().
onStop()
When your activity is no longer visible to the user, it has entered the Stopped state, and the system invokes the
onStop() callback.
This may occur, for example, when a newly launched activity covers the entire screen.
The system may also call onStop() when the activity has finished running, and is about to be terminated.
In the onStop() method, the app should release almost all resources that aren't needed while the user is not
using it.
When your activity enters the Stopped state, the Activity object is kept resident in memory: It maintains all state
and member information, but is not attached to the window manager.
When the activity resumes, the activity recalls this information.
You don’t need to re-initialize components that were created during any of the callback methods leading up to the
Resumed state.
The system also keeps track of the current state for each View object in the layout, so if the user entered text into
an EditText widget, that content is retained so you don't need to save and restore it.
onDestroy()
Called before the activity is destroyed.
This is the final call that the activity receives.
The system either invokes this callback because the activity is finishing due to someone's calling finish(), or
because the system is temporarily destroying the process containing the activity to save space.
You can distinguish between these two scenarios with the isFinishing() method.
The system may also call this method when an orientation change occurs, and then immediately call
onCreate() to recreate the process (and the components that it contains) in the new orientation.
The onDestroy() callback releases all resources that have not yet been released by earlier callbacks such as
onStop().
What is SQLite database? Write code for adding, updating and removing data
from SQLite database.
SQLite is a opensource SQL database that stores data to a text file on a device.
Android comes in with built in SQLite database implementation.
Database - Creation
In order to create a database you just need to call this method open OrCreateDatabase with your database name
and mode as a parameter. It returns an instance of SQLite database which you have to receive in your own object. Its
syntax is given below:
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);
// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(TABLE_NAME, null, values);
Update Rows
Delete Records
Returns
The number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass
1 as the whereClause.
Android Runtime
For devices running Android version 5.0 (API level 21) or higher, each app runs in its own process and with its own
instance of the Android Runtime (ART).
ART is written to run multiple virtual machines on low-memory devices by executing DEX files, a bytecode format
designed specially for Android that's optimized for minimal memory footprint.
Build toolchains, such as Jack, compile Java sources into DEX bytecode, which can run on the Android platform.
Some of the major features of ART include the following:
o Ahead-of-time (AOT) and just-in-time (JIT) compilation
Android Architecture
System Apps
Android comes with a set of core apps for email, SMS messaging, calendars, internet browsing, contacts, and more.
Apps included with the platform have no special status among the apps the user chooses to install.
So a third-party app can become the user's default web browser, SMS messenger, or even the default keyboard.
The system apps function both as apps for users and to provide key capabilities that developers can access from
their own app.
E.g., if your app would like to deliver an SMS message, you don't need to build that functionality yourself - you can
instead invoke whichever SMS app is already installed to deliver a message to the recipient you specify.
The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file.
It is a platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.
Dalvik virtual machine uses register based architecture. With this architecture, Dalvik Virtual Machine has few
advantages over JAVA virtual machine such as:
● Dalvik uses its own 16 bit instruction set than java 8 bit stack instructions, which reduce the dalvik instruction
count and raised its interpreter speed.
● Dalvik use less space, which means an uncompressed .dex file is smaller in size(few bytes) than compressed java
archive file(.jar file).
List out different types of layouts in android. Explain any two layouts.
A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can
declare a layout in two ways:
o Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View
classes and subclasses, such as those for widgets and layouts.
o Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and
manipulate their properties) programmatically.
Linear Layout
LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. You can specify
the layout direction with the android:orientation attribute.
All children of a Linear Layout are stacked one after the other, so a vertical list will only have one child per row, no
matter how wide they are, and a horizontal list will only be one row high (the height of the tallest child, plus
padding).
A Linear Layout respects margins between children and the gravity (right, center, or left alignment) of each child.
Relative Layout
Relative Layout is a view group that displays child views in relative positions.
The position of each view can be specified as relative to sibling elements (such as to the left-of or below another
view) or in positions relative to the parent Relative Layout area (such as aligned to the bottom, left or center).
Relative Layout lets child views specify their position relative to the parent view or to each other (specified by ID).
So you can align two elements by right border, or make one below another, centered in the screen, centered left,
and so on.
By default, all child views are drawn at the top-left of the layout, so you must define the position of each view
using the various layout properties available from RelativeLayout.LayoutParams.
3) android:layout_below
Positions the top edge of this view below the view specified with a resource ID.
4) android:layout_toRightOf
Positions the left edge of this view to the right of the view specified with a resource ID.
Frame Layout
Frame Layout is designed to block out an area on the screen to display a single item.
Generally, Frame Layout should be used to hold a single child view, because it can be difficult to organize child
views in a way that's scalable to different screen sizes without the children overlapping each other.
You can, however, add multiple children to a Frame Layout and control their position within the Frame Layout by
assigning gravity to each child, using the android:layout_gravity attribute.
Child views are drawn in a stack, with the most recently added child on top.
The size of the Frame Layout is the size of its largest child (plus padding), visible or not (if the Frame Layout's parent
permits). Sample code showing use of FrameLayout has been shown below:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:foregroundGravity="fill"
android:foreground="#0f0"><!--foreground color for a FrameLayout-->
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>
<!-- Imageview will not be shown because of foreground color which is drawn over
it-->
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
<!--Textview will not be shown because of foreground color is drawn over it-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="AndroidSample"/>
</LinearLayout>
</FrameLayout>
Table Layout
<TableRow>
<TextView
android:text="@string/table_layout_4_save"
android:padding="3dip" />
<TextView
android:text="@string/table_layout_4_save_shortcut"
android:gravity="right"
android:padding="3dip" />
</TableRow>
</TableLayout>
<manifest>
<uses-permission />
<permission />
<uses-sdk />
<uses-configuration />
<uses-feature />
<supports-screens />
<application>
<activity>
<intent-filter>
<action />
<category />
<data />
</intent-filter>
<meta-data />
</activity>
<service>
<intent-filter> . . . </intent-filter>
<meta-data/>
</service>
<receiver>
<intent-filter> . . . </intent-filter>
<meta-data />
</receiver>
<provider>
<grant-uri-permission />
<meta-data />
<path-permission />
</provider>
</application>
</manifest>
ART Features
Here are some of the major features implemented by ART.
Ahead-of-time (AOT) compilation - ART introduces ahead-of-time (AOT) compilation, which can improve app
performance. ART also has tighter install-time verification than Dalvik.
Improved garbage collection - ART improves garbage collection in several ways:
o One GC pause instead of two
o Parallelized processing during the remaining GC pause
o Lower total GC time
o Improved garbage collection ergonomics
o Compacting GC to reduce background memory usage and fragmentation
Development and debugging improvements
o Support for sampling profiler
o Support for more debugging features
o Improved diagnostic detail in exceptions and crash reports
Hardware profile
The hardware profile defines the characteristics of a device as shipped from the factory. The AVD Manager comes
preloaded with certain hardware profiles, such as Nexus phone devices, and you can define and import hardware
profiles as needed. You can override some of the settings in your AVD, if needed.
System image
The AVD Manager helps you choose a system image for your AVD by providing recommendations. It also lets you
download system images, some with add-on libraries, like Google APIs.
Native App
Native App has been developed for use on a particular platform or device.
A native mobile app is a Smartphone application that is coded in a specific programming language, Java for Android
operating systems.
Native mobile apps provide fast performance and a high degree of reliability.
They also have access to a phone’s various devices, such as its camera and address book.
In addition, users can use some apps without an Internet connection.
However, this type of app is expensive to develop because it is tied to one type of operating system, forcing the
company that creates the app to make duplicate versions that work on other platforms.
A Native app can only be “Native” to one type of mobile operating system.
Most video games are native mobile apps.
Web App
Web App stored on a remote server and delivered over the internet through a browser.
Web apps are not real apps; they are really websites that, in many ways, look and feel like native applications.
They are run by a browser and typically written in HTML5.
Users first access them as they would access any web page: they navigate to a special URL and then have the
option of “installing” them on their home screen by creating a bookmark to that page.
In contrast, a mobile web app is software that uses technologies such as JavaScript or HTML5 to provide
interaction, navigation, or customization capabilities.
These programs run within a mobile device’s web browser.
This means that they’re delivered wholly on the fly, as needed, via the internet; they are not separate programs
that get stored on the user’s mobile device.
Web apps became really popular when HTML5 came around and people realized that they can obtain native-like–
functionality in the browser.
Hybrid App
This type of application has cross-platform compatibility but can still access a phone’s hardware.
It is developed using platforms such as Sencha, PhoneGap and Mosync.
Hybrid Apps are like native apps, run on the device, and are written with web technologies (HTML5, CSS and
JavaScript).
Hybrid apps run inside a native container, and leverage the device’s browser engine to render the HTML and
process the JavaScript locally.
A web-to-native abstraction layer enables access to device capabilities that are not accessible in Mobile Web
applications, such as the accelerometer, camera and local storage.
Hybrid apps are also popular because they allow cross-platform development: that is, the same HTML code
components can be reused on different mobile operating systems, reducing significantly the development costs.
3) Click Next.
4) In the Target Android Devices screen, keep the default values and click Next.
The Minimum Required SDK is the earliest version of Android that your app supports, which is indicated by the
API level. To support as many devices as possible, you should set this to the lowest version available that allows
your app to provide its core feature set.
5) In the Add an Activity to Mobile screen, select Empty Activity and click Next.
6) In the Customize the Activity screen, keep the default values and click Finish.
After some processing, Android Studio opens and displays a "Hello World" app with default files. Following files will
be created after successful processing
app > java > com.example.myfirstapp > MainActivity.java
app > res > layout > activity_main.xml
app > manifests > AndroidManifest.xml
Gradle Scripts > build.gradle
XmlPullParser, which is an efficient and maintainable way to parse XML on Android. Historically Android has had
two implementations of this interface:
JSON Parsing
JSON stands for JavaScript Object Notation.
It is an independent data exchange format and is the best alternative for XML.
Android provides four different classes to manipulate JSON data.
These classes are JSONArray, JSONObject, JSONStringer and JSONTokenizer.
The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON
given below we interested in getting temperature only.
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
JSON - Elements
An JSON file consist of many components. Here is the table defining the components of an JSON file and their
description −
Array([) - In a JSON file , square bracket ([) represents a JSON array
Objects({) - In a JSON file, curly bracket ({) represents a JSON object
Key - A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
Value - Each key has a value that could be string, integer or double etc.,
JSON - Parsing
For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it.
Its syntax is −
String in:
JSONObject reader = new JSONObject(in);
The last step is to parse the JSON. A JSON file consist of different object with different key/value pair e.t.c. So
JSONObject has a separate function for parsing each of the component of JSON file. Its syntax is given below −
return null;
}
XmlPullParser, which is an efficient and maintainable way to parse XML on Android. Historically Android has had two
implementations of this interface:
XML Parsing
XML stands for Extensible Mark-up Language.
XML is a very popular format and commonly used for sharing data on the internet.
This chapter explains how to parse the XML file and extract necessary information from it.
Android provides three types of XML parsers which are DOM,SAX and XMLPullParser.
Among all of them android recommend XMLPullParser because it is efficient and easy to use.
So we are going to use XMLPullParser for parsing XML.
The first step is to identify the fields in the XML data in which you are interested in.
E.g., in the XML given below we interested in getting temperature only.
<?xml version="1.0"?>
<current>
XML - Elements
An xml file consist of many components. Here is the table defining the components of an XML file and their description.
Prolog - An XML file starts with a prolog. The first line that contains the information about a file is prolog
Events - An XML file has many events. Event could be like this. Document starts, Document ends, Tag start, Tag
end and Text
Text - Apart from tags and events, and xml file also contains simple text. Such as GB is a text in the country tag.
Attributes - Attributes are the additional properties of a tag such as value.
We will create XMLPullParser object , but in order to create that we will first create
XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser.
Its syntax is given below −
The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a
Stream. In our case it is a stream.
Its syntax is given below:
myparser.setInput(stream, null);
The last step is to parse the XML. An XML file consist of events, Name, Text, AttributesValue etc., So XMLPullParser
has a separate function for parsing each of the component of XML file. Its syntax is given below −
case XmlPullParser.END_TAG:
if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
break;
}
event = myParser.next();
}
The method getEventType returns the type of event that happens. e.g: Document start, tag start. The method
getName returns the name of the tag and since we are only interested in temperature, so we just check in conditional
statement that if we got a temperature tag, we call the method getAttributeValue to return us the value of
temperature tag.
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
try {
InputStream is = getAssets().open("file.xml");
Element element=doc.getDocumentElement();
element.normalize();
The Model: The model represents data or data container. We can see it as a database of pictures on our device. Let's
say, any user wants to hear an audio file, he clicks play button and it triggers an event in our app, now the app will get
data from data store or database and as per input and creates data to be sent back to the user. We can refer this data
as Model.
The View: The View is the portion of the application responsible for rendering the display, sending audio to speakers,
generating tactile feedback, and so on.
Now as per above example, the view in a hypothetical audio player might contain a component that shows the album
cover for the currently playing tune. User will always interact with this layer. User action on this layer will trigger events
that will go to the application functions.
The Controller: The Controller is the portion of an application that responds to external actions: a keystroke, a screen
tap, an incoming call, etc. It is implemented as an event queue. On User's action, the control is passed over to controller
and this will take care of all logic that needs to be done and prepare Model that need to be sent to view layer.
Grid View
Grid View is a ViewGroup that displays items in a two-dimensional, scrollable grid.
The grid items are automatically inserted to the layout using a ListAdapter.
For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an
Adapter.
Open HelloGridView.java and insert the following code for the onCreate() method:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(HelloGridView.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
After the main.xml layout is set for the content view, the GridView is captured from the layout with findViewById(int).
The setAdapter() method then sets a custom adapter (ImageAdapter) as the source for all items to be displayed in the
grid.
To do something when an item in the grid is clicked, the setOnItemClickListener() method is passed a new
AdapterView.OnItemClickListener. This anonymous instance defines the onItemClick() callback method to show a
Toast that displays the index position (zero-based) of the selected item (in a real world scenario, the position could be
used to get the full sized image for some other task).
public ImageAdapter(Context c) {
mContext = c;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
The first method necessary is getView(). This method creates a new View for each image added to the
ImageAdapter.
When this is called, a View is passed in, which is normally a recycled object, so there's a check to see if the object
is null.
If it is null, an ImageView is instantiated and configured with desired properties for the image presentation:
o setLayoutParams(ViewGroup.LayoutParams) sets the height and width for the View - this ensures
that, no matter the size of the drawable, each image is resized and cropped to fit in these dimensions, as
appropriate.
o setScaleType(ImageView.ScaleType) declares that images should be cropped toward the center
(if necessary).
o setPadding(int, int, int, int) defines the padding for all sides.
If the View passed to getView() is not null, then the local ImageView is initialized with the recycled View object.
At the end of the getView() method, the position integer passed into the method is used to select an image
from the mThumbIds array, which is set as the image resource for the ImageView.
All that's left is to define the mThumbIds array of drawable resources.
Run the application.
The android:name attribute in the <fragment> specifies the Fragment class to instantiate in the layout.
When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the
onCreateView() method for each one, to retrieve each fragment's layout.
The system inserts the View returned by the fragment directly in place of the <fragment> element.
You can then add a fragment using the add() method, specifying the fragment to add and the view in which to
insert it. For example:
The first argument passed to add() is the ViewGroup in which the fragment should be placed, specified by resource
ID, and the second parameter is the fragment to add.
Once you've made your changes with FragmentTransaction, you must call commit() for the changes to take effect.
What is Listview. Write a java class to add any 10 items within Listview.
ListView is a view group that displays a list of scrollable items.
The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an
array or database query and converts each item result into a view that's placed into the list.
<ListView android:layout_width="fill_parent"
The resource ID of the ListView is mainListView, which we will use to get a reference to the ListView in our
Activity class.
Activity
Our main activity (SimpleListViewActivity) creates an ArrayAdapter, which holds the objects to be
displayed in the ListView.
The ArrayAdapter constructor is passed the resource ID of the TextView layout file
(R.layout.simplerow).
The ArrayAdapter will use it to instantiate a TextView for each row.
package com.example.android;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
HTTP Request
The client request from the browser will look like:
GET http://weatherinfo.org/getweather/mumbai HTTP/1.1
HTTP Response
The server response will look like
HTTP/1.1 200 Ok
Date: Mon, 14 Apr 2014 10:20:58 GMT
Content-Type: text/xml
Content-length: 139
Line 1 is the initial line which has the HTTP response code – 200 OK, lines 2 through 4 are the HTTP headers, line 5
is the mandatory blank line separating header and body, and lines 6 through 10 constitute the “HTTP Body (or
content)” – this part is the data that the response carries and can be in any format, not necessarily XML.