Unit 5
Unit 5
Visit this Android SDK page, choose which platform and install it.
In Android SDK installed folder, run “Android SDK manager”, choose what Android
version you want to develop.
To integrate Android SDK with Eclipse IDE, you need to install Eclipse ADT plugin.
Refer to this official guide – “Installing the ADT Plugin“.
In Eclipse IDE, select “Help” -> Install New Software…”, and put below URL :
https://dl-ssl.google.com/android/eclipse/
Note
In my case, above ADT plugin is taking years to download, no idea why. If you are
facing the similar problem, just download and install the ADT plugin manually, refer to
this ADT plugin troubleshooting guide.
In Eclipse, you can access the “Android Virtual Device (AVD)” in Eclipse toolbar.
Click “new” to create a AVD.
In Eclipse, select “File -> New -> Project….”, “Android Project”, and input your
application detail. Eclipse will create all the necessary Android project files and
configuration.
5. Hello World
Locate the generated activity file, and modify a bit to output a string “Hello World”.
File : HelloWorldActivity.java
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloWorldActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
text.setText("Hello World, Android - mkyong.com");
setContentView(text);
}
}
6. Demo
Run it as “Android Application“, see output.
Press “Home” button (on right hand side), and you will noticed that “HelloWorld”
application is deployed successfully on the Android virtual device.
Android Screen UI Components
Up to this point, you have seen that the basic unit of an Android application is an
Activity. An Activity displays the user interface of your application, which may
contain widgets like buttons, labels, text boxes, etc. Typically, you define your UI using
an XML file (for example, the main.xml file located in the res/layout folder), which
may look like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
What happens is that during compilation time, each element in the XML file is compiled
into its equivalent Android GUI class, with attributes represented by methods. The
Android system then creates the UI of the Activity when it is loaded.
While it is always easier to build your UI using a XML file, there are times where you
need to build your UI dynamically during runtime (for example, when writing games).
Hence, it is also possible to create your UI entirely using code.
An Activity contains Views and ViewGroups. A View is a widget that has an appearance
on screen. Examples of widgets are buttons, labels, text boxes, etc. A View derives from
the base class android.view.View.
One or more Views can be grouped together into a ViewGroup. A ViewGroup (which is by
itself is a special type of View) provides the layout in which you can order the
appearance and sequence of views. Examples of Viewgroups are LinearLayout,
FrameLayout, etc. A ViewGroup derives from the base class android.view.ViewGroup.
LinearLayout
AbsoluteLayout
TableLayout
RelativeLayout
FrameLayout
ScrollView
The following sections will discuss each ViewGroup in more details. Note that in
practice, it is common to nest different types of layouts to create the UI you want.
For this article, create a new Android project and name it as shown in Figure 1.
Figure 1 Creating a new Android project using Eclipse
Eclipse provides only minimal support for designing Android UI and so you won't be
able to drag-and-drop of widgets on a design surface. Instead, you can use the free
DroidDraw tool available at http://www.droiddraw.org/. Figure 2 shows the DroidDraw
in action. You can drag-and-drop widgets onto different layouts and then use it to
generate its equivalent XML code. While DroidDraw is not perfect, it is very useful to
get you started with Android UI design and is a good tool to learn the various Views and
ViewGroups in Android.
Figure 2 The DroidDraw web application to design your Android UI
You can also download standalone versions of DroidDraw for Windows, Mac OS X, and
Linux.
LinearLayout
The LinearLayout arranges views in a single column or single row. Child views can
either be arranged vertically or horizontally. To see how LinearLayout works, let's
modify the main.xml file in the project:
Each View and ViewGroup has a set of common attributes, some of which are shown in
Table 1.
Attribute Description
layout_width Specifies the width of the View or ViewGroup
layout_height Specifies the height of the View or ViewGroup
layout_marginTop Specifies extra space on the top side of the View or ViewGroup
layout_marginBottom
Specifies extra space on the bottom side of the View or
ViewGroup
layout_marginLeft Specifies extra space on the left side of the View or ViewGroup
layout_marginRight Specifies extra space on the right side of the View or ViewGroup
layout_gravity Specifies how child Views are positioned
layout_weight
Specifies how much of the extra space in the layout to be
allocated to the View
layout_x Specifies the x-coordinate of the View or ViewGroup
layout_y Specifies the y-coordinate of the View or ViewGroup
Note that some of these attributes are only applicable when a View is in certain specific
ViewGroup(s). For example, the layout_weight and layout_gravity attributes are only
applicable if a View is either in a LinearLayout or TableLayout.
For example, the <TextView> element above has its width filling up the entire width of
its parent (which is the screen in this case) using the fill_parent constant. Its height is
indicated by the wrap_content constant, which means that its height is the height of its
content (in this case, the text contained within it). If you do not wish to have the
<TextView> view occupy the entire row, you can set its layout_width attribute to
wrap_content, like this:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
This will set the width of the view to be equal to the width of the text contained within it.
You can also set the width to an absolute value, like this:
<TextView
android:layout_width="105px"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
In this case, the width is set to 105 pixels wide. Let's modify the main.xml file by adding
a <Button> view as shown below:
The default orientation of LinearLayout is set to horizontal. If you want to change its
orientation to vertical, set the orientation attribute to vertical, like this:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
Figure 4 shows the effect of changing the orientation to vertical.
AbsoluteLayout
The AbsoluteLayout lets you specify the exact location of its children. Consider the
following UI defined in main.xml:
Author's Note. You should ideally use AbsoluteLayout when you need to reposition
your views when there is a change in the screen rotation.
TableLayout
The TableLayout groups views into rows and columns. You use the <TableRow>
element to designate a row in the table. Each row can contain one or more views. Each
view you place within a row forms a cell. The width for each column is determined by
the largest width of each cell in that column.
Populate main.xml with the following elements and observe the UI as shown in Figure 7.
Note that in the above example, there are two columns and four rows in the TableLayout.
The cell directly under the Password TextView is populated with an empty element. If
you don't do this, the Remember Password checkbox will then appear under the Password
TextView, like that shown in Figure 8.
Figure 8 Note the change in the position of the Remember Password view
RelativeLayout
The RelativeLayout lets you specify how child views are positioned relative to each
other. Consider the following main.xml file:
Notice that each view embedded within the RelativeLayout have attributes that allow
them to align with another view. These attributes are:
layout_alignParentTop
layout_alignParentLeft
layout_alignLeft
layout_alignRight
layout_below
layout_centerHorizontal
The value for each of these attributes is the ID for the view that you are referencing. The
above XML UI creates the screen shown in Figure 9.
The FrameLayout is a placeholder on screen that you can use to display a single view.
Views that you add to a FrameLayout is always anchored to the top left of the layout.
Consider the following content in main.xml:
Note: This example assumes that the res/drawable folder has an image named
androidlogo.png.
Figure 10 Using FrameLayout
If you add another view (such as a Button view) within the FrameLayout, the view will
overlap the previous view (see also Figure 11):
You can add multiple views to a FrameLayout, but each will stack on top of the previous
one.
ScrollView
Note: Do not use a ListView together with the ScrollView. The ListView is designed
for showing a list of related information and is optimized for dealing with large lists.
Introduction to Intents
Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.
It is generally used with startActivity() method to invoke activity, broadcast receivers etc.
The dictionary meaning of intent is intention or purpose. So, it can be described as the
intention to do action.
Types of Intents
There are following two types of intents supported by Android till version 4.1
Explicit Intents
These intents designate the target component by its name and they are typically used for
application-internal messages - such as an activity starting a subordinate service or
launching a sister activity. For example:
// Starts TargetActivity
startActivity(i);
Implicit Intents
These intents do not name a target and the field for the component name is left blank.
Implicit intents are often used to activate components in other applications. For example:
The target component which receives the intent can use the getExtras() method to get the
extra data sent by the source component. For example:
Let's see the simple example of implicit intent that displays a web page.
activity_main.xml
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6. <EditText
7. android:id="@+id/editText1"
8. android:layout_width="wrap_content"
9. android:layout_height="wrap_content"
10. android:layout_alignParentTop="true"
11. android:layout_centerHorizontal="true"
12. android:layout_marginTop="44dp"
13. android:ems="10" />
14. <Button
15. android:id="@+id/button1"
16. android:layout_width="wrap_content"
17. android:layout_height="wrap_content"
18. android:layout_below="@+id/editText1"
19. android:layout_centerHorizontal="true"
20. android:layout_marginTop="54dp"
21. android:text="Visit" />
22. </RelativeLayout>
Activity class
File: MainActivity.java
1. package org.sssit.implicitintent;
2. import android.net.Uri;
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.content.Intent;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. import android.widget.EditText;
10. public class MainActivity extends Activity {
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15. final EditText editText1=(EditText)findViewById(R.id.editText1);
16. Button button1=(Button)findViewById(R.id.button1);
17. button1.setOnClickListener(new OnClickListener() {
18. @Override
19. public void onClick(View arg0) {
20. String url=editText1.getText().toString();
21. Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
22. startActivity(intent);
23. }
24. });
25. }
26. }
Example-Explicit Intent
First Activitity
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.*;
import android.content.*;
import android.view.View;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in=new Intent(FirstActivity.this,SecondActivity.class);
startActivity(in);
}
});
}
Second Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.*;
import android.content.*;
import android.view.View;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in=new Intent(SecondActivity.this,FirstActivity.class);
startActivity(in);
}
});
}
Introduction to SQLite
What is SQLite?
SQLite is an Open Source database. SQLite supports standard relational database features
like SQL syntax, transactions and prepared statements. The database requires limited
memory at runtime (approx. 250 KByte) which makes it a good candidate from being
embedded into other runtimes.
SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long
in Java) and REAL (similar to double in Java). All other types must be converted into one
of these fields before getting saved in the database. SQLite itself does not validate if the
types written to the columns are actually of the defined type, e.g. you can write an integer
into a string column and vice versa.
SQLiteDatabase
Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase
with your database name and mode as a parameter. It returns an instance of SQLite
database which you have to recieve in your own object.Its syntax is given below:
SQLiteDatabase is the base class for working with a SQLite database in Android and
provides methods to open, query, update and close the database.
In addition it provides the execSQL() method, which allows to execute an SQL statement
directly.
The object ContentValues allows to define key/values. The key represents the table
column identifier and the value represents the content for the table record in this column.
ContentValues can be used for inserts and updates of database entries.
Queries can be created via the rawQuery() and query() methods or via the
SQLiteQueryBuilder class .
Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below
We can retrieve anything from datbase using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing
to the table. We can move the cursor forward and retrieve the data.
Example
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editRollno=(EditText)findViewById(R.id.editText1);
editName=(EditText)findViewById(R.id.editText2);
editMarks=(EditText)findViewById(R.id.editText3);
btnAdd=(Button)findViewById(R.id.button1);
btnDelete=(Button)findViewById(R.id.button2);
btnShowInfo=(Button)findViewById(R.id.button3);
btnAdd.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnShowInfo.setOnClickListener(this);
db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno
VARCHAR,name VARCHAR,marks VARCHAR);");
}
public void onClick(View view)
{
if(view==btnAdd)
{
if(editRollno.getText().toString().trim().length()==0||
editName.getText().toString().trim().length()==0||
editMarks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student VALUES('"+editRollno.getText()
+"','"+editName.getText()+
"','"+editMarks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
if(view==btnDelete)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE
rollno='"+editRollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
if(view==btnShowInfo)
{
Cursor c=db.rawQuery("SELECT * FROM student",null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
editRollno.setText("");
editName.setText("");
editMarks.setText("");
editRollno.requestFocus();
}
}