Android Development for Beginners

Transcription

Android Development for Beginners
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
1
Android Development for Beginners
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
2
Android Development for Beginners
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
3
Android Development for Beginners
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
4
Android Development for Beginners
Chapter 1: Java Review
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
5
Android Development for Beginners
1.1 Creating Basic Java Applications
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World from Java");
}
}
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
6
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
7
Android Development for Beginners
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
*/
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
8
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
9
Android Development for Beginners
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)
{
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
10
Android Development for Beginners
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");
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
11
Android Development for Beginners
}
}
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);
}
}
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
12
Android Development for Beginners
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]
agesOfFamily[1]
agesOfFamily[2]
agesOfFamily[3]
agesOfFamily[4]
agesOfFamily[5]
=
=
=
=
=
=
37;
69;
65;
31;
4;
2;
System.out.println("My adorable nephew is " +
agesOfFamily[5] + " years old");
String[] familyMembers;
familyMembers = new String[5];
familyMembers[0]
familyMembers[1]
familyMembers[2]
familyMembers[3]
familyMembers[4]
=
=
=
=
=
"Mark";
"Joan";
"Rick";
"Brett";
"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
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
13
Android Development for Beginners
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
14
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
15
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
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
18
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
19
Android Development for Beginners
Chapter 2: Java Object Oriented Concepts Review
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
20
Android Development for Beginners
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;
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
21
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
22
Android Development for Beginners
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;
}
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
23
Android Development for Beginners
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");
}
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
24
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
25
Android Development for Beginners
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;
}
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
26
Android Development for Beginners
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");
}
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
27
Android Development for Beginners
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();
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
28
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
29
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
30
Android Development for Beginners
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;
}
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
31
Android Development for Beginners
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");
}
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
32
Android Development for Beginners
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");
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
33
Android Development for Beginners
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() {
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
34
Android Development for Beginners
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();
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
35
Android Development for Beginners
Lion leo = new Lion(4, 240, "Leo The Lion", 420);
leo.eatPray();
}
}
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
36
Android Development for Beginners
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){
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
37
Android Development for Beginners
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");
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
38
Android Development for Beginners
}
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();
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
39
Android Development for Beginners
Lion leo = new Lion(4, 240, "Leo The Lion", 420);
leo.eatPray();
System.out.println("You produced " +
Animal.numAnimals + " animals");
}
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
40
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
41
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
42
Android Development for Beginners
Chapter 3: Creating Your First Android Application
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
43
Android Development for Beginners
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
44
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
45
Android Development for Beginners
3.2
Working with the Emulator
Emulator
DDMS View
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
46
Android Development for Beginners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
47
Android Development for Beginners
Emulator Control: Telephony
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
48
Android Development for Beginners
Emulator Control: Geolocation
Logcat Monitoring
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
49
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
50
Android Development for Beginners
3.3
Strings
L2pStringsActivity.java
package edureka.in.android;
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.Button;
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
51
Android Development for Beginners
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
52
Android Development for Beginners
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
53
Android Development for Beginners
3.4
Drawables
L2pDrawablesActivity.java
package edureka.in.android;
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.Button;
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
54
Android Development for Beginners
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
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
55
Android Development for Beginners
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
56
Android Development for Beginners
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
57
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
58
Android Development for Beginners
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();
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
59
Android Development for Beginners
}
@Override
public void onStop()
{
Log.i(TAG, "in onStop()");
super.onStop();
}
@Override
public void onDestroy()
{
Log.i(TAG, "in onDestroy()");
super.onDestroy();
}
}
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
60
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
61
Android Development for Beginners
Chapter 4: Creating Listeners
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
62
Android Development for Beginners
4.1
Listeners Using an Inner Class
L2pListenersActivity.java
package edureka.in.android;
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
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" >
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
63
Android Development for Beginners
<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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
64
Android Development for Beginners
4.2
Listeners Using an Interface
L2pListenersActivity.java
package edureka.in.android;
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
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());
}
});
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
65
Android Development for Beginners
}
@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" />
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
66
Android Development for Beginners
<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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
67
Android Development for Beginners
4.3
Listeners By Variable Name
L2pListenersActivity.java
package edureka.in.android;
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
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);
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
68
Android Development for Beginners
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
69
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
70
Android Development for Beginners
4.4
Long Clicks
L2pListenersActivity.java
package edureka.in.android;
import
import
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.view.View.OnLongClickListener;
android.widget.Button;
android.widget.TextView;
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);
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
71
Android Development for Beginners
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
72
Android Development for Beginners
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
73
Android Development for Beginners
android:id="@+id/buttonVariable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Variable" />
</LinearLayout>
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
74
Android Development for Beginners
4.5
Keyboard Listeners
L2pKeyboardListenersActivity.java
package edureka.in.android;
import
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.KeyEvent;
android.view.View;
android.view.View.OnKeyListener;
android.widget.EditText;
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;
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
75
Android Development for Beginners
}
});
}
}
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
76
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
77
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
78
Android Development for Beginners
Chapter 5: Understanding Android View Containers
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
79
Android Development for Beginners
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
80
Android Development for Beginners
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
81
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
82
Android Development for Beginners
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
83
Android Development for Beginners
<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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
84
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
85
Android Development for Beginners
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
86
Android Development for Beginners
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" />
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
87
Android Development for Beginners
<ImageView
android:id="@+id/imageView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cat9" />
</TableRow>
</TableLayout>
</LinearLayout>
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
88
Android Development for Beginners
5.4
List View
L2pListViewActivity.java
package edureka.in.android;
import
import
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.AdapterView;
android.widget.AdapterView.OnItemClickListener;
android.widget.ArrayAdapter;
android.widget.ListView;
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) {
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
89
Android Development for Beginners
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
90
Android Development for Beginners
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
91
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
92
Android Development for Beginners
Chapter 6: Android Widgets Part I
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
93
Android Development for Beginners
6.1
Custom Buttons
L2pCustomButton.java
package edureka.in.android;
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.Button;
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
94
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
95
Android Development for Beginners
6.2
Toggle Buttons
L2pToggleButtonsActivity.java
package edureka.in.android;
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.Toast;
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
{
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
96
Android Development for Beginners
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" />
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
97
Android Development for Beginners
</LinearLayout>
<Button
android:id="@+id/buttonCheckEngineStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Engine Status" />
</LinearLayout>
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
98
Android Development for Beginners
6.3
Checkboxes and Radio Buttons
L2pCheckAndRadioActivity.java
package edureka.in.android;
import
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.CheckBox;
android.widget.RadioButton;
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())
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
99
Android Development for Beginners
{
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
100
Android Development for Beginners
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" />
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
101
Android Development for Beginners
</RadioGroup>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Place Order" />
</LinearLayout>
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
102
Android Development for Beginners
6.4
Spinners
L2pSpinnerActivity.java
package edureka.in.android;
import
import
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.AdapterView;
android.widget.AdapterView.OnItemSelectedListener;
android.widget.ArrayAdapter;
android.widget.Spinner;
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<?>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
103
Android Development for Beginners
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
104
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
105
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
106
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
107
Android Development for Beginners
Chapter 7: Android Widgets Part II
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
108
Android Development for Beginners
7.1
Autocomplete Text Box
L2pAutoCompleteTextViewActivity.java
package edureka.in.android;
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.widget.ArrayAdapter;
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
109
Android Development for Beginners
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<requestFocus />
</AutoCompleteTextView>
</LinearLayout>
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
110
Android Development for Beginners
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
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
111
Android Development for Beginners
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
112
Android Development for Beginners
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/wpcontent/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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
113
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
114
Android Development for Beginners
7.4
Time and Date Pickers
L2pDateAndTimeActivity.java
package edureka.in.android;
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.DatePickerDialog;
android.app.Dialog;
android.app.TimePickerDialog;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.DatePicker;
android.widget.TextView;
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);
}
});
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
115
Android Development for Beginners
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,
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
116
Android Development for Beginners
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
117
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
118
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
119
Android Development for Beginners
Chapter 8: Communicating Between Activities
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
120
Android Development for Beginners
8.1
Switching Activities
L2pSwitchingActivitiesActivity.java
package edureka.in.android;
import
import
import
import
import
android.app.Activity;
android.content.Intent;
android.os.Bundle;
android.view.View;
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);
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
121
Android Development for Beginners
// 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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
122
Android Development for Beginners
<?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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
123
Android Development for Beginners
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
124
Android Development for Beginners
8.2
Putting Extra
L2pPutExtraActivity.java
package edureka.in.android;
import
import
import
import
import
import
android.app.Activity;
android.content.Intent;
android.os.Bundle;
android.view.View;
android.widget.Button;
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;
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
125
Android Development for Beginners
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
126
Android Development for Beginners
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
127
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
128
Android Development for Beginners
8.3
Using Shared Preferences
L2pSharedPreferencesActivity.java
package edureka.in.android;
import
import
import
import
import
import
import
android.app.Activity;
android.content.Intent;
android.content.SharedPreferences;
android.os.Bundle;
android.view.View;
android.widget.Button;
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());
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
129
Android Development for Beginners
editor.commit();
Intent intent = new
Intent(getApplicationContext(), second.class);
startActivity(intent);
}
});
}
}
second.java
package edureka.in.android;
import
import
import
import
android.app.Activity;
android.content.SharedPreferences;
android.os.Bundle;
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
130
Android Development for Beginners
<?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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
131
Android Development for Beginners
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
132
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
133
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
134
Android Development for Beginners
Chapter 9: Storing Information on the Device
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
135
Android Development for Beginners
9.1
Internal Storage
L2pInternalStorageActivity.java
package edureka.in.android;
import
import
import
import
import
import
java.io.BufferedReader;
java.io.BufferedWriter;
java.io.FileNotFoundException;
java.io.IOException;
java.io.InputStreamReader;
java.io.OutputStreamWriter;
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.EditText;
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) {
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
136
Android Development for Beginners
//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);
}
}
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
137
Android Development for Beginners
} 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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
138
Android Development for Beginners
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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
139
Android Development for Beginners
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
140
Android Development for Beginners
9.2
External Storage
L2pExternalStorgageActivity.java
package edureka.in.android;
import
import
import
import
import
import
import
java.io.BufferedReader;
java.io.BufferedWriter;
java.io.File;
java.io.FileNotFoundException;
java.io.FileReader;
java.io.FileWriter;
java.io.IOException;
import
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.os.Environment;
android.view.View;
android.widget.Button;
android.widget.EditText;
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
141
Android Development for Beginners
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;
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
142
Android Development for Beginners
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
143
Android Development for Beginners
<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
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
144
Android Development for Beginners
9.3
Web Communication and Storage
L2pSimpleWebServiceActivity.java
package edureka.in.android;
import
import
import
import
import
import
java.io.BufferedInputStream;
java.io.IOException;
java.io.InputStream;
java.net.MalformedURLException;
java.net.URL;
java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.util.Log;
android.view.View;
android.webkit.WebView;
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
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
145
Android Development for Beginners
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" />
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
146
Android Development for Beginners
<Button
android:id="@+id/btnGetScores"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Scores" />
</LinearLayout>
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
147
Android Development for Beginners
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.
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
148
Android Development for Beginners
Chapter 10: Audio and Video
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
149
Android Development for Beginners
10.1 Playing Audio with the MediaPlayer
package edureka.in.android;
import
import
import
import
import
import
android.app.Activity;
android.media.MediaPlayer;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
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();
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
150
Android Development for Beginners
}
}
}
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>
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
151
Android Development for Beginners
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
152
Android Development for Beginners
10.2 Playing Video with the MediaPlayer
L2pVideoViewActivity.java
package edureka.in.android;
import
import
import
import
import
android.app.Activity;
android.net.Uri;
android.os.Bundle;
android.widget.MediaController;
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"
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
153
Android Development for Beginners
/>
</LinearLayout>
Notes
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
154
Android Development for Beginners
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!
© 2012 Edureka.in Pvt. Ltd, All rights reserved.
155

Similar documents

STAGE I-Draft0909

STAGE I-Draft0909 142Campbell-STAGEI.pln; 07 Framing Plans - Ground Flooor; 100%; 9/09/2008 4:36 p.m.

More information