Modul Java Android
Modul Java Android
Java
a nd A
p
o
h
s
TM Work
d
i
o
r
d
n
Module-by-Module Overview
! Module 1 : Introduction Java
Module 2 : Object Oriented
Module 3 : Variables
Module 4 : How Object Behave
Module 5 : Core Concept Android
! Module 6 : Activities
Module 1
Introduction Java
Anatomy of Class
public class MyFirstApp {
public static void main (String[] args) {
System.out.println(Java and Android workshop);
}
}
Looping
! Java has three standard looping constructs : while, dowhile, and for
! The key to a loop is the conditional test that result in a
boolean value
! You can do a simple boolean test by checking the value of
a variable, using a comparison operator including :
< (less than)
>(greater than)
== (equality)
Int x = 4; // assign 4 to x
while (x>3) {
//loop code will run because x is greater than 3
x = x-1;
}
Int z = 27;
while (z == 17) {
//loop code will not run because z is not equal to 17
}
Compiler Vs JVM
Java Virtual Machine
Compiler
Module 2
Object Oriented
Inheritance
Square
rotate ()
palySound ()
Shape
rotate ()
palySound ()
Circle
rotate ()
palySound ()
Triangle
Amoeba
rotate ()
palySound ()
rotate ()
palySound ()
Shape
superclass
rotate ()
palySound ()
subclasses
Square
Circle
Triangle
Amoeba
Overriding Method
Shape
rotate ()
palySound ()
Square
Circle
Triangle
Amoeba
rotate () {
//amoeba specific
rotate method}
playsound () {
//amoeba specific
sound code}
Class Structure
When you design a class, think about the object that will be created from that
Class type. Think about :
things the object knows
things the object does
Things an object knows about itself are called instance variables
Things an object can do are called methods
Shopping Cart
Button
cartContents
knows
label
color
knows
addToCart()
removeFromCart()
checkOut()
does
setColor()
setLabel()
dePress()
unDePress()
does
Using main()
GuessGame
GameLauncher
main(String[] args)
p1
p2
p3
startGame()
Player
number
guess()
int guessp1=0;
int guessp2=0;
int guessp3=0;
boolean p1isRight=false;
boolean p2isRight=false;
boolean p3isRight=false;
int targetNumber=(int)(Math.random()*10);
System.out.println(Im thinking of a number between 0 and 9);
while(true){
System.out.println(Number to guess is +targetNumber);
p1.guess();
p2.guess();
p3.guess();
guessp1=p1.number;
System.out.println(Player one guessed +guessp1);
guessp2=p2.number;
System.out.println(Player two guessed +guessp2);
guessp3=p3.number;
System.out.println(Player three guessed +guessp3);
if(uessp1==targetNumber){
p1isRight=true;
}
if(uessp2==targetNumber){
p2isRight=true;
}
if(uessp3==targetNumber){
p3isRight=true;
}
if(p1isRight||p2isRight||p3isRight){
System.out.println(We have a winner!);
System.out.println(Player one got it right? +p1isRight);
System.out.println(Player two got it right? +p2isRight);
System.out.println(Player three got it right? +p3isRight);
System.out.println(game is over);
break;
}else{
System.out.println(Players will have to try again);
}
}
}
}
Module 3
Variables
Declaring a Variable
Variables come in two flavors : primitive and object reference. Primitives
hold fundamental values including integers, booleans, and floating point
numbers. Object reference hold reference to object.
Regardless the type, there is two declaration rules:
name
Primitive Types
Type
Bit Depth
boolean and char
boolean (JVM-specific)
char
16 bits
numeric (all are signed)
integer
byte
8 bits
short
16 bits
int
32 bits
long
64 bits
floating point
float
32 bits
double
64 bits
Value Range
true or false
0 to 65535
128 to 127
-32768 to 32767
-2147483648 to 2147483647
-huge to huge
varies
varies
Java Keyword
A class, method, or variable can be named according to the following
rules:
it must start with a letter, underscore (_), or dollar sign($). You cant start
a name with a number
After the first character, you can use numbers as well
it can be anything you like, subject to those two rules, just so long as it
isnt one of Javas reserved words.
Java reserved words :
boolean
protected
else
class
catch
byte
abstract
do
extends
finally
char
final
while
implements
try
double
native
switch
import
throw
float
static
case
instanceof
throws
int
stictfp
default
interface
return
long
synchronized
for
new
void
short
transient
break
package
const
public
volatile
continue
super
goto
private
if
assert
this
enum
Reference Variable
An object reference variable holds bits that represent a way to access an
object
It doesnt hold the object itself, but it holds something like a pointer. Or
an address. Except, in Java we dont really know what is inside a reference
variable. We do know that whatever it is, it represents one and only one
object. And the JVM knows how to use the reference to get to the object
3
Dog myDog = new Dog();
2. Create an object
1
b
Book object
Book
2
Book object
c
Book
1
Book d = c;
Book object
Book
2
Book object
c
Book
d
Book
1
c = b;
Book object
Book
2
Book object
c
d
Book
Book
b = null;
Book object
Book
2
Book object
c
Book
d
Book
Arrays
1. Declare an int array variable
int[] nums;
nums
int[]
0 1 2 3 4 5 6
int int int int int int int
int array object (int[])
Dog object
nums
int[]
Module 4
method
(behaviour)
void play(){
soundPlayer.playSound(title);
}
title
artist
knows
setTitle()
setArtist()
play()
does
method
(behaviour)
void play(){
soundPlayer.playSound(title);
}
title
artist
knows
setTitle()
setArtist()
play()
does
Darkstar
Grateful
Dead
My Way
Sex Pistols
Sing
Travis
t2
s3
Song
Song
t2.play();
Calling play() on this instance
will cause Sing to play
s3.play();
Calling play() on this instance
will cause My Way to play
if you declare a method to return a value, you must return a value of the declared
type.
these type
must match
int giveSecret() {
return 42;
}
Pass-by-Value
int x = 7
x
int
int
copy of x
int
int
foo.go(x);
x and z arent
connected
x
int
int
void go(int z){
z = 0;
}
String getBrand(){
return brand;
}
void setBrand(String aBrand){
brand = aBrand
}
int getNumOfPickups(){
return numOfPickUps;
}
void setNumOfPickUps(int num){
numOfPickUps=num;
}
boolean getRockStarUseIt(){
return rockStarUseIt;
}
void setRockStarUseIt(boolean yesOrNo){
rockStarUseIt = yesOrNo;
}
}
ElectricGuitar
brand
numOfPickups
rockStarUseIt
getBrand()
setBrand()
getNumOfPickups()
setNumOfPickups()
getRockStarUseIt()
setRockStarUseIt()
Encapsulations
Encapsulation puts a force-fields around class instance variables, so nobody can
set them with an inappropriate values.
Heres an encapsulation starter rule of thumb : mark your instance variables
private and provide public getters.
class GoodDog{
private int size;
public int getSize(){
return size;
}
public void setSize(int s){
size = s;
}
void bark(){
if (size > 60){
System.out.println(Woof! Woof!);
} else if (size > 14) {
System.out.println(Ruff! Ruff!);
}
GoodDog
size
getSize()
setSize()
bark()
else {
System.out.println(Yip! Yip!);
}
}
}
class GoodDogTestDrive {
public static void main(String[] args) {
GoodDog one = new GoodDog();
one.setSize(70);
GoodDog two = new GoodDog();
two.setSize(8);
System .out.println(Dog one : +one.getSize());
System .out.println(Dog two : +two.getSize());
one.bark();
two.bark();
}
}
0 1
2 3
4
5 6
Dog Dog Dog Dog Dog Dog Dog
Dog array object (Dog[])
pets
Dog[]
30
size
size
Dog Object
Dog Object
0 1
2 3
4
5 6
Dog Dog Dog Dog Dog Dog Dog
Dog array object (Dog[])
pets
Dog[]
Module 5
Core Concepts
Project
Structure
Root Contents :
! AndroidManifest.xml , an XML file describing the
application being built and what componentsactivities,
services, etc.are being supplied by that application
! build.xml, an Ant script for compiling the application and
installing it on the device
! default.properties, a property file used by the Ant build
script
! bin/ holds the application once it is compiled
! libs/ holds any third-party Java JARs your application
requires
! src/ holds the Java source code for the application
! res/ holds resources, such as icons, GUI layouts, and the
like, that get packaged with the compiled Java in the
application
! assets/ holds other static files you wish packaged with the
application for deployment onto the device
Inside the
Manifest
! The root of all manifest files is a manifest element:
! <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.commonsware.android.search">
...
</manifest>
! Underneath the manifest element, you will find the following:
uses-permission elements to indicate what permissions your application will
need in order to function properly.
permission elements to declare permissions that activities or services might
require other applications hold in order to use your applications data or logic.
instrumentation elements to indicate code that should be invoked on key
system events, such as starting up activities, for the purposes of logging or
monitoring.
uses-library elements to hook in optional Android components, such as
mapping services
Possibly a uses-sdk element to indicate what version of the Android SDK the
application was built for.
An application element defining the guts of the application that the manifest
describes.
! <manifest xmlns:android="http://schemas.android.com/
apk/res/android"
package="com.commonsware.android.skeleton">
! <application>
<activity android:name=".Now" android:label="Now">
! <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
! </intent-filter> </activity>
! </application> </manifest>
Module 6
Activities
package com.commonsware.android.skeleton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Date;
public class Now extends Activity implements View.OnClickListener {
Button btn;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(this);
updateTime();
}
public void onClick(View view) {
updateTime();
}
private void updateTime() {
btn.setText(new Date().toString());
}
}
Images
The simplest widget is the label, referred to in Android as a TextView.
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/icon"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:src="@drawable/molecule"/>
Fields
Check Box
<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This checkbox is: unchecked" />
public class CheckBoxDemo extends Activity
implements CompoundButton.OnCheckedChangeListener {
CheckBox cb;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
cb=(CheckBox)findViewById(R.id.check);
cb.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cb.setText("This checkbox is: checked");
}
else {
cb.setText("This checkbox is: unchecked");
}
}
}
Radio Button
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RadioButton android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rock" />
<RadioButton android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scissors" />
<RadioButton android:id="@+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paper" />
</RadioGroup>
<RadioGroup android:id="@+id/gravity"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px">
<RadioButton
android:id="@+id/left"
android:text="left" />
<RadioButton
android:id="@+id/center"
android:text="center" />
<RadioButton
android:id="@+id/right"
android:text="right" />
</RadioGroup>
</LinearLayout>
package com.commonsware.android.containers;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.text.TextWatcher;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.EditText;
public class LinearLayoutDemo extends Activity implements
RadioGroup.OnCheckedChangeListener {
RadioGroup orientation;
RadioGroup gravity;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
orientation=(RadioGroup)findViewById(R.id.orientation);
orientation.setOnCheckedChangeListener(this);
gravity=(RadioGroup)findViewById(R.id.gravity);
gravity.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (group==orientation) {
if (checkedId==R.id.horizontal) {
orientation.setOrientation(LinearLayout.HORIZONTAL);
} else {
orientation.setOrientation(LinearLayout.VERTICAL);
}
}
else if (group==gravity) {
if (checkedId==R.id.left) {
gravity.setGravity(Gravity.LEFT);
} else if (checkedId==R.id.center) {
gravity.setGravity(Gravity.CENTER_HORIZONTAL);
}
else if (checkedId==R.id.right) {
gravity.setGravity(Gravity.RIGHT);
}
}
}
Relative Layout
RelativeLayout, as the name suggests, lays out widgets based upon their
relationship to other widgets in the container and in the parent container.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px">
<TextView android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="URL:"
android:paddingTop="15px"/>
<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/label"
android:layout_alignBaseline="@id/label"/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/entry"
android:layout_alignRight="@id/entry"
android:text="OK" />
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok"
android:text="Cancel" />
</RelativeLayout>
Table Layout
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="URL:" />
<EditText android:id="@+id/entry"
android:layout_span="3"/>
</TableRow>
<View
android:layout_height="2px"
android:background="#0000FF" />
<TableRow>
<Button android:id="@+id/cancel"
android:layout_column="2"
android:text="Cancel" />
<Button android:id="@+id/ok"
android:text="OK" />
</TableRow>
</TableLayout>
Scroll View
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="0">
<TableRow>
<View
android:layout_height="80px"
android:background="#000000"/>
<TextView android:text="#000000"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#440000" />
<TextView android:text="#440000"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#884400" />
<TextView android:text="#884400"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#aa8844" />
<TextView android:text="#aa8844"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffaa88" />
<TextView android:text="#ffaa88"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffffaa" />
<TextView android:text="#ffffaa"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffffff" />
<TextView android:text="#ffffff"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
</TableLayout>
</ScrollView>
Spin
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Spinner android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
/>
</LinearLayout>
Grid
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<GridView
android:id="@+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:verticalSpacing="35px"
android:horizontalSpacing="5px"
android:numColumns="auto_fit"
android:columnWidth="100px"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</LinearLayout>
Fields
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<AutoCompleteTextView android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionThreshold="3"/>
</LinearLayout>
Applying Menus
Hardcode
public class MenuDemo extends ListActivity {
TextView selection;
String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
"consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis",
"etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
public static final int EIGHT_ID = Menu.FIRST+1;
public static final int SIXTEEN_ID = Menu.FIRST+2;
public static final int TWENTY_FOUR_ID = Menu.FIRST+3;
public static final int TWO_ID = Menu.FIRST+4;
public static final int THIRTY_TWO_ID = Menu.FIRST+5;
public static final int FORTY_ID = Menu.FIRST+6;
public static final int ONE_ID = Menu.FIRST+7;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
selection=(TextView)findViewById(R.id.selection);
registerForContextMenu(getListView());
}
case TWO_ID:
getListView().setDividerHeight(2);
return(true);
case THIRTY_TWO_ID:
getListView().setDividerHeight(32);
return(true);
case FORTY_ID:
getListView().setDividerHeight(40);
return(true);
}
return(false);
}
}
XML Structure
sample.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/close"
android:title="Close"
android:orderInCategory="3"
android:icon="@drawable/eject" />
<item android:id="@+id/no_icon"
android:orderInCategory="2"
android:title="Sans Icon" />
<item android:id="@+id/disabled"
android:orderInCategory="4"
android:enabled="false"
android:title="Disabled" />
<group android:id="@+id/other_stuff"
android:menuCategory="secondary"
android:visible="false">
<item android:id="@+id/later"
android:orderInCategory="0"
android:title="2nd-To-Last" />
<item android:id="@+id/last"
android:orderInCategory="1"
android:title="Last" />
</group>
<item android:id="@+id/submenu"
android:orderInCategory="3"
android:title="A Submenu">
<menu>
<item android:id="@+id/non_ghost"
android:title="Non-Ghost"
android:visible="true"
android:alphabeticShortcut="n" />
<item android:id="@+id/ghost"
android:title="A Ghost"
android:visible="false"
android:alphabeticShortcut="g" />
</menu>
</item>
</menu>