Você está na página 1de 106

[Type text]

Exercise : 1

Create “Hello World” application. That will display “Hello World” in the
middle of the screen in the red color with white background.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF" android:orientation="vertical">

Site:http://theandroid.in
[Type text]

<RelativeLayout android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/relativeLayout1"
android:background="#FFFFFF"
android:gravity="center">

<TextView android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView1"
android:layout_height="wrap_content"
android:text="Hello World"
android:textColor="#FF0000"
android:layout_gravity="center"
android:enabled="true">
</TextView>
</RelativeLayout>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as FirstActivity.java.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

FirstActivity.java :

package theandroid.in;

import android.app.Activity;
import android.os.Bundle;

public class FirstActivity extends Activity


{
/** @author Y@@D */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

Exercise : 2
To understand Activity, Intent
a. Create sample application with login module.(Check username and
password)
b. On successful login, go to next screen. And on failing login, alert user using
Toast.
c. Also pass username to next screen

So let’s get started by creating a simple project by opening eclipse IDE.

Site:http://theandroid.in
[Type text]

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableLayout
android:layout_height="wrap_content"
android:id="@+id/tableLayout1"
android:layout_width="match_parent">

<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:addStatesFromChildren="true"
android:id="@+id/tableRow1">

<TextView
android:id="@+id/txtUname"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="User Name:"></TextView>

<EditText
android:width="350px"
android:id="@+id/edtUname"
android:layout_height="wrap_content"
android:layout_width="match_parent">

</EditText>

</TableRow>

<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:addStatesFromChildren="true"
android:id="@+id/tableRow1">

<TextView
android:id="@+id/txtPwd"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Password:"></TextView>

<EditText
android:inputType="textPassword"
android:id="@+id/edtPwd"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</EditText>
</TableRow>
</TableLayout>

Site:http://theandroid.in
[Type text]

<Button
android:layout_height="wrap_content"
android:text="Login"
android:layout_width="wrap_content"
android:id="@+id/btnLogin"
android:layout_gravity="center">
</Button>
</LinearLayout>

main2.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/txtWelCome"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="WelCome"
android:layout_weight="1">
</TextView>

<FrameLayout
android:layout_weight="1"
android:id="@+id/frameLayout1"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<Button
android:text="Exit"
android:layout_height="wrap_content"
android:id="@+id/btnExit"
android:layout_width="wrap_content">
</Button>
</FrameLayout>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as SecondActivity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

SecondActivity.java:
package com.theandroid.in;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

Site:http://theandroid.in
[Type text]

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SecondActivity extends Activity implements OnClickListener


{
/** @author Y@@D */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button b= (Button) findViewById(R.id.btnLogin);


b.setOnClickListener(this);

}
public void onClick(View v)
{
EditText username = (EditText)findViewById(R.id.txtusername);
EditText password =(EditText)findViewById(R.id.txtpassword);
if(v.getId()==R.id.btnlogin)
{
Intent i = new Intent(this, Activity2.class);

EditText t1= (EditText) findViewById(R.id.edtUname);


EditText t2= (EditText) findViewById(R.id.edtPwd);
String s1= t1.getText().toString();
String s2= t2.getText().toString();

if(s1.equals("XYZ") && s2.equals("ABC"))


{
i.putExtra("Param", s1);
startActivity(i);
}
else
{
Toast t= Toast.makeText(this, "Invalid UserName or
Password..", Toast.LENGTH_LONG);
t.show();
} }
}

Activity2.java :

package com.theandroid.in;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Activity2 extends Activity implements OnClickListener {

protected void onCreate(Bundle savedInstanceState) {


// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);

Intent i= getIntent();

Site:http://theandroid.in
[Type text]

String str=i.getStringExtra("Param");
TextView t= (TextView) findViewById(R.id.txtWelCome);
t.setText("WelCome.. " + str);

Button b= (Button) findViewById(R.id.btnExit);


b.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

finish();

}
}

Exercise : 3
Create login application where you will have to validate EmailID(UserName).
Till the username and password is not validated, login button should remain
disabled.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<TableLayout
android:layout_height="wrap_content"
android:id="@+id/tableLayout1"
android:layout_width="match_parent">

<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:addStatesFromChildren="true"
android:id="@+id/tableRow1">

<TextView
android:id="@+id/txtUname"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="User Name:"></TextView>

Site:http://theandroid.in
[Type text]

<EditText
android:inputType="textEmailAddress"
android:id="@+id/edtUname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:width="350px">
<requestFocus></requestFocus>
</EditText>
</TableRow>

<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:addStatesFromChildren="true"
android:id="@+id/tableRow1">

<TextView
android:id="@+id/txtPwd"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Password:"></TextView>

<EditText
android:inputType="textPassword"
android:id="@+id/edtPwd"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</EditText>
</TableRow>
</TableLayout>

<Button
android:layout_height="wrap_content"
android:text="Login"
android:layout_width="wrap_content"
android:id="@+id/btnLogin"
android:layout_gravity="center"
android:enabled="false"></Button>
</LinearLayout>

main2.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<TextView
android:id="@+id/txtWelCome"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="WelCome"
android:layout_weight="1"></TextView>

<FrameLayout
android:layout_weight="1"
android:id="@+id/frameLayout1"
android:layout_gravity="center_horizontal"

Site:http://theandroid.in
[Type text]

android:layout_width="wrap_content"
android:layout_height="wrap_content">

<Button
android:text="Exit"
android:layout_height="wrap_content"
android:id="@+id/btnExit"
android:layout_width="wrap_content">
</Button>

</FrameLayout>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as ThirdActivity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

ThirdActivity.java:

package theandroid.in;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ThirdActivity extends Activity implements


OnClickListener,TextWatcher
{
/**@author Y@@D */
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText txtemail = (EditText)findViewById(R.id.txtemail);
EditText txtpassword = (EditText)findViewById(R.id.txtpassword);
txtemail.addTextChangedListener(this);
txtpassword.addTextChangedListener(this);
Button btn = (Button)findViewById(R.id.btnlogin);
btn.setOnClickListener(this);
}
public void onClick(View v)
{
EditText txte = (EditText)findViewById(R.id.txtemail);
EditText txtp = (EditText)findViewById(R.id.txtpassword);

if(txte.getText().toString().equals("Abc") &&
txtp.getText().toString().equals("Xyz"))
{

Site:http://theandroid.in
[Type text]

Intent i = new Intent(this,S2.class);


i.putExtra("txte", txte.getText().toString());
startActivity(i);

//Toast.makeText(this, "Login...",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Invalid",Toast.LENGTH_LONG).show();
}
}
public void afterTextChanged(Editable s)
{
EditText txte = (EditText)findViewById(R.id.txtemail);
EditText txtp = (EditText)findViewById(R.id.txtpassword);
Button btn = (Button)findViewById(R.id.btnlogin);
if(txte.getText().toString().equals("keval") &&
txtp.getText().toString().equals("nagaria"))
{
btn.setEnabled(true);
}
else
{
btn.setEnabled(false);
}
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub

}
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int
arg3) {
// TODO Auto-generated method stub

}
}

S2.java :

package theandroid.in

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class S2 extends Activity


{
/**@author Y@@D */
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i= getIntent();
//Toast.makeText(this,"Welcome",Toast.LENGTH_LONG).show();

Site:http://theandroid.in
[Type text]

String txte=i.getStringExtra("txte");
TextView tv=new TextView(this);
Button btnBack = new Button(this);
btnBack.setText("Back");
tv.setText("Welcome "+txte+" !");
tv.setTextColor(Color.rgb(255, 255, 100));
tv.setTextSize(25);
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(tv);
ll.addView(btnBack);
setContentView(ll);

btnBack.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
//setContentView(R.layout.main);
finish();
}
});
}
}

Exercise : 4
Create and Login application as above. On successful login, open browser with
any URL.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<TableLayout
android:layout_height="wrap_content"
android:id="@+id/tableLayout1"
android:layout_width="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:addStatesFromChildren="true"
android:id="@+id/tableRow1">

<TextView
android:id="@+id/txtUname"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="User Name:"></TextView>

<EditText
android:inputType="textEmailAddress"
android:id="@+id/edtUname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:width="350px">
<requestFocus></requestFocus>
</EditText>

</TableRow>

<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:addStatesFromChildren="true"
android:id="@+id/tableRow1">

<TextView
android:id="@+id/txtPwd"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Password:">
</TextView>

<EditText
android:inputType="textPassword"
android:id="@+id/edtPwd"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</EditText>

</TableRow>

Site:http://theandroid.in
[Type text]

</TableLayout>

<Button
android:layout_height="wrap_content"
android:text="Login"
android:layout_width="wrap_content"
android:id="@+id/btnLogin"
android:layout_gravity="center"
android:enabled="false"> </Button>

</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as LoginActivity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

LoginActivity.java:

package com.theandroid.in;

import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.text.Editable;

import android.text.TextWatcher;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

public class LoginActivity extends Activity implements OnClickListener,


TextWatcher{

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

Site:http://theandroid.in
[Type text]

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

EditText uname= (EditText) findViewById(R.id.edtUname);

uname.addTextChangedListener(this);

//uname.setOnFocusChangeListener(this);

EditText pwd= (EditText) findViewById(R.id.edtPwd);

pwd.addTextChangedListener(this);

//pwd.setOnFocusChangeListener(this);

Button b= (Button) findViewById(R.id.btnLogin);

b.setOnClickListener(this);

public void onClick(View v) {

Intent i= new Intent("android.intent.action.VIEW");

i.setData(Uri.parse("http://www.google.co.in/"));

startActivity(i);

public void afterTextChanged(Editable s) {

EditText t1= (EditText) findViewById(R.id.edtUname);

EditText t2= (EditText) findViewById(R.id.edtPwd);

String s1= t1.getText().toString();

String s2= t2.getText().toString();

Button b= (Button) findViewById(R.id.btnLogin);

Site:http://theandroid.in
[Type text]

if(s1.equals("Xyz") && s2.equals("Abc"))

b.setEnabled(true);

else

b.setEnabled(false);

public void onTextChanged(CharSequence s, int start, int before, int


count) {

@Override

public void beforeTextChanged(CharSequence s, int start, int count,

int after) {

// TODO Auto-generated method stub

Exercise : 5
Create an application that will pass some number to the next screen, and on the
next screen that number of items should be display in the list.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="vertical">

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edtTxt"> </EditText>

<Button
android:text="Click Me"
android:id="@+id/btnPrc"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"> </Button>

</LinearLayout>

main2.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<Button
android:text="Add Item"
android:layout_gravity="center"
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"> </Button>

<ListView
android:layout_height="wrap_content"
android:id="@android:id/list"
android:layout_width="match_parent"
android:longClickable="true"> </ListView>

</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as PassDataActivity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class


Site:http://theandroid.in
[Type text]

PassDataActivity.java:
package com.theandroid.in;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

public class PassDataActivity extends Activity implements OnClickListener {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Button b=(Button) findViewById(R.id.btnPrc);

b.setOnClickListener(this);

public void onClick(View v) {

Intent i=new Intent(this,Activity2.class);

EditText t1= (EditText) findViewById(R.id.edtTxt);

String s1 = t1.getText().toString();

i.putExtra("Param", s1);

startActivity(i);

Site:http://theandroid.in
[Type text]

Activity2.java :

package com.theandroid.in;

import java.util.ArrayList;

import android.app.ListActivity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.ArrayAdapter;

import android.widget.Button;

public class Activity2 extends ListActivity implements OnClickListener{

ArrayList<String> l=new ArrayList<String>();

ArrayAdapter<String> a;

int i=0;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main2);

a = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 ,l);

setListAdapter(a);

for(i=1; i<= Integer.parseInt(getIntent().getStringExtra("Param"));


i++)

l.add("Item : "+i);

Button b= (Button) findViewById(R.id.btnAdd);

b.setOnClickListener(this);

Site:http://theandroid.in
[Type text]

public void onClick(View v) {

a = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 ,l);

setListAdapter(a);

l.add("Item : " + i);

i++;

Exercise : 6
Understand resource folders :
a. Create spinner with strings taken from resource folder(res >> value folder).
b. On changing spinner value, change image.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner1"
android:entries="@array/Spiner"> </Spinner>

<ImageView
android:src="@drawable/icon"
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
</LinearLayout>

Site:http://theandroid.in
[Type text]

Now we are creating activities by right click on your package folder and create
classes and name them as Prog_6Activity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

Prog_6Activity.java:

package theandroid.in;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class Prog_6Activity extends Activity implements


OnItemSelectedListener {

Integer[] imageIDs = {
R.drawable.blue,
R.drawable.sunset,
R.drawable.lilies,
R.drawable.winter};

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Spinner sp= (Spinner) findViewById(R.id.spinner1);


sp.setOnItemSelectedListener(this);
}

public void onItemSelected(AdapterView<?> arg0, View arg1, int


arg2,long arg3)
{
Toast.makeText(this, "Selected Item is = "+
arg0.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();

ImageView imageView = (ImageView)


findViewById(R.id.imageView1);
imageView.setImageResource(imageIDs[arg2]);

public void onNothingSelected(AdapterView<?> arg0) {


// TODO Auto-generated method stub

}
}

Site:http://theandroid.in
[Type text]

Exercise : 7
Understand Menu option.
a. Create an application that will change color of the screen, based on selected
options from the menu.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<RelativeLayout

Site:http://theandroid.in
[Type text]

android:id="@+id/relativeLayout1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1.09" android:background="@color/bgcolor">
</RelativeLayout>

</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as SeventhActivity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

SeventhActivity.java:

package theandroid.in;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;

public class SeventhActivity extends Activity


{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
CreateMenu(menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
return MenuChoice(item);
}
private void CreateMenu(Menu menu)
{
MenuItem mnu1 = menu.add(0, 0, 0, "Red");
{
mnu1.setAlphabeticShortcut('r');
mnu1.setIcon(R.drawable.icon);
}
MenuItem mnu2 = menu.add(0, 1, 0, "Green");
{
mnu2.setAlphabeticShortcut('g');
mnu2.setIcon(R.drawable.icon);
}
MenuItem mnu3 = menu.add(0, 2, 0, "White");

Site:http://theandroid.in
[Type text]

{
mnu3.setAlphabeticShortcut('w');
mnu3.setIcon(R.drawable.icon);
}
}
private boolean MenuChoice(MenuItem item)
{
RelativeLayout l= (RelativeLayout)
findViewById(R.id.relativeLayout1);

switch (item.getItemId())
{
case 0:
l.setBackgroundColor(Color.RED);
return true;
case 1:
l.setBackgroundColor(Color.GREEN);
return true;
case 2:
l.setBackgroundColor(Color.WHITE);
return true;
}
return false;
}
}

Exercise : 8
Create an application that will display toast(Message) on specific interval of
time.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.
main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bgcolor">
<Button android:layout_height="wrap_content"
android:id="@+id/btnfinish" android:layout_width="match_parent"
android:text="Press Me"></Button>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as EightActivity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

Site:http://theandroid.in
[Type text]

EightActivity.java:
package theandroid.in;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class EightActivity extends Activity


{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final Handler h = new Handler();


final Runnable r = new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(), "Y@@D",
Toast.LENGTH_SHORT).show();
}
};
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
h.post(r);
}
}, 1000, 5000);
Button b = (Button)findViewById(R.id.btnfinish);
b.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
finish();

android.os.Process.killProcess(android.os.Process.myPid());
}
});
}
}

OR

Site:http://theandroid.in
[Type text]

Exercise : 8
Create an application that will display toast(Message) on specific interval of
time.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1" android:background="@color/bgcolor">
<Chronometer android:id="@+id/chronometer1" android:text="Chronometer"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:layout_weight="0.05" android:visibility="invisible"></Chronometer>
<EditText android:id="@+id/editText1"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:enabled="false">
<requestFocus></requestFocus>
</EditText>
</LinearLayout>

Site:http://theandroid.in
[Type text]

Now we are creating activities by right click on your package folder and create
classes and name them as Chronometer.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

Chronometer.java:
package theandroid.in;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.EditText;
import android.widget.Toast;

public class ChronometerActivity extends Activity


{

int i=0;
int Duration=10;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Chronometer chn = (Chronometer)findViewById(R.id.chronometer1);


chn.start();
chn.setOnChronometerTickListener(new OnChronometerTickListener()
{
public void onChronometerTick(Chronometer arg0)
{
EditText txt =
(EditText)findViewById(R.id.editText1);
txt.setText("Message Will Be Display After
["+(Duration-(i+1))+"] Seconds");
i++;
if(i>=Duration)
{
Toast.makeText(ChronometerActivity.this,
"Message"+(i/10), 10000).show();
Duration+=10;
}
}
});
}
}

Site:http://theandroid.in
[Type text]

Exercise : 9
Create a background application that will open activity on specific time.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bgcolor">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="180dp"
android:text="Start Service"></Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"

Site:http://theandroid.in
[Type text]

android:layout_below="@+id/button1"
android:layout_alignLeft="@+id/button1"
android:layout_marginTop="18dp" android:text="Stop
Service"></Button>

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content" android:text="BG Service
Demo" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"></TextView>
</RelativeLayout>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as MyService.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

MyService.java
package theandroid.in;

import kmn.servicedemo.R;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service


{
/** @author Y@@D */
private static final String TAG = "MyService";
MediaPlayer player;

public IBinder onBind(Intent intent)


{
return null;
}

public void onCreate()


{
Toast.makeText(this, "My Service Created",
Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");

player = MediaPlayer.create(this, R.raw.braincandy);


player.setLooping(false); // Set looping
}

Site:http://theandroid.in
[Type text]

public void onDestroy()


{
Toast.makeText(this, "My Service Stopped",
Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}

public void onStart(Intent intent, int startid)


{
Toast.makeText(this, "My Service Started",
Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}

Nine.java

package theandroid.in;

import kmn.servicedemo.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Nine extends Activity implements OnClickListener


{
private static final String TAG = "ServicesDemo";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button)findViewById(R.id.button1);
Button stop = (Button)findViewById(R.id.button2);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}

public void onClick(View v)


{
if(v.getId()==R.id.button1)
{
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
//break;
}
if(v.getId()==R.id.button2)
{
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
//break;
}
}
}

Site:http://theandroid.in
[Type text]

Exercise : 10
Create an application that will have spinner with list of animation names. On
selecting animation name , that animation should affect on the images
displayed below.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

Site:http://theandroid.in
[Type text]

<Spinner
android:layout_width="match_parent"
android:id="@+id/spinner1"
android:layout_height="wrap_content"
android:entries="@array/animation">
</Spinner>

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:src="@drawable/icon"
android:layout_height="wrap_content">
</ImageView>
</LinearLayout>

-> in this problem we make “anim” folder to res. Directory and


create an xml file like following:

alpha.xml :

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="5000"
android:repeatMode="reverse"
android:repeatCount="infinite"
/>

</set>

rotate.xml :

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000"
android:repeatMode="reverse"
android:repeatCount="infinite"
/>

</set>

scale.xml :

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="0"
android:toXScale="1"
android:fromYScale="0"
android:toYScale="1"

Site:http://theandroid.in
[Type text]

android:pivotX="50%"
android:pivotY="50%"
android:duration="5000"
android:repeatMode="reverse"
android:repeatCount="infinite"
/>

</set>

translate.xml :

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromXDelta="0"
android:toXDelta="200"
android:fromYDelta="0"
android:toYDelta="200"
android:duration="5000"
android:repeatMode="reverse"
android:repeatCount="infinite"

/>
</set>

Now we are creating activities by right click on your package folder and create
classes and name them as AnimationDemo.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

AnimationDemo.java:

package com.theandroid.in;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.animation.Animation;

import android.view.animation.AnimationUtils;

import android.widget.AdapterView;

import android.widget.ImageView;

import android.widget.Spinner;

Site:http://theandroid.in
[Type text]

import android.widget.AdapterView.OnItemSelectedListener;

public class AnimationDemo extends Activity implements


OnItemSelectedListener {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Spinner sp = (Spinner) findViewById(R.id.spinner1);

sp.setOnItemSelectedListener(this);

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,

long arg3) {

// TODO Auto-generated method stub

ImageView img = (ImageView)findViewById(R.id.imageView1);

if(arg3==0)

Animation an = AnimationUtils.loadAnimation(this,
R.anim.alpha);

img.startAnimation(an);

if(arg3==1)

Animation an = AnimationUtils.loadAnimation(this,
R.anim.rotation);

img.startAnimation(an);

Site:http://theandroid.in
[Type text]

if(arg3==2)

Animation an = AnimationUtils.loadAnimation(this,
R.anim.translate);

img.startAnimation(an);

if(arg3==3)

Animation an = AnimationUtils.loadAnimation(this,
R.anim.scale);

img.startAnimation(an);

public void onNothingSelected(AdapterView<?> arg0) {

// TODO Auto-generated method stub

Exercise : 11
Understanding of UI :
a. Create an UI such that , one screen have list of all the types of cars.
b. On selecting of any car name, next screen should show Car details like :
name , launched date ,company name, images(using gallery) if available, show
different colors in which it is available.

So let’s get started by creating a simple project by opening eclipse IDE.

Site:http://theandroid.in
[Type text]

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bgcolor">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/lv"
android:entries="@array/carname"
/>
</LinearLayout>

Main1.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:background="@color/bgcolor">

<TableLayout android:orientation="vertical" android:gravity="center"


android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableRow android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Gallery android:id="@+id/examplegallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></Gallery>
</TableRow >

<TableRow android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</TableRow>
</TableLayout>

</LinearLayout>

Site:http://theandroid.in
[Type text]

Now we are creating activities by right click on your package folder and create
classes and name them as ElevenActivity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

ElevenActivity.java:
package theandroid.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ElevenActivity extends Activity implements OnItemClickListener


{
/** @author Y@@D */
ListView lv;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv=(ListView) findViewById(R.id.lv);
lv.setClickable(true);
lv.setOnItemClickListener(this);
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,


long arg3)
{
try
{
Integer itn=Integer.valueOf(arg2);
String ext=itn.toString();
Intent i = new Intent(this,CarInfo.class);
i.putExtra("CarPos", ext);
startActivity(i);
}
catch(Exception e)
{
Toast.makeText(this, e.getMessage()+" OnItemClick",
Toast.LENGTH_LONG).show();
}
}
}

CarInfo.java

package kmn.Eleven;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;

Site:http://theandroid.in
[Type text]

import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

public class CarInfo extends Activity


{
/** @author Y@@D */
TextView tv;
private Gallery gallery;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);

tv=(TextView) findViewById(R.id.tv);
Intent i=this.getIntent();
String str =i.getStringExtra("CarPos");
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this,str));
if(str.equals("0"))
{
tv.setText("Name:Maruti Suzuki 800"+"\n"+"Launched
Date:1/3/1987"+"\n"+"Company Name:Maruti Suzuki"+"\nColors
Available:\nWhite\nBlue\nRed\nLight Yellow");
}
else if(str.equals("1"))
{
tv.setText("Name:Hyundai Accent Executive"+"\n"+"Launched
Date:15/10/2010"+"\n"+"Company Name:Hyundai"+"\nColors
Available:\nGray\nOcean Blue\nMidnight Black\nMaganta Blue");
}
else if(str.equals("2"))
{
tv.setText("Name:Chevrolet Beat"+"\n"+"Launched
Date:11/11/2011"+"\n"+"Company Name:Chevrolet"+"\nColors
Available:\nMidnight Black\nAmazon Green\nRoyal Gold\nSport Red");
}
else
{
tv.setText("No car available");
}
}
}
class AddImgAdp extends BaseAdapter
{
int GalItemBg;
private Context cont;
String positionLast;
private Integer[] Imgidb = {R.drawable.b1, R.drawable.b2,
R.drawable.b3, R.drawable.b4};
private Integer[] Imgidh = {R.drawable.h1, R.drawable.h2,
R.drawable.h3, R.drawable.h4};
private Integer[] Imgidm = {R.drawable.m1, R.drawable.m2,
R.drawable.m3, R.drawable.m4};

Site:http://theandroid.in
[Type text]

public AddImgAdp(Context c,String pos)


{
cont = c;
positionLast=pos;
TypedArray typArray =
c.obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg =
typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackgrou
nd, 0);

typArray.recycle();
}

public int getCount()


{
if(positionLast.equals("0"))
{
return Imgidm.length;
}
else if(positionLast.equals("1"))
{
return Imgidh.length;
}
else if(positionLast.equals("2"))
{
return Imgidb.length;
}
else
{
return Imgidm.length;
}
}

public Object getItem(int position) {


return position;
}

public long getItemId(int position) {


return position;
}

public View getView(int position, View convertView, ViewGroup parent)


{
ImageView imgView = new ImageView(cont);
if(positionLast.equals("0"))
{
imgView.setImageResource(Imgidm[position]);
}
else if(positionLast.equals("1"))
{
imgView.setImageResource(Imgidh[position]);
}
else if(positionLast.equals("2"))
{
imgView.setImageResource(Imgidb[position]);
}
else
{
imgView.setImageResource(Imgidm[position]);
}
// Fixing width & height for image to display

Site:http://theandroid.in
[Type text]

imgView.setLayoutParams(new Gallery.LayoutParams(200, 200));


imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
Exercise : 12
Understanding content providers and permissions:
a. Read phonebook contacts using content providers and display in list.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Now open your main.xml under res -> layout folder and type the following
code.

main.xml:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"

Site:http://theandroid.in
[Type text]

android:layout_height="fill_parent"
android:weightSum="1">

<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="@+id/textView1"
android:layout_weight="0.03"
android:layout_width="fill_parent"
android:textSize="10pt"> </TextView>

<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:layout_weight="0.03"
android:id="@+id/textView2"
android:layout_width="fill_parent"> </TextView>

</LinearLayout>

read_list.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
android:id="@+id/listcont"
android:layout_height="wrap_content"
android:layout_width="match_parent"> </ListView>

</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as ReadContactActivity.java. Type the following
code respectively.

Right Click on package folder -> New -> Class

ReadContactActivity.java:
package com.readcontact;

import android.app.Activity;

import android.database.Cursor;

import android.os.Bundle;

Site:http://theandroid.in
[Type text]

import android.provider.Contacts;

import android.provider.Contacts.People;

import android.util.Log;

import android.widget.ListView;

import android.widget.SimpleCursorAdapter;

public class ReadContactActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.read_list);

String[] requestedColumns = {

Contacts.People.NAME,

Contacts.People.NUMBER

};

Cursor oneContact =managedQuery(Contacts.People.CONTENT_URI,


null, null, null,null);

SimpleCursorAdapter cursorAdapter =

new SimpleCursorAdapter(this, R.layout.main, oneContact,


requestedColumns, new int[]{R.id.textView1,R.id.textView2});

ListView ls=(ListView)findViewById(R.id.listcont);

ls.setAdapter(cursorAdapter);

Site:http://theandroid.in
[Type text]

Now everything is ready and before running your project make sure that you
an entry of new activity name in AndroidManifest.xml file. Open you
AndroidManifest.xml file and modify the code as below.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.readcontact"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission
android:name="android.permission.READ_CONTACTS"></uses-permission>

<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".ReadContactActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>

</application>
</manifest>

Exercise : 13
Read messages from the mobile and display it on the screen.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="20dip"
/>
</LinearLayout>

Site:http://theandroid.in
[Type text]

Now we are creating activities by right click on your package folder and create
classes and name them as ReadMessagesActivity.java. Type the following
code respectively.

Right Click on package folder -> New -> Class

ReadMessagesActivity.java:
package com.android.ReadMessages;

import android.app.Activity;

import android.database.Cursor;

import android.graphics.Color;

import android.net.Uri;

import android.os.Bundle;

import android.widget.TextView;

public class ReadMessagesActivity extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

TextView view = new TextView(this);

Uri uriSMS = Uri.parse("content://sms");

Cursor c = getContentResolver().query(uriSMS, null, null,


null,null);

String sms = "";

while (c.moveToNext())

Site:http://theandroid.in
[Type text]

sms += "From :" + c.getString(2) + " : " +


c.getString(11)+"\n";

view.setText(sms);

view.setBackgroundColor(Color.WHITE);

view.setTextColor(Color.BLUE);

view.setTextSize(20);

setContentView(view);

Now everything is ready and before running your project make sure that you
an entry of new activity name in AndroidManifest.xml file. Open you
AndroidManifest.xml file and modify the code as below.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.ReadMessages"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.READ_SMS"></uses-
permission>

<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".ReadMessagesActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>

</application>
</manifest>

Site:http://theandroid.in
[Type text]

Exercise : 14

Create an application to call specific entered number by user in the EditText.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="calling.........."
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edt"
/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"

Site:http://theandroid.in
[Type text]

android:text="call"
/>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as callnumber.java. Type the following code
respectively.

Right Click on package folder -> New -> Class


callnumber.java:
package com.android.test;

import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

import android.view.View;

import android.view.View.OnClickListener;

public class callnumber extends Activity implements OnClickListener {

TextView tv;

EditText edt;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Site:http://theandroid.in
[Type text]

edt = (EditText) findViewById(R.id.edt);

tv =(TextView) findViewById(R.id.tv);

Button btn = (Button) findViewById(R.id.btn);

btn.setOnClickListener(this);

public void onClick(View v) {

// TODO Auto-generated method stub

tv.setText("calling "+edt.getText());

if(edt.getText().length()>0)

try

Intent intent = new Intent(Intent.ACTION_CALL);

intent.setData(Uri.parse("tel:"+edt.getText()));

startActivity(intent);

catch (Exception e)

Toast.makeText(this,"problem calling",10000).show();

Site:http://theandroid.in
[Type text]

Now everything is ready and before running your project make sure that you
an entry of new activity name in AndroidManifest.xml file. Open you
AndroidManifest.xml file and modify the code as below.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.CALL_PHONE"></uses-
permission>

<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".callnumber"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>

</application>
</manifest>

Exercise : 15
Create an application that will create database with table of User credential.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bgcolor">
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as FifteenActivity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class


FifteenActivity.java:
package theandroid.in;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

Site:http://theandroid.in
[Type text]

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class FifteenActivity extends Activity


{
/** @author Y@@D */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

SQLiteDatabase myDB= null;


String TableName = "myTable";

String Data="";

/* Create a Database. */
try
{
myDB = this.openOrCreateDatabase("DatabaseName",
MODE_PRIVATE, null);

/* Create a Table in the Database. */


myDB.execSQL("CREATE TABLE IF NOT EXISTS " + TableName +
" (Field1 VARCHAR, Field2 INT(3));");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO " + TableName + " (Field1,
Field2)" + " VALUES ('Y@@D', 22);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName ,
null);

int Column1 = c.getColumnIndex("Field1");


int Column2 = c.getColumnIndex("Field2");

// Check if our result was valid.


c.moveToFirst();
if (c != null)
{
// Loop through all Results
do
{
String Name = c.getString(Column1);
int Age = c.getInt(Column2);
Data =Data +Name+"/"+Age+"\n";
}while(c.moveToNext());
}
TextView tv = new TextView(this);
tv.setBackgroundColor(Color.BLUE);
tv.setTextColor(Color.WHITE);
tv.setText(Data);
setContentView(tv);
}
catch(Exception e)
{
Log.e("Error", "Error", e);
}
finally
{

Site:http://theandroid.in
[Type text]

if (myDB != null)
myDB.close();
}
}
}

DropTb.java :

package theandroid.in;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;

public class DropTb extends Activity


{

/** @author Y@@D */


@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

SQLiteDatabase myDB= null;


String TableName = "myTable";

/**
* Create a Database.
* */
try
{
myDB = this.openOrCreateDatabase("DatabaseName",
MODE_PRIVATE, null);
myDB.execSQL("DROP TABLE IF EXISTS "+TableName+";");

}
catch(Exception e)
{
Log.e("Error", "Error", e);
}
finally
{
if (myDB != null)
myDB.close();
}
}
}

Site:http://theandroid.in
[Type text]

Exercise : 16
Create an application to read file from asset folder and copy it in memory card.

Screen Shot:

Now open your main.xml under res -> layout folder and type the following
code.

main.xml:

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tv"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edt1"
/>

Site:http://theandroid.in
[Type text]

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tv1"
android:text="Enter file name from above list that you want to copy in
below edit text"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edt2"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="copy"
/>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as SixteenActivity.java.Type the following code
respectively.

Right Click on package folder -> New -> Class


SixteenActivity.java:

package com.android.testData;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import android.app.Activity;

import android.content.res.AssetManager;

import android.os.Bundle;

import android.os.Environment;

import android.view.View;

import android.view.View.OnClickListener;

Site:http://theandroid.in
[Type text]

import android.widget.*;

public class SixteenActivity extends Activity implements OnClickListener{

/** Called when the activity is first created. */

Button btn;

EditText edt1,edt2;

TextView tv,tv1 ;

File file;

String a[];

InputStream is;

OutputStream out = null;

InputStreamReader irs;

byte[] buffer;

AssetManager am;

int read;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

tv =(TextView) findViewById(R.id.tv);

tv1 =(TextView) findViewById(R.id.tv1);

edt1=(EditText) findViewById(R.id.edt1);

edt2=(EditText) findViewById(R.id.edt2);

btn=(Button) findViewById(R.id.btn);

btn.setOnClickListener(this);

Site:http://theandroid.in
[Type text]

am = getAssets();

try

a=am.list("files");

for(int k=0;k<a.length;k++)

edt1.append(a[k]+"\n");

catch(Exception e)

Toast.makeText(this, e.getMessage()+" ONCREATE",


Toast.LENGTH_LONG).show();

public void onClick(View v) {

// TODO Auto-generated method stub

try {

is =am.open("files"+File.separator+edt2.getText());

irs=new InputStreamReader(is);

String newFileName =
Environment.getExternalStorageDirectory()+File.separator+edt2.getText();

out = new FileOutputStream(newFileName);

buffer = new byte[1024];

int result = irs.read();

while(result != -1)

Site:http://theandroid.in
[Type text]

//TO GET THE CONTENT OF FILE ON THE SCREEN REMOVE THE


BELOW TWO LINES COMMENTS

//char b = (char)result;

//tv.append(b+"");

result = irs.read();

while((read = is.read(buffer)) != -1)

out.write(buffer, 0, read);

} catch (IOException e) {

// TODO Auto-generated catch block

Toast.makeText(this, e.getMessage()+" onclick",


Toast.LENGTH_LONG).show();

Exercise : 17
Create an application that will play a media file from the memory card.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">

<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="match_parent"
android:background="@color/bgcolor"
android:layout_height="match_parent">

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_alignLeft="@+id/button1"
android:layout_marginTop="16dp"
android:text="stop">
</Button>

<MediaController

Site:http://theandroid.in
[Type text]

android:id="@+id/mediaController1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="21dp">
</MediaController>

<Button
android:layout_width="wrap_content"
android:id="@+id/button1"
android:text="start"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="148dp">
</Button>

</RelativeLayout>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as SeventeenActivity.java.Type the following code
respectively.

Right Click on package folder -> New -> Class


SeventeenActivity.java:
package kmn.Seventeen;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class SeventeenActivity extends Activity


{
/** @author Y@@D */

MediaPlayer player=null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start=(Button)findViewById(R.id.button1);
Button stop=(Button)findViewById(R.id.button2);
getSystemService(Context.AUDIO_SERVICE);
start.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0)


{

try

Site:http://theandroid.in
[Type text]

{
player=null;
player=new MediaPlayer();

String
audioFilePath="/sdcard/braincandy.mp3";
player.setDataSource(audioFilePath);
player.prepare();
player.start();
}
catch(Exception e)
{

Toast.makeText(SeventeenActivity.this,""+e,Toast.LENGTH_LONG).show();

}
}
});
stop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
player.stop();
}
});
}
}

-> step to add a mp3 file to sdcard

1)goto the ddms

2)click on push button

3)and select the given mp3 file.

Exercise : 18
Create an application to make Insert, update, Delete and retrieve operation on
the database.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Site:http://theandroid.in
[Type text]

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FirstName"> </TextView>

<EditText
android:layout_width="match_parent"
android:id="@+id/txtFnm"
android:layout_height="wrap_content"> </EditText>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LastName:"></TextView>

Site:http://theandroid.in
[Type text]

<EditText
android:layout_width="match_parent"
android:id="@+id/txtLnm"
android:layout_height="wrap_content"> </EditText>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnInsert"
android:text="Insert"> </Button>

<Button
android:id="@+id/btnDel"
android:layout_height="wrap_content"
android:text="Delete"
android:layout_width="wrap_content"></Button>

<Button
android:id="@+id/btnUpd"
android:layout_height="wrap_content"
android:text="Update"
android:layout_width="wrap_content"></Button>

<Button
android:text="Display"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

</LinearLayout>

Now create 3 xml layouts by right clicking on res/layout -> New -> Android
XML File and name them as update.xml, delete.xml and display.xml and
type the following code in respective files.

Update.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter ID of Record You want to update:">
</TextView>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtId"> </EditText>

<TextView

Site:http://theandroid.in
[Type text]

android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FirstName:"> </TextView>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtFnm"></EditText>

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LastName:"></TextView>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtLnm"></EditText>

<Button
android:text="Update"
android:id="@+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

<Button
android:text="Cancel"
android:id="@+id/btnCan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

</LinearLayout>

delete.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:text="Enter Id:"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>

<EditText
android:layout_width="match_parent"
android:id="@+id/txtId"
android:layout_height="wrap_content"> </EditText>

<Button
android:text="Delete"
android:id="@+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

Site:http://theandroid.in
[Type text]

</LinearLayout>

display.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/tv1"
android:textStyle="bold"
android:textSize="6pt"
android:layout_width="wrap_content"
android:layout_height="fill_parent"> </TextView>

</LinearLayout>

Now we need 4 activities by right click on your package folder and create
classes and name them as InsertActivity.java, UpdateActivity.java and
DeleteActivity.java and DisplayActivity.java. Type the following code
respectively.

Right Click on package folder -> New -> Class

InsertActivity.java
package com.firstdb;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class InsertActivity extends Activity {


/** Called when the activity is first created. */

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.main);

finalSQLiteDatabase
mydb=openOrCreateDatabase("firstdb.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);

String CREATE_TABLE="CREATE TABLE IF NOT EXISTS tbl_stud(id INTEGER PRIMARY KEY

Site:http://theandroid.in
[Type text]

AUTOINCREMENT,firstname TEXT,lastname TEXT);";

mydb.execSQL(CREATE_TABLE);

Button btn1=(Button)findViewById(R.id.btnInsert);

Button btn2=(Button)findViewById(R.id.btnDel);

Button btn3=(Button)findViewById(R.id.btnUpd);

Button btn4=(Button)findViewById(R.id.button1);

btn4.setOnClickListener(new View.OnClickListener(
){
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(),DisplayActivity.class));
}
});

final TextView txtFnm=(TextView)findViewById(R.id.txtFnm);


final TextView txtLnm=(TextView)findViewById(R.id.txtLnm);

btn1.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {


// TODO Auto-generated method stub
try
{
if(txtFnm.getText().toString().trim().length() > 0 &&
txtLnm.getText().toString().trim().length() > 0)
{
mydb.execSQL("insert into tbl_stud(firstname, lastname) values
('"+txtFnm.getText()+"', '"+txtLnm.getText()+"' );");

Toast.makeText(getApplicationContext(),"Record Inserted
Successfully",Toast.LENGTH_SHORT).show();
}
else
{
txtFnm.setText("");
txtLnm.setText("");
Toast.makeText(getApplicationContext(), "Please fill all the field!",
Toast.LENGTH_SHORT).show();
}

}
catch(SQLiteException se)
{
Toast.makeText(getApplicationContext(),"Please fill all the
fields.",Toast.LENGTH_SHORT).show();
}
}
});

Site:http://theandroid.in
[Type text]

btn2.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {


// TODO Auto-generated method stub

Intent it=new Intent(getApplicationContext(),DeleteActivity.class);


startActivity(it);

}
});

btn3.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {


// TODO Auto-generated method stub
startActivity(new
Intent(getApplicationContext(),UpdateActivity.class));

}
});

}
}

UpdateAvtivity.java

package com.firstdb;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class UpdateActivity extends Activity implements View.OnClickListener{

TextView txtFnm;
TextView txtLnm;
EditText txtId;
SQLiteDatabase mydb;
Button btn;
Button btncan;

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.update);

Site:http://theandroid.in
[Type text]

mydb=openOrCreateDatabase("firstdb.db", SQLiteDatabase.OPEN_READWRITE,null);

txtId=(EditText)findViewById(R.id.txtId);
txtFnm=(TextView)findViewById(R.id.txtFnm);
txtLnm=(TextView)findViewById(R.id.txtLnm);
btn=(Button)findViewById(R.id.btnUpdate);
btncan=(Button)findViewById(R.id.btnCan);

btn.setText("Find");

txtFnm.setEnabled(false);
txtLnm.setEnabled(false);

btn.setOnClickListener(this);
btncan.setOnClickListener(this);

btncan.setWillNotDraw(false);
}

public void onClick(View v) {


// TODO Auto-generated method stub
if(v.getId()==btn.getId())
{
if(btn.getText().equals(new String("Find")))
{
Cursor cur=mydb.query("tbl_stud", new
String[]{"id","firstname","lastname"},"id='"+txtId.getText()+"'", null,null,null, null,null);

if(cur.getCount()>0)
{
Toast.makeText(getApplicationContext(), "Record Found! Enter new
Values.",Toast.LENGTH_LONG).show();

try
{
cur.moveToNext();
txtFnm.setEnabled(true);
txtLnm.setEnabled(true);
btn.setText("Update");

txtFnm.setText(cur.getString(1));
txtLnm.setText(cur.getString(2));

}
catch(Exception se)
{
Toast.makeText(getApplicationContext(),se.toString(),Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"Record not found.",
Toast.LENGTH_SHORT).show();
txtFnm.setEnabled(false);
txtLnm.setEnabled(false);
txtFnm.setText("");
txtLnm.setText("");

Site:http://theandroid.in
[Type text]

}
}
else if(btn.getText().equals(new String("Update")))
{
if(txtFnm.getText().toString().trim().length() > 0 &&
txtLnm.getText().toString().trim().length() > 0)
{
mydb.execSQL("update tbl_stud set
firstname='"+txtFnm.getText()+"',lastname='"+txtLnm.getText()+"' where id='"+txtId.getText()+"'");
Toast.makeText(getApplicationContext(),"Record Id
'"+txtId.getText()+"' Updated.", Toast.LENGTH_LONG).show();
btn.setText("Find");
txtFnm.setText("");
txtLnm.setText("");
txtFnm.setEnabled(false);
txtLnm.setEnabled(false);
txtId.setText("");
}
else
{
Toast.makeText(getApplicationContext(), "Please fill all the
fields.", Toast.LENGTH_SHORT).show();
}

}
}
else if(v.getId()==btncan.getId())
{
btn.setText("Find");
txtFnm.setText("");
txtLnm.setText("");
txtFnm.setEnabled(false);
txtLnm.setEnabled(false);
txtId.setText("");

}
}
}

DeleteActivity.java

package com.firstdb;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DeleteActivity extends Activity {


/** Called when the activity is first created. */

Site:http://theandroid.in
[Type text]

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.delactivity);

final SQLiteDatabase
mydb=openOrCreateDatabase("firstdb.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);

final TextView txtId=(TextView)findViewById(R.id.txtId);


Button btn1=(Button)findViewById(R.id.btnDelete);

btn1.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {


// TODO Auto-generated method stub

if (txtId.getText().toString().trim().length() > 0) {
try {
Cursor cur = mydb.query("tbl_stud",
new String[] { "id" }, "id='" + txtId.getText()
+ "'", null, null,
null, null, null);
if (cur.getCount() > 0) {
mydb.delete("tbl_stud", "id=?",
new String[] {
txtId.getText().toString() });
Toast.makeText(getApplicationContext(),
"Record removed
successfully.",

Toast.LENGTH_SHORT).show();
startActivity(new
Intent(getApplicationContext(),
InsertActivity.class));
} else {
Toast.makeText(getApplicationContext(),
"No such Record found.",
Toast.LENGTH_SHORT)
.show();
}
} catch (SQLiteException se) {
Toast.makeText(getApplicationContext(),
"Connection Problem.",
Toast.LENGTH_SHORT)
.show();
}
}
}
});

}
}

DisplayActivity.java

Site:http://theandroid.in
[Type text]

package com.firstdb;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TextView;

public class DisplayActivity extends Activity {

TextView tv;

SQLiteDatabase mydb;

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.display);
tv=(TextView)findViewById(R.id.tv1);
mydb=openOrCreateDatabase("firstdb.db", SQLiteDatabase.OPEN_READWRITE,null);
Cursor cur=mydb.query("tbl_stud", new String[]{"id","firstname","lastname"},null, null,null,null,
null,null);
printData(cur);

}
public void printData(Cursor c) {

StringBuffer str=new StringBuffer();


String rowResults=null;

str.append("\t\t\t*** Student Table Data *** \n" + " \n Results:" +

c.getCount() + "\n\n Columns: " + c.getColumnCount()+"\n");

// Print column names


String rowHeaders = "|| ";

for (int i = 0; i < c.getColumnCount(); i++) {


rowHeaders = rowHeaders.concat(c.getColumnName(i).toUpperCase() + " ||
");
}

str.append(" \n \t\t" + rowHeaders+"\n");


// Print records
c.moveToFirst();
while (c.isAfterLast() == false) {

str.append(rowResults = "\t ");

for (int i = 0; i < c.getColumnCount(); i++) {

rowResults = rowResults.concat(c.getString(i) + " \t\t\t ");

Site:http://theandroid.in
[Type text]

str.append("\nRow " + c.getPosition() + " : " + rowResults);

c.moveToNext();

}
tv.setText(str);
tv.setBackgroundColor(Color.WHITE);
tv.setTextColor(Color.DKGRAY);
}

Now everything is ready and before running your project make sure that
you an entry of new activity name in AndroidManifest.xml file. Open you
AndroidManifest.xml file and modify the code as below.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.firstdb"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".InsertActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="DeleteActivity"></activity>
<activity android:name="UpdateActivity"></activity>
<activity android:name="DisplayActivity"></activity>

</application>

</manifest>

Site:http://theandroid.in
[Type text]

Exercise : 19
Create an application to read file from the sdcard and display that file content to
the screen.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<RelativeLayout android:id="@+id/relativeLayout1"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/bgcolor">
<TextView android:id="@+id/textView1"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" android:text="Write Text In Below
TextBox"></TextView>
<EditText android:layout_width="wrap_content"
android:inputType="textMultiLine" android:layout_below="@+id/textView1"
android:layout_marginTop="26dp" android:layout_alignParentRight="true"
android:layout_alignParentLeft="true" android:id="@+id/txt"
android:layout_height="220dp">
<requestFocus></requestFocus>
</EditText>
<Button android:id="@+id/read" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="3.Read SD File"
android:layout_above="@+id/close"
android:layout_alignLeft="@+id/clear"></Button>

Site:http://theandroid.in
[Type text]

<Button android:id="@+id/clear" android:layout_width="wrap_content"


android:layout_height="wrap_content" android:text="2.Clear Screen"
android:layout_above="@+id/read"
android:layout_centerHorizontal="true"></Button>
<Button android:id="@+id/write" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="1.Write SD File"
android:layout_above="@+id/clear"
android:layout_alignLeft="@+id/clear"></Button>
<Button android:id="@+id/close" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="4.Close"
android:layout_alignParentBottom="true" android:layout_marginBottom="18dp"
android:layout_alignLeft="@+id/read"
android:layout_alignRight="@+id/read"></Button>
</RelativeLayout>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as NineteenActivity.java.Type the following code
respectively.

Right Click on package folder -> New -> Class


NineteenActivity.java:
package theandroid.in;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class NineteenActivity extends Activity


{
/** @author Y@@D */
EditText txtData;
Button btnWriteSDFile;
Button btnReadSDFile;
Button btnClearScreen;
Button btnClose;
public void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtData = (EditText) findViewById(R.id.txt);
btnWriteSDFile = (Button)findViewById(R.id.write);
btnWriteSDFile.setOnClickListener(new OnClickListener()

Site:http://theandroid.in
[Type text]

{
public void onClick(View V)
{
try
{
File myFile = new
File("/sdcard/mysdfile.txt");
myFile.createNewFile();
Toast.makeText(NineteenActivity.this,
"Created",1000);
FileOutputStream fOut = new
FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new
OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing
SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),
e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
btnReadSDFile = (Button) findViewById(R.id.read);
btnReadSDFile.setOnClickListener(new OnClickListener() {

public void onClick(View v)


{
// write on SD card file data in the text box
try
{
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new
InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),"Done reading SD
'mysdfile.txt'",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),
e.getMessage(),Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnReadSDFile

btnClearScreen = (Button) findViewById(R.id.clear);


btnClearScreen.setOnClickListener(new OnClickListener()
{

Site:http://theandroid.in
[Type text]

public void onClick(View v)


{
// clear text box
txtData.setText("");
}
}); // btnClearScreen

btnClose = (Button) findViewById(R.id.close);


btnClose.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// clear text box
finish();
}
}); // btnClose
}
}

*Step to create SDcard...

First goto command promt.

->Then gotofollowing directory.

C:\Android\android-sdk_r11-windows\android-sdk-windows\tools

-> Then type following command.

mksdcard 1024M sdcard.iso

->It will create sdcard.iso file in tools folder.

->Finally Now go to AVD mananger using eclipse and edit avd or create
new

at that time attach sdcard.iso file to create sdcard using browse option.

Site:http://theandroid.in
[Type text]

Exercise : 20
Create an application to draw line on the screen as user drag his finger.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

Site:http://theandroid.in
[Type text]

Now we are creating activities by right click on your package folder and create
classes and name them as TouchEventActivity.java.Type the following code
respectively.

Right Click on package folder -> New -> Class


TouchEventActivity.java:

package com.touchevent;

import android.app.Activity;

import android.os.Bundle;

public class TouchEventActivity extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(new ExploreTouchEvent(this,null));

ExploreTouchEvent.java:

package com.touchevent;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.Path;

import android.util.AttributeSet;

import android.view.MotionEvent;

import android.view.View;

Site:http://theandroid.in
[Type text]

public class ExploreTouchEvent extends View

private Paint paint = new Paint();

private Path path = new Path();

public ExploreTouchEvent(Context context, AttributeSet attrs)

super(context, attrs);

paint.setAntiAlias(true);

paint.setStrokeWidth(6f);

paint.setColor(Color.WHITE);

paint.setStyle(Paint.Style.STROKE);

paint.setStrokeJoin(Paint.Join.ROUND);

protected void onDraw(Canvas canvas)

canvas.drawColor(Color.MAGENTA);

canvas.drawPath(path, paint);

public boolean onTouchEvent(MotionEvent event)

float eventX = event.getX();

float eventY = event.getY();

switch (event.getAction())

case MotionEvent.ACTION_DOWN:

path.moveTo(eventX, eventY);

Site:http://theandroid.in
[Type text]

return true;

case MotionEvent.ACTION_MOVE:

path.lineTo(eventX, eventY);

break;

case MotionEvent.ACTION_UP:

// nothing to do

break;

default:

return false;

// Schedules a repaint.

invalidate();

return true;

Exercise : 21

Create an application to send message between two emulators.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Site:http://theandroid.in
[Type text]

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bgcolor">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter the phone number of recipient"
/>
<EditText
android:id="@+id/txtPhoneNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Message"
/>
<EditText

Site:http://theandroid.in
[Type text]

android:id="@+id/txtMessage"
android:layout_width="fill_parent"
android:layout_height="150px"
android:gravity="top"
/>
<Button
android:id="@+id/btnSendSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send SMS"
/>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as SendMessageActivity.java.Type the following
code respectively.

Right Click on package folder -> New -> Class


SendMessageActivity.java:
package com.readmessage;

import android.app.Activity;

import android.app.PendingIntent;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.Bundle;

import android.telephony.SmsManager;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

public class SendMessageActivity extends Activity {

Button btnSendSMS;

EditText txtPhoneNo;

Site:http://theandroid.in
[Type text]

EditText txtMessage;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

btnSendSMS = (Button) findViewById(R.id.btnSendSMS);

txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);

txtMessage = (EditText) findViewById(R.id.txtMessage);

btnSendSMS.setOnClickListener(new View.OnClickListener()

public void onClick(View v)

String phoneNo = txtPhoneNo.getText().toString();

String message = txtMessage.getText().toString();

if (phoneNo.length()>0 && message.length()>0)

sendSMS(phoneNo, message);

else

Toast.makeText(getBaseContext(),

"Please enter both phone number and message.",

Toast.LENGTH_SHORT).show();

});

private void sendSMS(String phoneNumber, String message)

Site:http://theandroid.in
[Type text]

String SENT = "SMS_SENT";

String DELIVERED = "SMS_DELIVERED";

PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,

new Intent(SENT), 0);

PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,

new Intent(DELIVERED), 0);

//---when the SMS has been sent---

registerReceiver(new BroadcastReceiver(){

@Override

public void onReceive(Context arg0, Intent arg1) {

switch (getResultCode())

case Activity.RESULT_OK:

Toast.makeText(getBaseContext(), "SMS sent",

Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_GENERIC_FAILURE:

Toast.makeText(getBaseContext(), "Generic failure",

Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_NO_SERVICE:

Toast.makeText(getBaseContext(), "No service",

Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_NULL_PDU:

Toast.makeText(getBaseContext(), "Null PDU",

Toast.LENGTH_SHORT).show();

Site:http://theandroid.in
[Type text]

break;

case SmsManager.RESULT_ERROR_RADIO_OFF:

Toast.makeText(getBaseContext(), "Radio off",

Toast.LENGTH_SHORT).show();

break;

}, new IntentFilter(SENT));

//---when the SMS has been delivered---

registerReceiver(new BroadcastReceiver(){

@Override

public void onReceive(Context arg0, Intent arg1) {

switch (getResultCode())

case Activity.RESULT_OK:

Toast.makeText(getBaseContext(), "SMS delivered",

Toast.LENGTH_SHORT).show();

break;

case Activity.RESULT_CANCELED:

Toast.makeText(getBaseContext(), "SMS not


delivered",

Toast.LENGTH_SHORT).show();

break;

}, new IntentFilter(DELIVERED));

SmsManager sms = SmsManager.getDefault();

sms.sendTextMessage(phoneNumber, null, message, sentPI,


deliveredPI);

Site:http://theandroid.in
[Type text]

Now we are creating activities by right click on your package folder and create
classes and name them as ReadMessageActivity.java. Type the following
code respectively.

Right Click on package folder -> New -> Class


ReadMessageActivity.java:

package com.readmessage;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.SmsMessage;

import android.widget.Toast;

public class ReadMessageActivity extends BroadcastReceiver {

/** Called when the activity is first created. */

@Override

public void onReceive(Context context, Intent intent)

//---get the SMS message passed in---

Bundle bundle = intent.getExtras();

SmsMessage[] msgs = null;

String str = "";

if (bundle != null)

//---retrieve the SMS message received---

Site:http://theandroid.in
[Type text]

Object[] pdus = (Object[]) bundle.get("pdus");

msgs = new SmsMessage[pdus.length];

for (int i=0; i<msgs.length; i++){

msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);

str += "SMS from " + msgs[i].getOriginatingAddress();

str += " :";

str += msgs[i].getMessageBody().toString();

str += "\n";

//---display the new SMS message---

Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

Step to Creat two emulator and send sms.

1)goto windows->Android SDK and AVD Mangaer.

2)creat two emulator and give the different name.

3)start emulator by clicking start button

3)now enter the emulator number to phone number and send it.

Note:- see the give OutPut Image..

Site:http://theandroid.in
[Type text]

Exercise : 22
Create an application to take picture using native application.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LinearLayout>

Site:http://theandroid.in
[Type text]

Now we are creating activities by right click on your package folder and create
classes and name them as TwentyTwoActivity.java. Type the following
code respectively.

Right Click on package folder -> New -> Class


TwentyTwoActivity.java:
package theandroid.in;

import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

public class TwentyTwoActivity extends Activity


{
/** @author Y@@D */
String path;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
path = Environment.getExternalStorageDirectory() + File.separator +
"make_machine_example.jpg";
File file = new File( path );
Uri outputFileUri = Uri.fromFile( file );

Intent intent = new


Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

startActivityForResult( intent, 0 );

}
}

Site:http://theandroid.in
[Type text]

Exercise : 23
Create an application to pick up any image from the native application gallery
and display it on the screen.

So let’s get started by creating a simple project by opening eclipse IDE.

Screen Shot:

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bgcolor">

<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/txtTitle"
android:layout_width="match_parent"></TextView>
<ImageView

Site:http://theandroid.in
[Type text]

android:src="@drawable/icon" android:id="@+id/myImg"
android:layout_width="match_parent"
android:layout_height="456dp"></ImageView>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as TwentythreeActivity.java. Type the following
code respectively.

Right Click on package folder -> New -> Class


TwentythreeActivity.java:
package theandroid.in;
import java.io.File;
import java.io.FileInputStream;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class TwentythreeActivity extends Activity


{
/** @author Y@@D **/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
try
{

String[] projection={Media.DISPLAY_NAME, Media.DATA,


Media.SIZE};
Cursor c=managedQuery(Media.EXTERNAL_CONTENT_URI, projection,
null, null, null);
ImageView ivImage=(ImageView)findViewById(R.id.myImg);
File file = null;
String imgName = null ;

if(c.getCount()>0)
{
while(c.moveToNext())
{
file=new File(c.getString(1)); //after
completing loop, it take last image from native Gallery to display.
imgName=c.getString(0);
}
c.close();
FileInputStream fis=new FileInputStream(file);
byte[] buffer=new byte[fis.available()];

Site:http://theandroid.in
[Type text]

fis.read(buffer);
Bitmap bm=BitmapFactory.decodeByteArray(buffer, 0,
buffer.length);

TextView
txtTitle=(TextView)findViewById(R.id.txtTitle);
txtTitle.setText(imgName.toString());
ivImage.setImageBitmap(bm);
}
}
catch(Exception e)
{
Toast.makeText(TwentythreeActivity.this, "Error: "+e,
Toast.LENGTH_LONG).show();
}
}
}

Step To store images on sdcard and scanning in to the emulator.

1)click on push on file onto the device button

2)now select the iamge an upload it

3)goto the "Dev Tools" on your emulator and click on "Media Scanner".

4)now check your image in "gallery"

5)run your program

Site:http://theandroid.in
[Type text]

Exercise : 24
Create an application to open any URL inside the application and clicking on
any link from that URl should not open Native browser but that URL should
open the same screen.

So let’s get started by creating a simple project by opening eclipse IDE.

Now open your main.xml under res -> layout folder and type the following
code.

main.xml :

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="ttp://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:padding="10px"
android:background="@color/bgcolor">

<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bgcolor"/>
</LinearLayout>

Now we are creating activities by right click on your package folder and create
classes and name them as TwentyFourActivity.java. Type the following
code respectively.

Right Click on package folder -> New -> Class

Site:http://theandroid.in
[Type text]

TwentyFourActivity.java:
package theandroid.in;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class TwentyFourActivity extends Activity


{ @Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.gtumcappt.blogspot.com");
webView.setWebViewClient(new HelloWebViewClient());
}
}

HelloWebViewClient.java:

package theandroid.in;

import android.webkit.WebView;
import android.webkit.WebViewClient;

public class HelloWebViewClient extends WebViewClient


{ @Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}

Site:http://theandroid.in
[Type text]

Site:http://theandroid.in

Você também pode gostar