Date post: | 17-Jul-2016 |
Category: |
Documents |
Upload: | rhsabbir007 |
View: | 13 times |
Download: | 1 times |
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
1
Android Development for Beginners
©2012 by Edureka.in, All rights reserved. No part of this document may be reproduced or
transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of Edureka.in, Incorporated.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
2
TABLE OF CONTENTS
CHAPTER 1: JAVA REVIEW ............................................................................... 5
1.1 Creating Basic Java Applications .................................................................................................. 6
1.2 Creating Applications in Packages .............................................................................................. 7
1.3 Java Variables ...................................................................................................................................... 8
1.4 Java Conditionals and Loops ....................................................................................................... 10
1.5 Java Arrays ......................................................................................................................................... 13
1.6 Java Array Lists ................................................................................................................................ 15
Chapter 1 Lab Exercise ......................................................................................................................... 18
CHAPTER 2: JAVA OBJECT ORIENTED CONCEPTS REVIEW ................................ 20
2.1 Creating a Java Class .................................................................................................................. 21
2.2 Improving the Java Class ......................................................................................................... 23
2.3 Using Inheritance ........................................................................................................................ 26
2.4 Understanding Interfaces ........................................................................................................ 31
2.5 The Static Context ....................................................................................................................... 37
Chapter 2 Lab Exercise ......................................................................................................................... 41
CHAPTER 3: CREATING YOUR FIRST ANDROID APPLICATION ........................... 43
3.1 The Hello World Application .................................................................................................. 44
3.2 Working with the Emulator..................................................................................................... 46
3.3 Strings ............................................................................................................................................. 51
3.4 Drawables ...................................................................................................................................... 54
3.5 Introducing the Manifest .......................................................................................................... 57
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
3
3.6 Understanding the Activity Lifecycle ................................................................................... 59
Chapter 3 Lab Exercise ......................................................................................................................... 61
CHAPTER 4: CREATING LISTENERS .................................................................. 62
4.1 Listeners Using an Inner Class ............................................................................................... 63
4.2 Listeners Using an Interface ................................................................................................... 65
4.3 Listeners By Variable Name .................................................................................................... 68
4.4 Long Clicks ..................................................................................................................................... 71
4.5 Keyboard Listeners .................................................................................................................... 75
Chapter 4 Lab Exercise ......................................................................................................................... 77
CHAPTER 5: UNDERSTANDING ANDROID VIEW CONTAINERS .......................... 79
5.1 Linear Layout ............................................................................................................................... 80
5.2 Relative Layout ............................................................................................................................ 83
5.3 Table Layout ................................................................................................................................. 86
5.4 List View ......................................................................................................................................... 89
Chapter 5 Lab Exercise ......................................................................................................................... 92
CHAPTER 6: ANDROID WIDGETS PART I .......................................................... 93
6.1 Custom Buttons ............................................................................................................................ 94
6.2 Toggle Buttons ............................................................................................................................. 96
6.3 Checkboxes and Radio Buttons .............................................................................................. 99
6.4 Spinners ........................................................................................................................................ 103
Chapter 6 Lab Exercise ....................................................................................................................... 106
CHAPTER 7: ANDROID WIDGETS PART II ....................................................... 108
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
4
7.1 Autocomplete Text Box ......................................................................................................... 109
7.2 Map View ...................................................................................................................................... 111
7.3 Web Views ................................................................................................................................... 113
7.4 Time and Date Pickers ............................................................................................................ 115
Chapter 7 Lab Exercise ....................................................................................................................... 119
CHAPTER 8: COMMUNICATING BETWEEN ACTIVITIES ................................... 120
8.1 Switching Activities .................................................................................................................. 121
8.2 Putting Extra ............................................................................................................................... 125
8.3 Using Shared Preferences ...................................................................................................... 129
Chapter 8 Lab Exercise ....................................................................................................................... 134
CHAPTER 9: STORING INFORMATION ON THE DEVICE ................................... 135
9.1 Internal Storage ......................................................................................................................... 136
9.2 External Storage ........................................................................................................................ 141
9.3 Web Communication and Storage ....................................................................................... 145
Chapter 9 Lab Exercise ....................................................................................................................... 148
CHAPTER 10: AUDIO AND VIDEO .................................................................. 149
10.1 Playing Audio with the MediaPlayer ............................................................................... 150
10.2 Playing Video with the MediaPlayer ............................................................................... 153
Chapter 10 Lab Exercise ..................................................................................................................... 155
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
5
Chapter 1: Java Review
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
6
1.1 Creating Basic Java Applications public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World from Java");
}
}
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
7
1.2 Creating Applications in Packages package edureka.in.androidcourse;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World from Java");
}
}
Notes _____________________________________________________________ _____________________________________________________________
_____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
8
1.3 Java Variables package edureka.in.androidcourse;
public class Variables
{
public static void main(String[] args)
{
// Variables
int age; //Variable Declaration
age= 37;
float gpa = 3.77f; //Delcaration and Initialization
double preciseNumner = 1.000005;
byte score = 12;
short tennisScore = 30;
long socialSecNumber = 650162727;
boolean isPlaying = true;
char letterGrade = 'A';
System.out.println("Our integer value is: " + age);
System.out.println("Our floating point value is: " +
gpa);
System.out.println("Out boolean value is: " + isPlaying);
/*
Aritmatic Operators
+, - , *, /
++ Increment Operator adds One
-- Decrement Operator subtracts One
% Modulus Operator
Combined Assignment Operators
+= Add (or concatenate) and then assign
-= Subtract then Assign
*= Multiply then Assign
/= Divide then Assign
*/
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
9
System.out.println("Next year I will be " + (++age));
System.out.println("17 % 3 = " + (17%3)); tennisScore += 10; //tennisScore = tennisScore+10;
System.out.println("Tennis Score= " + tennisScore);
}
}
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
10
1.4 Java Conditionals and Loops Conditionals.java package edureka.in.androidcourse;
public class Conditionals
{
public static void main(String[] args)
{
int age = 37;
boolean citizen = true;
if(age>=18 && citizen)
{
//True
System.out.println("You are eligible to vote.");
} else
{
//False
System.out.println("You are ineligible to vote.");
}
}
}
ComplexConditionals.java package edureka.in.androidcourse;
public class ComplexConditionals
{
public static void main(String[] args)
{
int age =60;
if(age<18)
{
System.out.println("You are still young.");
} else if(age<29)
{
System.out.println("These are the years you should be
having fun.");
} else if(age<39)
{
System.out.println("Time to get serious about your
career.");
} else if(age < 49)
{
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
11
System.out.println("These are your money-making
years.");
} else if(age <59)
{
System.out.println("I hope you are preparing for
retirement.");
} else
{
System.out.println("You are offically old.");
}
}
}
Switch.java package edureka.in.androidcourse;
public class Switch
{
public static void main(String[] args)
{
char grade = 'c';
switch(grade)
{
case 'A':
case 'a':
System.out.println("Outstanding Achievement.");
break;
case 'B':
case 'b':
System.out.println("Above Average Achievement");
break;
case 'C':
case 'c':
System.out.println("Average Achievement.");
break;
case 'D':
case 'd':
System.out.println("Low Passing Score.");
break;
case 'F':
case 'f':
System.out.println("Failing Grade.");
break;
default:
System.out.println("Grade not recognized");
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
12
}
}
Loops.java package edureka.in.androidcourse;
public class Loops
{
public static void main(String[] args)
{
/*
int x = 0;
while(x < 101)
{
System.out.println(x);
x++;
}
int y=300;
do
{
System.out.println(y);
y+=5;
}while(y < 251);
*/
for(int z=100; z > -1; z=z-5)
{
System.out.println(z);
}
}
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
13
1.5 Java Arrays package edureka.in.androidcourse;
public class Arrays
{
public static void main(String[] args)
{
int[] agesOfFamily;
agesOfFamily = new int[6];
agesOfFamily[0] = 37;
agesOfFamily[1] = 69;
agesOfFamily[2] = 65;
agesOfFamily[3] = 31;
agesOfFamily[4] = 4;
agesOfFamily[5] = 2;
System.out.println("My adorable nephew is " +
agesOfFamily[5] + " years old");
String[] familyMembers;
familyMembers = new String[5];
familyMembers[0] = "Mark";
familyMembers[1] = "Joan";
familyMembers[2] = "Rick";
familyMembers[3] = "Brett";
familyMembers[4] = "Rose";
System.out.println("My grandmother's name is " +
familyMembers[4]);
for(int i=0; i < familyMembers.length; i++)
{
System.out.println(familyMembers[i]);
}
}
}
Notes _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
14
_____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
15
1.6 Java Array Lists package edureka.in.androidcourse;
import java.util.*;
public class ArrayLists
{
public static void main(String[] args)
{
ArrayList airlines = new ArrayList();
System.out.println("Array list airline initial size: " +
airlines.size());
airlines.add("American");
airlines.add("Delta");
airlines.add("United");
airlines.add("US Airways");
airlines.add("jetBlue");
airlines.add("Southwest");
System.out.println("Array list airline initial size: " +
airlines.size());
System.out.println("Airlines in the list: " + airlines);
System.out.println("The first airline: " +
airlines.get(0));
System.out.println("The last airline: " +
airlines.get(5));
airlines.remove(3);
System.out.println("The third airlines is now: " +
airlines.get(3));
}
}
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
16
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
17
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
18
Chapter 1 Lab Exercise 1. Create a new Java class and create an ArrayList called
players that has the following members:
Joey
Thomas
Joan
Sarah
Freddie
Aaron
2. Create a second ArrayList called battingAverages. Populate the ArrayList with the
following values:
.333
.221
.401
.297
.116
.250
3. By accessing each element of both ArrayLists output each name and batting average in row. Place the
next name and batting average in the subsequent row.
4. Calculate and output the team average batting average.
5. Add the name “Horace” and the batting average .232 to the appropriate ArrayLists. (Use the appropriate
ArrayList method.) Re-output the names and batting
averages as instructed in step 3. Also recalculate
the team average. You should refactor the code at
this point so that the routine to output the
information and calculate the team average are is
not repeated. Instead, use function calls.
6. Sort the ArrayList by name. (You may need to investigate the methods associated with the
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
19
ArrayList class.) Note that now that you have done
this the batting averages no longer correspond to
the correct players. Look up the HashTable class in
the java documentation.
(http://docs.oracle.com/javase/1.4.2/docs/api/java/u
til/Hashtable.html) Use this documentation to
recreate the inital data as a HashTable.
7. Access each element pair in the HashTable and output the name and batting average to the console.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
20
Chapter 2: Java Object Oriented Concepts Review
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
21
2.1 Creating a Java Class Animal.java package edureka.in.android;
public class Animal_driver {
/**
* @param args
*/
public static void main(String[] args) {
Animal doggie = new Animal();
doggie.name = "Rover";
doggie.age = 3;
doggie.length = 36;
doggie.weight = 17;
doggie.breathe();
doggie.eat("Vittles");
doggie.sleep();
System.out.println("The animal's name is: " +
doggie.name);
System.out.println("The animal's age is: " +
doggie.age);
System.out.println("The animal's length is: " +
doggie.length);
}
}
Animal_driver.java package edureka.in.android;
public class Animal_driver {
/**
* @param args
*/
public static void main(String[] args) {
Animal doggie = new Animal();
doggie.name = "Rover";
doggie.age = 3;
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
22
doggie.length = 36;
doggie.weight = 17;
doggie.breathe();
doggie.eat("Vittles");
doggie.sleep();
System.out.println("The animal's name is: " +
doggie.name);
System.out.println("The animal's age is: " +
doggie.age);
System.out.println("The animal's length is: " +
doggie.length);
}
}
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
23
2.2 Improving the Java Class Animal.java package edureka.in.android;
public class Animal {
/*
* Private- Accessible only within the class
* Public- Accessible within the class and to other classes
* Protected- Accessible within the class and to children
of the class (subclassess)
*/
//Properties of Animal
//Known as "members"
private int age;
private int length;
private String name;
private int weight;
public Animal(int age, int length, String name, int weight)
{
this.age = age;
this.length = length;
this.name = name;
this.weight = weight;
}
public Animal()
{
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age>0){
this.age = age;
}
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
24
public int getLength() {
return length;
}
public void setLength(int length) {
if(length>0){
this.length = length;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
if(weight >0)
{
this.weight = weight;
}
}
//Methods
void eat(String food)
{
System.out.println("Animal is eating " + food);
}
void sleep()
{
System.out.println("Animal is sleeping");
}
void breathe()
{
System.out.println("Animal is breathing");
}
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
25
Animal_driver.java package edureka.in.android;
public class Animal_driver {
/**
* @param args
*/
public static void main(String[] args) {
Animal doggie = new Animal();
doggie.setName("Rover");
doggie.setAge(3);
doggie.setLength(36);
doggie.setWeight(17);
doggie.breathe();
doggie.eat("Vittles");
doggie.sleep();
System.out.println("The animal's name is: " +
doggie.getName());
System.out.println("The animal's age is: " +
doggie.getAge());
System.out.println("The animal's length is: " +
doggie.getLength());
Animal kittie = new Animal(1, 23, "Kitty", 5);
System.out.println("The second animal's name is " +
kittie.getName());
kittie.eat("shrimp");
}
}
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
26
2.3 Using Inheritance Animal.java package edureka.in.android;
public class Animal {
/*
* Private- Accessible only within the class
* Public- Accessible within the class and to other classes
* Protected- Accessible within the class and to children
of the class (subclassess)
*/
//Properties of Animal
//Known as "members"
private int age;
private int length;
private String name;
private int weight;
public Animal(int age, int length, String name, int weight)
{
this.age = age;
this.length = length;
this.name = name;
this.weight = weight;
}
public Animal()
{
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age>0){
this.age = age;
}
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
27
public int getLength() {
return length;
}
public void setLength(int length) {
if(length>0){
this.length = length;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
if(weight >0)
{
this.weight = weight;
}
}
//Methods
public void eat(String food)
{
System.out.println("Animal is eating " + food);
}
public void sleep()
{
System.out.println("Animal is sleeping");
}
public void breathe()
{
System.out.println("Animal is breathing");
}
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
28
Fish.java package edureka.in.android;
public class Fish extends Animal {
boolean scales;
public Fish(int age, int length, String name, int weight,
boolean scales)
{
super(age, length, name, weight);
this.scales = scales;
}
public Fish()
{
}
//New Method specific to the fish class
public void swim()
{
System.out.println("Fish is swimming");
}
//Overriding the method in the parent
public void breathe()
{
System.out.println("Fish is breathing through its
gills");
}
}
Animal_driver.java package edureka.in.android;
public class Animal_driver {
/**
* @param args
*/
public static void main(String[] args) {
Animal doggie = new Animal();
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
29
doggie.setName("Rover");
doggie.setAge(3);
doggie.setLength(36);
doggie.setWeight(17);
doggie.breathe();
doggie.eat("Vittles");
doggie.sleep();
System.out.println("The animal's name is: " +
doggie.getName());
System.out.println("The animal's age is: " +
doggie.getAge());
System.out.println("The animal's length is: " +
doggie.getLength());
Animal kittie = new Animal(1, 23, "Kitty", 5);
System.out.println("The second animal's name is " +
kittie.getName());
kittie.eat("shrimp");
Fish goldfish = new Fish(1, 2, "Goldie", 1, true);
System.out.println("The fish's name is: " +
goldfish.getName());
goldfish.setWeight(2);
System.out.println("The fish's weight is: " +
goldfish.getWeight());
}
}
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
30
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
31
2.4 Understanding Interfaces Animal.java package edureka.in.android;
public class Animal {
/*
* Private- Accessible only within the class
* Public- Accessible within the class and to other classes
* Protected- Accessible within the class and to children
of the class (subclassess)
*/
//Properties of Animal
//Known as "members"
private int age;
private int length;
private String name;
private int weight;
public Animal(int age, int length, String name, int weight)
{
this.age = age;
this.length = length;
this.name = name;
this.weight = weight;
}
public Animal()
{
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age>0){
this.age = age;
}
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
32
public int getLength() {
return length;
}
public void setLength(int length) {
if(length>0){
this.length = length;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
if(weight >0)
{
this.weight = weight;
}
}
//Methods
public void eat(String food)
{
System.out.println("Animal is eating " + food);
}
public void sleep()
{
System.out.println("Animal is sleeping");
}
public void breathe()
{
System.out.println("Animal is breathing");
}
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
33
Pray.java package edureka.in.android;
public interface Pray {
void getChased();
void getEaten();
}
Predator.java package edureka.in.android;
public interface predator {
void chasePray();
void eatPray();
}
Lion.java package edureka.in.android;
public class Lion extends Animal implements predator {
public Lion(int age, int length, String name, int weight) {
super(age, length, name, weight);
// TODO Auto-generated constructor stub
}
public Lion() {
// TODO Auto-generated constructor stub
}
@Override
public void chasePray() {
System.out.println("The Lion is chasing some pray");
}
@Override
public void eatPray() {
System.out.println("The Lion is eating it's pray");
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
34
public void roar(){
System.out.println("ROARRRR!");
}
}
Fish.java package edureka.in.android;
public class Fish extends Animal implements Pray {
boolean scales;
public Fish(int age, int length, String name, int weight,
boolean scales)
{
super(age, length, name, weight);
this.scales = scales;
}
public Fish()
{
}
//New Method specific to the fish class
public void swim()
{
System.out.println("Fish is swimming");
}
//Overriding the method in the parent
public void breathe()
{
System.out.println("Fish is breathing through its
gills");
}
@Override
public void getChased() {
System.out.println("Fish is being chased.");
}
@Override
public void getEaten() {
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
35
System.out.println("Fish is being eaten. Goodbye");
}
}
Animal_driver.java package edureka.in.android;
public class Animal_driver {
/**
* @param args
*/
public static void main(String[] args) {
Animal doggie = new Animal();
doggie.setName("Rover");
doggie.setAge(3);
doggie.setLength(36);
doggie.setWeight(17);
doggie.breathe();
doggie.eat("Vittles");
doggie.sleep();
System.out.println("The animal's name is: " +
doggie.getName());
System.out.println("The animal's age is: " +
doggie.getAge());
System.out.println("The animal's length is: " +
doggie.getLength());
Animal kittie = new Animal(1, 23, "Kitty", 5);
System.out.println("The second animal's name is " +
kittie.getName());
kittie.eat("shrimp");
Fish goldfish = new Fish(1, 2, "Goldie", 1, true);
System.out.println("The fish's name is: " +
goldfish.getName());
goldfish.setWeight(2);
System.out.println("The fish's weight is: " +
goldfish.getWeight());
goldfish.getChased();
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
36
Lion leo = new Lion(4, 240, "Leo The Lion", 420);
leo.eatPray();
}
}
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
37
2.5 The Static Context Animal.java package edureka.in.android;
public class Animal {
/*
* Private- Accessible only within the class
* Public- Accessible within the class and to other classes
* Protected- Accessible within the class and to children
of the class (subclassess)
*/
//Properties of Animal
//Known as "members"
//Instance Member
private int age;
private int length;
private String name;
private int weight;
public static int numAnimals;
public Animal(int age, int length, String name, int weight)
{
this.age = age;
this.length = length;
this.name = name;
this.weight = weight;
numAnimals++;
}
public Animal()
{
numAnimals++;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age>0){
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
38
this.age = age;
}
}
public int getLength() {
return length;
}
public void setLength(int length) {
if(length>0){
this.length = length;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
if(weight >0)
{
this.weight = weight;
}
}
//Methods
public void eat(String food)
{
System.out.println("Animal is eating " + food);
}
public void sleep()
{
System.out.println("Animal is sleeping");
}
public void breathe()
{
System.out.println("Animal is breathing");
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
39
}
Animal_driver.java package edureka.in.android;
public class Animal_driver {
/**
* @param args
*/
public static void main(String[] args) {
Animal doggie = new Animal();
doggie.setName("Rover");
doggie.setAge(3);
doggie.setLength(36);
doggie.setWeight(17);
doggie.breathe();
doggie.eat("Vittles");
doggie.sleep();
System.out.println("The animal's name is: " +
doggie.getName());
System.out.println("The animal's age is: " +
doggie.getAge());
System.out.println("The animal's length is: " +
doggie.getLength());
Animal kittie = new Animal(1, 23, "Kitty", 5);
System.out.println("The second animal's name is " +
kittie.getName());
kittie.eat("shrimp");
Fish goldfish = new Fish(1, 2, "Goldie", 1, true);
System.out.println("The fish's name is: " +
goldfish.getName());
goldfish.setWeight(2);
System.out.println("The fish's weight is: " +
goldfish.getWeight());
goldfish.getChased();
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
40
Lion leo = new Lion(4, 240, "Leo The Lion", 420);
leo.eatPray();
System.out.println("You produced " +
Animal.numAnimals + " animals");
}
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
41
Chapter 2 Lab Exercise
1. Create the design for an object oriented soda
machine. You may use any type of drawing, diagramming,
notation or recording system you’d like to create the
design-- However do NOT write any Java code. The soda
machine must have the following features:
It Must Accept Money
It Must Make Change if the user inserts more than the
price of a soda ($1.50 initially)
It Must Allow You (Administrator) Stock the Machine with
Soda
It Must Allow the User to Choose a Soda After Accepting
Money
It Must Indicate If a Choice is Out of stock
It Must Refund Money Upon Request After a User Has
Inserted Money
It Must Dispense the Soda After Money is Inserted and
Choice is Made
It Must Display The Types of Soda Available (Cola, Diet
Cola, Lemon-Lime, Diet Lemon-Lime and Root Beer.
It must allow you (Administrator) to
Your design document should represent the classes needed,
fields needed, and the methods of each class. You must
use at least two distinct classes for this exercise.
Once your design document is complete, you may want to
send it to the instructor for comments. This will be the
basis of you constructing the classes that you will code
in the following steps.
2. Construct the soda machine and related classes based
on your design document. If you need to change anything
about your design, first map out the change in your
design document and then make the change to your code.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
42
3. Create a driver class that will instantiate your soca
machine and related classes. It is through this class
that you should allow your soda machine in to interact
with the user and administrator.
Feel free to send your code to the instructor for
feedback or comments. You may also post your solution in
the forum to share with others.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
43
Chapter 3: Creating Your First Android Application
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
44
3.1 The Hello World Application HelloWorld.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
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>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
45
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
46
3.2 Working with the Emulator Emulator
DDMS View
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
47
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
48
Emulator Control: Telephony
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
49
Emulator Control: Geolocation
Logcat Monitoring
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
50
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
51
3.3 Strings L2pStringsActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class L2pStringsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btnPush =
(Button)findViewById(R.id.button1);
final TextView tv =
(TextView)findViewById(R.id.TextView);
btnPush.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tv.setText(R.string.thanks);
}
});
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/instruction"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
52
android:id="@+id/TextView"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/push_me" />
</LinearLayout>
strings.xml <?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World,
L2pStringsActivity!</string>
<string name="app_name">L2pStrings</string>
<string name="instruction">Please push the button for a big
surprise!</string>
<string name="push_me">Push Me!</string>
<string name="thanks">Thank you for pushing the
button</string>
</resources>
Notes
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
53
_____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
54
3.4 Drawables L2pDrawablesActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class L2pDrawablesActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button pressMe =
(Button)findViewById(R.id.buttonShowMark);
final ImageView iv =
(ImageView)findViewById(R.id.imageViewMark);
pressMe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
iv.setImageResource(R.drawable.mark);
}
});
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
55
android:text="Drawables" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/logo"
android:layout_gravity="center_horizontal"/>
<ImageView
android:id="@+id/imageViewMark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
<Button
android:id="@+id/buttonShowMark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="See Mark" />
</LinearLayout>
Notes _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
56
_____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
57
3.5 Introducing the Manifest Manifest GUI
Manifest.xml <?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.netcomlearning.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:icon="@drawable/ic_launcher"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
58
android:label="@string/app_name" >
<activity
android:name=".ShowLocationActivity"
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>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
59
3.6 Understanding the Activity Lifecycle L2pLifeCycleActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class L2pLifeCycleActivity extends Activity {
public static final String TAG = "LIFECYCLE";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "in onCreate()");
}
@Override
public void onStart()
{
super.onStart();
Log.i(TAG, "in onStart()");
}
@Override
public void onResume()
{
super.onResume();
Log.i(TAG, "in onResume()");
}
@Override
public void onRestart()
{
super.onRestart();
Log.i(TAG, "in onRestart()");
}
@Override
public void onPause()
{
Log.i(TAG, "in onPause()");
super.onPause();
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
60
}
@Override
public void onStop()
{
Log.i(TAG, "in onStop()");
super.onStop();
}
@Override
public void onDestroy()
{
Log.i(TAG, "in onDestroy()");
super.onDestroy();
}
}
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
61
Chapter 3 Lab Exercise
1. Create a new Android 2.3.3 Application as demonstrated in the video lecture.
2. Open main.xml in the layout folder and make sure you are in the Graphical Layout mode. Drag three
TextView controls on to the application
surface. They should appear one on top of another.
3. Make sure they are ID’ed as follows: @+id/TVName
@+id/TVEmail
@+id/TVPhone
4. Using the properties of the fields you have created populate them with your Name, Email and Phone
number. (If you wish you can create String
resources in the strings.xml and apply that strong
resource to the fields.)
5. Find an image of you and (if necessary) resize it so it appears no more than 100px by 100px. Make sure
it is a .png, .jpg or .gif and drag it in to the
Drawables folders. (Make sure the filename is all
lowercase or an error will occur)
6. Move back to the Graphical Layout mode with main.xml selected. Drag an ImageView object on to the
application surface. Give the ImageView the id
@+id/IVPictureOfMe.
7. Below the ImageView place a Button. Put the text “Show Picture” on the button.
8. Move to the Java code file and, as demonstrated in the video lecture, write the code to make local
references to the Button and image view. (You will
use the findViewById() method for this).
9. As demonstrated in the video lecture create a listener on the button reference and code it so the
image of you appears when the button is clicked.
10. If you haven’t already created an AVD (Android
Virtual Device) create one that is compatible with
version 2.3.3 of Android. Test your application and
find and correct any errors in your code.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
62
Chapter 4: Creating Listeners
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
63
4.1 Listeners Using an Inner Class L2pListenersActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class L2pListenersActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button inner =
(Button)findViewById(R.id.buttonInner);
final TextView tv =
(TextView)findViewById(R.id.textViewResult);
inner.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//What does the button do?
tv.setText("Thanks for pressing the inner
button. ID: " + v.getId());
}
});
}
}
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" >
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
64
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/buttonInner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inner Class" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
65
4.2 Listeners Using an Interface L2pListenersActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class L2pListenersActivity extends Activity implements
OnClickListener {
Button interfaceB;
Button interfaceB2;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button inner =
(Button)findViewById(R.id.buttonInner);
tv = (TextView)findViewById(R.id.textViewResult);
interfaceB = (Button)findViewById(R.id.buttonInterface);
interfaceB2 =
(Button)findViewById(R.id.buttonInterface2);
interfaceB.setOnClickListener(this);
interfaceB2.setOnClickListener(this);
inner.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//What does the button do?
tv.setText("Thanks for pressing the inner
button. ID: " + v.getId());
}
});
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
66
}
@Override
public void onClick(View v) {
int callerId = v.getId();
switch(callerId)
{
case R.id.buttonInterface:
tv.setText("Thanks for pressing the interface
button. ID: " + v.getId());
break;
case R.id.buttonInterface2:
tv.setText("Thanks for pressing interface
Button 2. ID: " + v.getId());
break;
default:
tv.setText("I don't know what you pushed!");
}
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/buttonInner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inner Class" />
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
67
<Button
android:id="@+id/buttonInterface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Interface" />
<Button
android:id="@+id/buttonInterface2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Interface 2" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
68
4.3 Listeners By Variable Name L2pListenersActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class L2pListenersActivity extends Activity implements
OnClickListener {
Button interfaceB;
Button interfaceB2;
Button variableB;
TextView tv;
private OnClickListener myOnClickListener = new
OnClickListener()
{
@Override
public void onClick(View v) {
tv.setText("Thanks for press the variable
button. ID: " + v.getId
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button inner =
(Button)findViewById(R.id.buttonInner);
tv = (TextView)findViewById(R.id.textViewResult);
interfaceB = (Button)findViewById(R.id.buttonInterface);
interfaceB2 =
(Button)findViewById(R.id.buttonInterface2);
variableB = (Button)findViewById(R.id.buttonVariable);
variableB.setOnClickListener(myOnClickListener);
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
69
interfaceB.setOnClickListener(this);
interfaceB2.setOnClickListener(this);
inner.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//What does the button do?
tv.setText("Thanks for pressing the inner
button. ID: " + v.getId());
}
});
}
@Override
public void onClick(View v) {
int callerId = v.getId();
switch(callerId)
{
case R.id.buttonInterface:
tv.setText("Thanks for pressing the interface
button. ID: " + v.getId());
break;
case R.id.buttonInterface2:
tv.setText("Thanks for pressing interface
Button 2. ID: " + v.getId());
break;
default:
tv.setText("I don't know what you pushed!");
}
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
70
android:text="@string/hello" />
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/buttonInner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inner Class" />
<Button
android:id="@+id/buttonInterface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Interface" />
<Button
android:id="@+id/buttonInterface2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Interface 2" />
<Button
android:id="@+id/buttonVariable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Variable" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
71
4.4 Long Clicks L2pListenersActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class L2pListenersActivity extends Activity implements
OnClickListener, OnLongClickListener {
Button interfaceB;
Button interfaceB2;
Button variableB;
TextView tv;
private OnClickListener myOnClickListener = new
OnClickListener()
{
@Override
public void onClick(View v) {
tv.setText("Thanks for press the variable
button. ID: " + v.getId());
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button inner =
(Button)findViewById(R.id.buttonInner);
tv = (TextView)findViewById(R.id.textViewResult);
interfaceB = (Button)findViewById(R.id.buttonInterface);
interfaceB2 =
(Button)findViewById(R.id.buttonInterface2);
variableB = (Button)findViewById(R.id.buttonVariable);
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
72
variableB.setOnClickListener(myOnClickListener);
interfaceB.setOnClickListener(this);
interfaceB2.setOnClickListener(this);
interfaceB.setOnLongClickListener(this);
interfaceB2.setOnLongClickListener(this);
inner.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(),
"Thanks for longclicking inner", Toast.LENGTH_SHORT).show();
return false;
}
});
inner.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//What does the button do?
tv.setText("Thanks for pressing the inner
button. ID: " + v.getId());
}
});
}
@Override
public void onClick(View v) {
int callerId = v.getId();
switch(callerId)
{
case R.id.buttonInterface:
tv.setText("Thanks for pressing the interface
button. ID: " + v.getId());
break;
case R.id.buttonInterface2:
tv.setText("Thanks for pressing interface
Button 2. ID: " + v.getId());
break;
default:
tv.setText("I don't know what you pushed!");
}
}
@Override
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
73
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), "Thanks for
long clicking the implements buttons",
Toast.LENGTH_SHORT).show();
return false;
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/buttonInner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inner Class" />
<Button
android:id="@+id/buttonInterface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Interface" />
<Button
android:id="@+id/buttonInterface2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Interface 2" />
<Button
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
74
android:id="@+id/buttonVariable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Variable" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
75
4.5 Keyboard Listeners L2pKeyboardListenersActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
public class L2pKeyboardListenersActivity extends Activity {
EditText userEntry;
TextView tvResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
userEntry =
(EditText)findViewById(R.id.editTextUserEntry);
tvResult= (TextView)findViewById(R.id.textResult);
userEntry.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode,
KeyEvent event) {
if(event.getAction() ==
KeyEvent.ACTION_DOWN)
{
if(keyCode ==
KeyEvent.KEYCODE_ENTER)
{
tvResult.setText(userEntry.getText());
}
}
return false;
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
76
}
});
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textResult"/>
<EditText
android:id="@+id/editTextUserEntry"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
77
Chapter 4 Lab Exercise
1. Create a new Android 2.3.3 Application as demonstrated in the video lecture.
2. Open the main.xml file and drag a TextView on to the application surface. Below the TextView drag three
buttons. Make the text label on the first button
say “Inner Class.” Label the second Text button
“Interface” and the third button “Variable.”
3. Switch to the Java code. Write the necessary code to give each button a local reference via
findElementById(). Give the text view a local
reference as well
4. On the button labeled “Inner Class” create a listener and call back function via an inner class
as demonstrated in the video lecture. When the
button is clicked, the words “Listener via Inner
Class” should appear in the TextView.
5. On the button labeled “Interface” create a listener and call back function via an interface as
demonstrated in the video lecture. When the button
is clicked, the words “Listener via Interface”
should appear in the TextView. Don’t forget to
“extend” your activity class with the appropriate
interface.
6. On the button labeled “Variable” create a listener and call back function via a variable as
demonstrated in the video lecture. When the button
is clicked, the words “Listener via Variable” should
appear in the TextView.
7. On each button implement a long click listener. Use the method that is labeled on the button to respond
to the long click. Make the messages in the Text
box “Long Click via inner class”, “Long Click via
interface”, and “Long click via variable.”
8. Below the third button add an EditText field in the main.xml file. Create a local reference in the Java
file.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
78
9. As demonstrated in lecture, create a listener on the EditText so that when the user types a character, it
appears the existing TextView clears and echos the
character(s) in the EditText.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
79
Chapter 5: Understanding Android View Containers
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
80
5.1 Linear Layout L2pLinearLayoutActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
public class L2pLinearLayoutActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
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"
android:gravity="center_vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="White"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="@color/White"
android:textColor="#000000"
android:gravity="center_horizontal"
android:layout_weight=".5"/>
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Green"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
81
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="@color/Green"
android:gravity="center_horizontal"
android:layout_weight=".16"/>
<TextView
android:id="@+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Yellow"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="@color/Yellow"
android:textColor="#000000"
android:gravity="center_horizontal"
android:layout_weight=".16"/>
<TextView
android:id="@+id/textView4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Red"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="@color/Red"
android:gravity="center_horizontal"
android:layout_weight=".16"/>
</LinearLayout>
colors.xml <?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="White">#FFFFFF</color>
<color name="Green">#00FF00</color>
<color name="Red">#FF0000</color>
<color name="Yellow">#FFFF00</color>
</resources>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
82
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
83
5.2 Relative Layout L2pRelativeLayoutActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
public class L2pRelativeLayoutActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
main.xml <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/wrapperLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="3dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="User Name:" />
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1" >
</EditText>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
84
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:text="Passoword" />
<EditText
android:id="@+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/textView2" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/editText2"
android:text="Submit" />
</RelativeLayout>
</LinearLayout>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
85
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
86
5.3 Table Layout L2pTableLayoutActivity package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
public class L2pTableLayoutActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cats of The World" />
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableRow>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cat1" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
87
android:src="@drawable/cat2" />
<ImageView
android:id="@+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cat1" />
<ImageView
android:id="@+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cat5" />
</TableRow>
<TableRow>
<ImageView
android:layout_column="1"
android:id="@+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cat4" />
<ImageView
android:layout_column="3"
android:id="@+id/imageView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cat6" />
</TableRow>
<TableRow>
<ImageView
android:id="@+id/imageView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cat7" />
<ImageView
android:id="@+id/imageView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cat8" />
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
88
<ImageView
android:id="@+id/imageView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cat9" />
</TableRow>
</TableLayout>
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
89
5.4 List View L2pListViewActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class L2pListViewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView bandList =
(ListView)findViewById(R.id.bandList);
final String[] bands = new String[] { "Journey",
"Reo Speedwagon",
"Heart",
"Styx",
"Foreigner",
"Kansas",
"Cheap Trick",
"Kiss"
};
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
bands);
bandList.setAdapter(adapter);
bandList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View
view, int position,
long id) {
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
90
Toast.makeText(getApplicationContext(),
bands[position], Toast.LENGTH_SHORT).show();
}
});
}
}
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" >
<ListView
android:id="@+id/bandList"
android:layout_width="match_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Notes
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
91
_____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
92
Chapter 5 Lab Exercise
1. Create a new Android 2.3.3 Application as demonstrated in the video lecture.
2. As demonstrated in the video lecture add a ListView to the interface and make a local reference in the
Java code.
3. Create a String array called months of the year and populate with the names of the months.
4. Create an ArrayAdapter object called adapter that uses the simple_list_item_I layout and uses your
months array as a data source.
5. Associate the adapter with your ListView reference as demonstrated in the video lecture.
6. Implement a click listener on the ListView so that a Toast appears with each click indicating the name of
the month clicked.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
93
Chapter 6: Android Widgets Part I
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
94
6.1 Custom Buttons L2pCustomButton.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class L2pCustomButtonActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"You pressed the custom button!", Toast.LENGTH_SHORT).show();
}
});
}
}
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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_button"/>
</LinearLayout>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
95
custom_button.xml <?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable ="@drawable/button_one"
android:state_pressed="true" />
<item android:drawable = "@drawable/button_two" />
</selector>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
96
6.2 Toggle Buttons L2pToggleButtonsActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class L2pToggleButtonsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ToggleButton toggleOne =
(ToggleButton)findViewById(R.id.toggleButtonEngineOne);
final ToggleButton toggleTwo =
(ToggleButton)findViewById(R.id.toggleButtonEngineTwo);
final Button statusButton =
(Button)findViewById(R.id.buttonCheckEngineStatus);
statusButton.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
if(toggleOne.isChecked() &&
toggleTwo.isChecked())
{
Toast.makeText(getApplicationContext(), "Both Engines are
running", Toast.LENGTH_SHORT).show();
} else
{
if(toggleOne.isChecked())
{
Toast.makeText(getApplicationContext(), "Engine One is
running", Toast.LENGTH_SHORT).show();
} else
{
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
97
if(toggleTwo.isChecked())
{
Toast.makeText(getApplicationContext(), "Engine Two is
running", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(getApplicationContext(), "Neither engine is
running", Toast.LENGTH_SHORT).show();
}
}
}
}
});
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start Your Engines!" />
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ToggleButton
android:id="@+id/toggleButtonEngineOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
<ToggleButton
android:id="@+id/toggleButtonEngineTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
98
</LinearLayout>
<Button
android:id="@+id/buttonCheckEngineStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Engine Status" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
99
6.3 Checkboxes and Radio Buttons L2pCheckAndRadioActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.Toast;
public class L2pCheckAndRadioActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final CheckBox chkApt =
(CheckBox)findViewById(R.id.checkBox1);
final CheckBox chkSalad =
(CheckBox)findViewById(R.id.checkBox2);
final CheckBox chkEntree =
(CheckBox)findViewById(R.id.checkBox3);
final CheckBox chkDessert=
(CheckBox)findViewById(R.id.checkBox4);
final RadioButton radioRare =
(RadioButton)findViewById(R.id.radioButtonRare);
final RadioButton radioMedium =
(RadioButton)findViewById(R.id.radioMedium);
final RadioButton radioWell =
(RadioButton)findViewById(R.id.radioButtonWell);
final Button btnPlaceOrder =
(Button)findViewById(R.id.button1);
btnPlaceOrder.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
String order ="";
if(chkApt.isChecked())
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
100
{
order += chkApt.getText();
}
if(chkSalad.isChecked())
{
order+= chkSalad.getText();
}
if(chkEntree.isChecked())
{
order += chkEntree.getText();
}
if(chkDessert.isChecked())
{
order += chkDessert.getText();
}
if(radioRare.isChecked())
{
order += " " + radioRare.getText();
} else if(radioMedium.isChecked())
{
order += " " +
radioMedium.getText();
} else
{
order += " " + radioWell.getText();
}
Toast.makeText(getApplicationContext(),
order, Toast.LENGTH_SHORT).show();
}
});
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
101
android:text="Please check all that apply" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Appetizer" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Salad" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Entree" />
<CheckBox
android:id="@+id/checkBox4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dessert" />
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radioButtonRare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rare" />
<RadioButton
android:id="@+id/radioMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium" />
<RadioButton
android:id="@+id/radioButtonWell"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Well Done" />
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
102
</RadioGroup>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Place Order" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
103
6.4 Spinners L2pSpinnerActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class L2pSpinnerActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] cities = { "New York",
"Chicago",
"Denver",
"Las Vegas",
"Detroit",
"Hartford",
"Los Angeles",
"Paris"
};
Spinner citySpinner =
(Spinner)findViewById(R.id.spinnerCities);
ArrayAdapter<String> as = new
ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_dropdown_item, cities);
citySpinner.setAdapter(as);
citySpinner.setOnItemSelectedListener(new
OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
104
parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
cities[position], Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?>
arg0) {
// TODO Auto-generated method stub
}
});
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Spinner
android:id="@+id/spinnerCities"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
105
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
106
Chapter 6 Lab Exercise
1. Create a new Android 2.3.3 Application as demonstrated in the video lecture.
2. Download and import the supplied starter project into Eclipse. You may do so by clicking the File
Menu and Import. Choose from the General Folder
either Existing Projects Into WorkSpace (for
unzipped files) or Archive Files (for zipped
files). Select either the root directory or archive
file from the next screen as appropriate and import
the project.
3. Open your main.xml and notice that a layout has already been provided for you:
4. Add a button below the spinner that has the text
label “Report.”
5. Change the id properties of all of the widgets so that they are more specific.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
107
6. Create the necessary Array and Array adapter objects to populate the spinner with the names of your five
favorite bands or artists.
7. Place a listener on the button you added. When the button is clicked a “report” is created in a
Toast. The report should report the status of each
of the widgets when the user pressed the
button. For example “Fun Button: On, Things I Like
To Do: Eat, Be Merry, Gender: Male, Band:
Journey.” (You may have to add additional code to
make this work smoothly.)
8. Compile and test on your emulator. Debug until all is working correctly. Make sure you test each
widget thoroughly.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
108
Chapter 7: Android Widgets Part II
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
109
7.1 Autocomplete Text Box L2pAutoCompleteTextViewActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class L2pAutoCompleteTextViewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AutoCompleteTextView acStates =
(AutoCompleteTextView)findViewById(R.id.autoCompleteStates);
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line , States.states);
acStates.setAdapter(adapter);
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter Your State" />
<AutoCompleteTextView
android:id="@+id/autoCompleteStates"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
110
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<requestFocus />
</AutoCompleteTextView>
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
111
7.2 Map View L2pMapsActivity.java package edureka.in.android;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.app.Activity;
import android.os.Bundle;
public class L2pMapsActivity extends MapActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView map = (MapView)findViewById(R.id.mapview);
map.setBuiltInZoomControls(true);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
main.xml <?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey ="0ckU7Ceq-V9UGSl1-zeLDY85oMxM8bE4Cy2Fukw"
/>
Notes _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
112
_____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
113
7.3 Web Views L2pWebViewActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class L2pWebViewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String content = "<html lang='en'><head><title>HTML
Displayed on Android</title></head><body><h1>Edureka.in</h1><img
src='http://www.edureka.in/wp-
content/themes/learntoprogrametv102/images/learnto.png' /><p>Your
Android device can display HTML code in the WebView
control.</p></body></html>";
WebView view = new WebView(this);
setContentView(view);
//view.loadUrl("http://www.edureka.in");
view.loadData(content, "text/html", null);
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
114
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
115
7.4 Time and Date Pickers L2pDateAndTimeActivity.java package edureka.in.android;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class L2pDateAndTimeActivity extends Activity {
static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID = 1;
TextView tvDateDisplay;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button dateClick =
(Button)findViewById(R.id.buttonSetDate);
tvDateDisplay =
(TextView)findViewById(R.id.textViewDateDisplay);
Button timeClick =
(Button)findViewById(R.id.buttonSetTime);
timeClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
116
dateClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id)
{
if(id == 0)
{
return new DatePickerDialog(this, dateCallBack, 1990,
0, 1);
}
if(id==1)
{
return new TimePickerDialog(this, timeCallBack,12,
00, false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timeCallBack = new
TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int
minute) {
String timeString = hourOfDay + ":" + minute;
tvDateDisplay.setText(timeString);
}
};
private DatePickerDialog.OnDateSetListener dateCallBack = new
DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int
monthOfYear,
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
117
int dayOfMonth) {
String dateString = (monthOfYear +1) + "/" +
dayOfMonth + "/" + year;
tvDateDisplay.setText(dateString);
}
};
}
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" >
<TextView
android:id="@+id/textViewDateDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Your Birthdate"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/buttonSetDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Birthday" />
<Button
android:id="@+id/buttonSetTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set the Time" />
</LinearLayout>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
118
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
119
Chapter 7 Lab Exercise 1. Create a new Android 2.3.3 Application as
demonstrated in the lecture.
2. Create an autocomplete box, as demonstrated in
lecture,
that is designed to capture the name of a state. You
may use the list of states for your array at: http://
state.1keydata.com/.
3. Below the autocomplete text box drag a date picker
on to
the user interface. Below the date picker place a
button.
4. Below the button create a TextView object.
5. Write Java code so that when the button is clicked
the
TextView will display the name of the state displayed
in
the autocomplete box and the date indicated on the
date
picker object.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
120
Chapter 8: Communicating Between Activities
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
121
8.1 Switching Activities L2pSwitchingActivitiesActivity.java package edureka.in.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class L2pSwitchingActivitiesActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.btnSwitch);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new
Intent(getApplicationContext(), SecondActivity.class);
startActivity(myIntent);
}
});
}
}
SecondActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
122
// TODO Auto-generated method stub
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/btnSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change To Second Activity" />
</LinearLayout>
second.xml
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
123
<?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:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the Second Activity"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
124
_____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
125
8.2 Putting Extra L2pPutExtraActivity.java package edureka.in.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class L2pPutExtraActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText et =
(EditText)findViewById(R.id.etDogAge);
Button btn = (Button)findViewById(R.id.btnCalculate);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int dogAge =
Integer.parseInt(et.getText().toString());
Intent myIntent = new
Intent(getApplicationContext(), dogAgeActivity.class);
myIntent.putExtra("dogsage", dogAge);
startActivity(myIntent);
}
});
}
}
dogAgeActivity.java package edureka.in.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
126
public class dogAgeActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dogageactivity);
Bundle extras = getIntent().getExtras();
int dogAge = extras.getInt("dogsage");
TextView tv = (TextView)findViewById(R.id.tvResult);
dogAge = dogAge * 7;
tv.setText("In dog years, your dog is: " + dogAge);
// TODO Auto-generated method stub
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/query" />
<EditText
android:id="@+id/etDogAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
127
android:text="Age in Dog Years"
android:layout_gravity="right"/>
</LinearLayout>
dogageactivity.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:orientation="vertical" >
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
128
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
129
8.3 Using Shared Preferences L2pSharedPreferencesActivity.java package edureka.in.android;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class L2pSharedPreferencesActivity extends Activity {
public static final String PREFS_NAME =
"MyPreferencesFile";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText name =
(EditText)findViewById(R.id.editText1);
final EditText email =
(EditText)findViewById(R.id.editText2);
Button btn =
(Button)findViewById(R.id.btnSavePreferences);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor =
settings.edit();
editor.putString("name",
name.getText().toString());
editor.putString("email",
email.getText().toString());
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
130
editor.commit();
Intent intent = new
Intent(getApplicationContext(), second.class);
startActivity(intent);
}
});
}
}
second.java package edureka.in.android;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class second extends Activity {
public static final String PREFS_NAME =
"MyPreferencesFile";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView tvName =
(TextView)findViewById(R.id.textViewName);
TextView tvEmail =
(TextView)findViewById(R.id.textViewEmail);
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
tvName.setText(settings.getString("name", "Eddie"));
tvEmail.setText(settings.getString("email",
"[email protected]"));
// TODO Auto-generated method stub
}
}
main.xml
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
131
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Name" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email Address" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnSavePreferences"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Preferences" />
</LinearLayout>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
132
second.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:orientation="vertical" >
<TextView
android:id="@+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textViewEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
133
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
134
Chapter 8 Lab Exercise
1. Create a new Android 2.3.3 Application as demonstrated in the video lecture.
2. Create a UI where the user can enter their first name, last name and email address in three EditText
controls.
3. Place a button at the bottom of the UI labeled Next. 4. Write Java code so that when the button is pressed
the first and last name and email address are passed
to a second activity using putExtra().
5. Create a second activity, with a separate xml file for the layout which displays the first and last
name and email address entered in activity one.
6. Place another next button at the bottom of the activity two interface. Code the callback function
for the button so that the information passed from
Activity one is stored in a SharedPreferences Object
and passed to the third activity.
7. Create a third activity so that the SharedPrefences object is retrieved and the information is displayed
yet again.
8. Place a button that returns the user to the original activity and allows them to fill out first name,
last name and email address again.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
135
Chapter 9: Storing Information on the Device
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
136
9.1 Internal Storage L2pInternalStorageActivity.java package edureka.in.android;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class L2pInternalStorageActivity extends Activity {
/** Called when the activity is first created. */
TextView tvName;
TextView tvNumber;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText etName =
(EditText)findViewById(R.id.etUserName);
final EditText etNumber =
(EditText)findViewById(R.id.editText2);
final Button btnSave =
(Button)findViewById(R.id.btnSave);
tvName = (TextView)findViewById(R.id.tvUserName);
tvNumber = (TextView)findViewById(R.id.tvUserNumber);
readTheFile();
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
137
//Get info out of text boxes
String name = etName.getText().toString();
String number = etNumber.getText().toString();
String eol =
System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new
OutputStreamWriter(openFileOutput("userInformation",
MODE_WORLD_WRITEABLE)));
writer.write(name + eol);
writer.write(number + eol);
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private void readTheFile() {
String eol = System.getProperty("line.separator");
BufferedReader reader = null;
try {
reader = new BufferedReader(new
InputStreamReader(openFileInput("userInformation")));
String line;
int counter =0;
while((line = reader.readLine())!=null)
{
if(counter==0)
{
tvName.setText(line);
counter++;
} else
{
tvNumber.setText(line);
}
}
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
138
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:" />
<EditText
android:id="@+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone Number:" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress" />
<Button
android:id="@+id/btnSave"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
139
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Information" />
<TextView
android:id="@+id/tvUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/tvUserNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
140
_____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
141
9.2 External Storage L2pExternalStorgageActivity.java package edureka.in.android;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class L2pExternalStorageActivity extends Activity {
/** Called when the activity is first created. */
TextView tvName;
TextView tvNumber;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText etName =
(EditText)findViewById(R.id.etUserName);
final EditText etNumber =
(EditText)findViewById(R.id.editText2);
final Button btnSave =
(Button)findViewById(R.id.btnSave);
tvName = (TextView)findViewById(R.id.tvUserName);
tvNumber = (TextView)findViewById(R.id.tvUserNumber);
readTheFile();
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
142
public void onClick(View v) {
//Get info out of text boxes
String name = etName.getText().toString();
String number = etNumber.getText().toString();
String eol =
System.getProperty("line.separator");
File information =
Environment.getExternalStorageDirectory();
if(information.canWrite())
{
File userInfoFile = new File(information,
"userInfo.txt");
try {
FileWriter filewriter =new
FileWriter(userInfoFile);
BufferedWriter out = new
BufferedWriter(filewriter);
out.write(name + eol);
out.write(number + eol);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
private void readTheFile() {
String eol = System.getProperty("line.separator");
File directory =
Environment.getExternalStorageDirectory();
File file = new File(directory + "/userInfo.txt");
if(!file.exists())
{
throw new RuntimeException("File Not Found");
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new
FileReader(file));
String line;
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
143
int counter =0;
while((line = reader.readLine()) != null)
{
if(counter==0)
{
tvName.setText(line);
counter++;
}
else
{
tvNumber.setText(line);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:" />
<EditText
android:id="@+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
144
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone Number:" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress" />
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Information" />
<TextView
android:id="@+id/tvUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/tvUserNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
145
9.3 Web Communication and Storage L2pSimpleWebServiceActivity.java package edureka.in.android;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
public class L2pSimpleWebServiceActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btnGetScores =
(Button)findViewById(R.id.btnGetScores);
final WebView displayScores =
(WebView)findViewById(R.id.wvScores);
btnGetScores.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
try {
URL myURL = new
URL("http://www.edureka.in/baseball.php");
URLConnection ucon =
myURL.openConnection();
InputStream is =
ucon.getInputStream();
BufferedInputStream bis = new
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
146
BufferedInputStream(is);
ByteArrayBuffer baf = new
ByteArrayBuffer(50);
int current =0;
while((current = bis.read()) != -1)
{
baf.append((byte)current);
}
String myString = new
String(baf.toByteArray());
displayScores.loadData(myString,
"text/html", null);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fake Baseball Scores" />
<WebView
android:id="@+id/wvScores"
android:layout_width="match_parent"
android:layout_height="305dp" />
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
147
<Button
android:id="@+id/btnGetScores"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Scores" />
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
148
Chapter 9 Lab Exercise
1. Create a new Android 2.3.3 Application as demonstrated in the video lecture.
2. Create a user interface that contains two EditTexts for the user to enter their first and last
name. Create a custom spinner in which they can
indicate which model of car they drive. (You can
populate the spinner with as many car makes as you’d
like).
3. Create two buttons below the spinner-- the first button should be labeled “internal” and the second
button labeled “external”
4. Code the buttons so that the information entered by the user is saved to internal or external storage as
appropriate.
5. Test and in DDMS mode download the files stored and insure they look correct in a text editor.
6. Create a second activity that loads the data from external storage and displays it in three separate
TextView. Test this activity as well.
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
149
Chapter 10: Audio and Video
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
150
10.1 Playing Audio with the MediaPlayer package edureka.in.android;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class L2pAudioPlayerActivity extends Activity implements
OnClickListener {
/** Called when the activity is first created. */
MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button play = (Button)findViewById(R.id.buttonPlay);
Button pause = (Button)findViewById(R.id.buttonPause);
Button stop = (Button)findViewById(R.id.buttonStop);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.buttonPlay:
mp = MediaPlayer.create(this, R.raw.journey);
mp.start();
break;
case R.id.buttonPause:
mp.pause();
break;
case R.id.buttonStop:
mp.stop();
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
151
}
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/buttonPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play" />
<Button
android:id="@+id/buttonStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop" />
<Button
android:id="@+id/buttonPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause" />
</LinearLayout>
</LinearLayout>
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
152
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
153
10.2 Playing Video with the MediaPlayer L2pVideoViewActivity.java package edureka.in.android;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
public class L2pVideoViewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
VideoView vv = (VideoView)findViewById(R.id.vv);
Uri path =
Uri.parse("android.resource://edureka.in.android/" +
R.raw.america);
vv.setVideoURI(path);
vv.setMediaController(new MediaController(this));
vv.requestFocus();
vv.start();
}
}
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Watch a Video" />
<VideoView
android:id = "@+id/vv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
154
/>
</LinearLayout>
Notes _____________________________________________________________ _____________________________________________________________ _____________________________________________________________ _____________________________________________________________
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
155
Chapter 10 Lab Exercise
1. Create a new Android 2.3.3 Application as demonstrated in the video lecture.
2. Write Javascript code to play your favorite song using MediaPlayer.
3. Test the code in your emulator, sit back and enjoy. 4. Reward yourself with your favorite treat and
relax: You have completed the
course. Congratulations!