Android Programming CSE - IT Engineering Lecture Notes
Android Programming CSE - IT Engineering Lecture Notes
▼▼
Disclaimer
Please note none of the content or study material in this document or content in this file is prepared or
owned by AceTechie.com. This content is shared by our student partners and we do not hold any
copyright on this content.
Please let us know if the content in this file infringes any of your copyright by writing to us at:
[email protected] and we will take appropriate action.
IMP Question
m
o
.c
ie
h
c
e
T
e
c
A
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.
m
This method receives the parameter savedInstanceState, which is a Bundle object containing the activity's
previously saved state.
o
.c
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
ie
enters the Started state, and the system calls the onStart() and onResume() methods in quick succession.
onStart()
h
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
c
foreground and become interactive.
For example, this method is where the app initializes the code that maintains the UI.
e
The onStart() method completes very quickly and, as with the Created state, the activity does not stay resident
in the Started state.
T
Once this callback finishes, the activity enters the Resumed state, and the system invokes the onResume()
method.
e
c
onResume()
When the activity enters the Resumed state, it comes to the foreground, and then the system invokes the
onResume() callback.
A
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().
m
If the activity returns from the Paused state to the Resumed state, the system keeps the Activity instance resident
in memory, recalling that instance when it the system invokes onResume().
onStop()
o
.c
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.
ie
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.
h
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.
c
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.
e
The system also keeps track of the current state for each View object in the layout, so if the user entered text into
T
an EditText widget, that content is retained so you don't need to save and restore it.
onDestroy()
e
Called before the activity is destroyed.
c
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
A
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:
.c
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
ie
values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);
// Insert the new row, returning the primary key value of the new row
h
long newRowId = db.insert(TABLE_NAME, null, values);
e
not put any values). If you specify the name of a column, the framework inserts a row and sets the value of that
column to null. If you specify null, like in this code sample, the framework does not insert a row when there are
T
no values.
Update Rows
e
c
public void updateRecord(ContactModel contact) {
database = this.getReadableDatabase();
A
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());
contentValues.put(COLUMN_LAST_NAME, contact.getLastName());
database.update(TABLE_NAME, contentValues, COLUMN_ID + " = ?", new
String[]{contact.getID()});
database.close();
}
Delete Records
m
database.delete() is convenient method for deleting rows in the database
o
Returns
The number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass
.c
1 as the whereClause.
ie
Android is an open source, Linux-based software stack created for a wide array of devices and form factors.
The major components of the Android platform are:
e
Using a Linux kernel allows Android to take advantage of key security features and allows device manufacturers
T
to develop hardware drivers for a well-known kernel.
e
Hardware Abstraction Layer (HAL)
The hardware abstraction layer (HAL) provides standard interfaces that expose device hardware capabilities to the
c
higher-level Java API framework.
The HAL consists of multiple library modules, each of which implements an interface for a specific type of hardware
A
component, such as the camera or bluetooth module.
When a framework API makes a call to access device hardware, the Android system loads the library module for
that hardware component.
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
m
o
.c
ie
h
c
e
T
e
c
A
Android Architecture
m
o An Activity Manager that manages the lifecycle of apps and provides a common navigation back stack
o Content Providers that enable apps to access data from other apps, such as the Contacts app, or to share their
own data
o
.c
System Apps
Android comes with a set of core apps for email, SMS messaging, calendars, internet browsing, contacts, and more.
ie
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
h
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
c
instead invoke whichever SMS app is already installed to deliver a message to the recipient you specify.
e Explain it.
What is the role of DVM in android?
T
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices.
e
It optimizes the virtual machine for memory, battery life and performance.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM.
c
Multiple class files are converted into one dex file.
m
o
.c
Role of DVM in Android
ie
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.
h
The Android Assets Packaging Tool (aapt) handles the packaging process.
c
Dalvik virtual machine uses register based architecture. With this architecture, Dalvik Virtual Machine has few
advantages over JAVA virtual machine such as:
e
● 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.
T
● Dalvik use less space, which means an uncompressed .dex file is smaller in size(few bytes) than compressed java
e
archive file(.jar file).
c
List out different types of layouts in android. Explain any two layouts.
A
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.
m
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
o
padding).
A Linear Layout respects margins between children and the gravity (right, center, or left alignment) of each child.
.c
<?xml version="1.0" encoding="utf-8"?>
ie
h
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
c
android:layout_height="match_parent"
android:paddingLeft="16dp"
e
android:paddingRight="16dp"
android:orientation="vertical" >
T
<EditText
android:layout_width="match_parent"
e
android:layout_height="wrap_content"
android:hint="@string/to" />
<EditText
c
android:layout_width="match_parent"
android:layout_height="wrap_content"
A
android:hint="@string/subject" />
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="@string/message" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="@string/send" />
</LinearLayout>
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).
m
o
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,
.c
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.
ie
Some of the many layout properties available to views in a RelativeLayout include:
1) android:layout_alignParentTop
h
If "true", makes the top edge of this view match the top edge of the parent.
2) android:layout_centerVertical
c
If "true", centers this child vertically within its parent.
e
3) android:layout_below
Positions the top edge of this view below the view specified with a resource ID.
4) android:layout_toRightOf
T
e
Positions the left edge of this view to the right of the view specified with a resource ID.
c
Sample code illustrating Relative Layout is as follows:
A
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />
<Spinner
android:id="@+id/dates"
m
android:layout_alignParentRight="true"
android:text="@string/done" />
o
</RelativeLayout>
.c
Frame Layout
Frame Layout is designed to block out an area on the screen to display a single item.
ie
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
h
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.
c
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:
e
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/framelayout"
T
android:layout_width="match_parent"
android:layout_height="match_parent"
e
android:layout_gravity="center"
android:foregroundGravity="fill"
c
android:foreground="#0f0"><!--foreground color for a FrameLayout-->
A
<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>
m
</FrameLayout>
Table Layout
o
.c
ie
h
c
e
T
A layout that arranges its children into rows and columns.
e
A Table Layout consists of a number of TableRow objects, each defining a row (actually, you can have other
children, which will be explained below).
c
Table Layout containers do not display border lines for their rows, columns, or cells.
Each row has zero or more cells; each cell can hold one View object.
A
The table has as many columns as the row with the most cells.
A table can leave cells empty.
Cells can span columns, as they can in HTML.
The width of a column is defined by the row with the widest cell in that column.
However, a Table Layout can specify certain columns as shrinkable or stretchable by calling
setColumnShrinkable() or setColumnStretchable().
If marked as shrinkable, the column width can be shrunk to fit the table into its parent object.
If marked as stretchable, it can expand in width to fit any extra space.
The total width of the table is defined by its parent container.
It is important to remember that a column can be both shrinkable and stretchable.
In such a situation, the column will change its size to always use up the available space, but never more.
.c
android:layout_height="match_parent"
android:stretchColumns="1">
<TableRow>
ie
<TextView
android:text="@string/table_layout_4_open"
android:padding="3dip" />
<TextView
h
android:text="@string/table_layout_4_open_shortcut"
android:gravity="right"
c
android:padding="3dip" />
</TableRow>
<TableRow>
e
T
<TextView
android:text="@string/table_layout_4_save"
e
android:padding="3dip" />
<TextView
c
android:text="@string/table_layout_4_save_shortcut"
android:gravity="right"
A
android:padding="3dip" />
</TableRow>
</TableLayout>
m
The code snippet below shows the general structure of the manifest file and every element that it can contain. Each
element, along with all of its attributes, is fully documented in a separate file.
<manifest>
<uses-permission />
<permission />
<uses-sdk />
<uses-configuration />
<uses-feature />
<supports-screens />
<application>
<activity>
m
<intent-filter>
<action />
o
<category />
<data />
.c
</intent-filter>
<meta-data />
</activity>
ie
<service>
<intent-filter> . . . </intent-filter>
h
<meta-data/>
</service>
<receiver>
c
<intent-filter> . . . </intent-filter>
<meta-data />
e
T
</receiver>
<provider>
e
<grant-uri-permission />
<meta-data />
c
<path-permission />
</provider>
A
</application>
</manifest>
ie
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:
h
o One GC pause instead of two
o Parallelized processing during the remaining GC pause
c
o Lower total GC time
o Improved garbage collection ergonomics
e
o Compacting GC to reduce background memory usage and fragmentation
Development and debugging improvements
T
o Support for sampling profiler
o Support for more debugging features
e
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.
.c
It is a set of development tools used to develop applications for Android platform.
Every time Google releases a new version of Android, a corresponding SDK is also released.
To be able to write programs with the latest features, developers must download and install each version’s SDK
ie
for the particular phone.
The Android SDK includes the following:
o Required libraries
o Debugger
o An emulator h
c
o Relevant documentation for the Android application program interfaces (APIs)
e
o Sample source code
o Tutorials for the Android OS
T
e
Explain the various types of Android Application. OR Explain types of android
application. And create any small application in android? Explain.
c
Mobile apps are basically little, self-contained programs, used to enhance existing functionality, hopefully in a
A
simple, more user-friendly way.
They all come with powerful web browsers, meaning you can do pretty much anything you can do on a desktop
computer in a phone’s browser. Normally, when people talk about apps they are almost always referring to
programs that run on mobile devices, such as Smartphones or Tablet Computers.
Each app provides limited and isolated functionality such as game, calculator or mobile web browsing. Although
apps may have avoided multitasking because of the limited hardware resources of the early mobile devices, their
specificity is now part of their desirability because they allow consumers to hand-pick what their device are able
to do.
Different types of Apps:
1) Native App
2) Web App
3) Hybrid App
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. m
o
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.
.c
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.
ie
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.
h
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.
c
Web apps became really popular when HTML5 came around and people realized that they can obtain native-like–
functionality in the browser.
Hybrid App e
T
This type of application has cross-platform compatibility but can still access a phone’s hardware.
e
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
c
JavaScript).
Hybrid apps run inside a native container, and leverage the device’s browser engine to render the HTML and
A
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.
m
o
After some processing, Android Studio opens and displays a "Hello World" app with default files. Following files will
be created after successful processing
.c
app > java > com.example.myfirstapp > MainActivity.java
app > res > layout > activity_main.xml
app > manifests > AndroidManifest.xml
Gradle Scripts > build.gradle
i e
h
What is parsing? Explain JSON parsing with example.
c
Extensible Markup Language (XML) is a set of rules for encoding documents in machine-readable form.
XML is a popular format for sharing data on the internet.
e
Websites that frequently update their content, such as news sites or blogs, often provide an XML feed so that
external programs can keep abreast of content changes.
T
Uploading and parsing XML data is a common task for network-connected apps.
e
We will see how to parse XML documents and use their data.
c
XmlPullParser, which is an efficient and maintainable way to parse XML on Android. Historically Android has had
two implementations of this interface:
A
KXmlParser via XmlPullParserFactory.newPullParser()
ExpatPullParser via Xml.newPullParser()
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"
}
],
m
o
"main":
{
.c
"temp":304.15,
"pressure":1009,
}
ie
}
JSON - Elements
h
An JSON file consist of many components. Here is the table defining the components of an JSON file and their
description −
c
Array([) - In a JSON file , square bracket ([) represents a JSON array
Objects({) - In a JSON file, curly bracket ({) represents a JSON object
e
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.,
T
e
JSON - Parsing
For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it.
c
Its syntax is −
A
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 −
m
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
o
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
.c
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
ie
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
h
String home = phone.getString("home");
String office = phone.getString("office");
c
// tmp hash map for single contact
e
HashMap<String, String> contact = new HashMap<>();
T
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
e
contact.put("email", email);
contact.put("mobile", mobile);
c
// adding contact to contact list
A
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
return null;
}
.c
external programs can keep abreast of content changes.
Uploading and parsing XML data is a common task for network-connected apps.
ie
We will see how to parse XML documents and use their data.
XmlPullParser, which is an efficient and maintainable way to parse XML on Android. Historically Android has had two
implementations of this interface:
h
c
KXmlParser via XmlPullParserFactory.newPullParser()
ExpatPullParser, via Xml.newPullParser()
XML Parsing
e
T
XML stands for Extensible Mark-up Language.
XML is a very popular format and commonly used for sharing data on the internet.
e
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.
c
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.
A
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 −
m
private XmlPullParserFactory
XmlPullParserFactory.newInstance();
xmlFactoryObject
o =
.c
private XmlPullParser myparser = xmlFactoryObject.newPullParser();
The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a
ie
Stream. In our case it is a stream.
Its syntax is given below:
h
myparser.setInput(stream, null);
The last step is to parse the XML. An XML file consist of events, Name, Text, AttributesValue etc., So XMLPullParser
c
has a separate function for parsing each of the component of XML file. Its syntax is given below −
c
case XmlPullParser.END_TAG:
A
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;
m
@Override
public void onCreate(Bundle savedInstanceState) {
o
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
.c
try {
InputStream is = getAssets().open("file.xml");
ie
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
h
Element element=doc.getDocumentElement();
c
element.normalize();
e
NodeList nList = doc.getElementsByTagName("employee");
T
for (int i=0; i<nList.getLength(); i++) {
e
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
c
tv1.setText(tv1.getText()+"\nName : " + getValue("name",
element2)+"\n");
A
tv1.setText(tv1.getText()+"Surname : " + getValue("surname",
element2)+"\n");
tv1.setText(tv1.getText()+"-----------------------");
}
}
m
o
.c
ie
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.
h
c
The View: The View is the portion of the application responsible for rendering the display, sending audio to speakers,
e
generating tactile feedback, and so on.
T
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
e
that will go to the application functions.
c
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
A
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.
m
o
.c
Following steps will create a grid of image thumbnails.
When an item is selected, a toast message will display the position of the image.
ie
Steps to create GridView are as follows:
Start a new project named HelloGridView.
Find some photos you'd like to use. Save the image files into the project's res/drawable/ directory.
h
Open the res/layout/main.xml file and insert the following:
T
android:layout_width="match_parent"
android:layout_height="match_parent"
e
android:columnWidth="90dp"
android:numColumns="auto_fit"
c
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
/>
A
android:gravity="center"
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
m
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).
o
.c
Create a new class called ImageAdapter that extends BaseAdapter:
ie
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
}
mContext = c;
h
public int getCount() {
c
e
return mThumbIds.length;
}
T
public Object getItem(int position) {
}
return null;
e
c
public long getItemId(int position) {
A
return 0;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
m
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
o
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
.c
R.drawable.sample_6, R.drawable.sample_7
};
}
ie
First, this implements some required methods inherited from BaseAdapter.
getItem(int) should return the actual object at the specified position in the adapter.
h
getItemId(int) should return the row id of the item, but it's not needed here.
c
The first method necessary is getView(). This method creates a new View for each image added to the
ImageAdapter.
e
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.
T
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
e
that, no matter the size of the drawable, each image is resized and cropped to fit in these dimensions, as
appropriate.
c
o setScaleType(ImageView.ScaleType) declares that images should be cropped toward the center
(if necessary).
A
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.
m
Adding a fragment to an activity
Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part of the activity's
o
overall view hierarchy.
There are two ways you can add a fragment to the activity layout:
ie
file for an activity with two fragments:
h
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
c
android:layout_width="match_parent"
android:layout_height="match_parent">
e
<fragment android:name="com.example.news.ArticleListFragment"
android:id="@+id/list"
T
android:layout_weight="1"
android:layout_width="0dp"
e
android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment"
c
android:id="@+id/viewer"
android:layout_weight="2"
A
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
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:
m
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.
o
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.
.c
ie
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.
h
c
e
T
e
c
Example to list Planet names in List View:
Basically we create a ListView class and use TextView objects for each row. Each planet name is rendered in a
TextView.
<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.
m
android:id="@+id/rowTextView"
android:layout_width="fill_parent"
o
android:layout_height="wrap_content"
android:padding="10dp"
.c
android:textSize="16sp" >
</TextView>
ie
Activity
Our main activity (SimpleListViewActivity) creates an ArrayAdapter, which holds the objects to be
displayed in the ListView.
h
The ArrayAdapter constructor is passed the resource ID of the TextView layout file
(R.layout.simplerow).
c
The ArrayAdapter will use it to instantiate a TextView for each row.
e
We then set the ArrayAdapter as our ListView's adapter.
package com.example.android;
T
import java.util.ArrayList;
e
c
import java.util.Arrays;
A
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
m
// Add more planets. If you passed a String[] instead of a List<String>
// into the ArrayAdapter constructor, you must not add more items.
o
// Otherwise an exception will occur.
listAdapter.add( "Ceres" );
.c
listAdapter.add( "Pluto" );
listAdapter.add( "Haumea" );
listAdapter.add( "Makemake" );
ie
listAdapter.add( "Eris" );
h
mainListView.setAdapter( listAdapter );
}
}
c
e
What is web services? How it integrates and implements in industrial
projects?
T
e
A web service is a standard used for exchanging information between applications or systems of heterogeneous
type.
c
Software applications written in various programming languages and running on various platforms can use web
services to exchange information over Internet using http protocol.
HTTP Request m
The client request from the browser will look like:
GET http://weatherinfo.org/getweather/mumbai HTTP/1.1
o
HTTP Response
The server response will look like .c
ie
HTTP/1.1 200 Ok
Date: Mon, 14 Apr 2014 10:20:58 GMT
Content-Type: text/xml
Content-length: 139
h
c
<City name="Mumbai" datetime="2014-04-14 10:20:58 GMT" >
<Condition>Scattered Clouds</Condition>
e
<Temp>33</Temp>
</City>
T
Line 1 is the initial line which has the HTTP response code – 200 OK, lines 2 through 4 are the HTTP headers, line 5
e
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.
c
Advantages of using RESTful webservice
A
RESTful Web services are designed with less dependence on proprietary middleware (for example, an application
server) than the SOAP- and WSDL-based kind.
As per the RESTful interface design, XML or JSON over HTTP is a powerful interface that allows internal
applications, such as Asynchronous JavaScript + XML/JSON (Ajax) - based custom user interfaces, to easily connect,
address, and consume resources.
The great fit between Ajax and REST has increased the amount of attention REST is getting these days.
Exposing a system’s resources through a RESTful API is a flexible way to provide different kinds of applications with
data formatted in a standard way. It helps to meet integration requirements that are critical to building systems
where data can be easily combined (mashups) and to extend or build on a set of base, RESTful services into
something much bigger.