JavaAndroidProgramming PDF
JavaAndroidProgramming PDF
Outline
Getting Started
Java: The Basics
Java: ObjectOriented Programming
Android Programming
Linux:
Type sudo
aptget
install
defaultjdk at command line
(Debian, Ubuntu)
Other distributions: consult distributions documentation
Install!
Install!
Outline
Getting Started
Java: The Basics
Java: ObjectOriented Programming
Android Programming
Rightclick,
NewClass
Every Java program has a method main() that executes the program
Method signature must be exactly
Every Java method has curly braces {,} surrounding its code
Every statement in Java ends with a semicolon, e.g.,
System.out.println(Hello
world!);
Size
Minimum
Maximum
Wrapper type
boolean
1bit
N/A
N/A
Boolean
char
16bit
Unicode 0
Unicode 216 1
Character
byte
8bit
128
+127
Byte
short
16bit
215
+215 1
Short
int
32bit
231
+231 1
Integer
long
64bit
263
+263 1
Long
float
32bit
IEEE 754
IEEE 754
Float
double
64bit
IEEE 754
IEEE 754
Double
Math
Comments:
Single-line: //
some
comment
to
end
of
line
Multi-line: /*
comments
span
multiple
lines
*/
boolean
char
int
double
++ --
||
+ -
+ -
&&
* / %
* /
<
>
<=
>=
==
!=
<
>
<
>
<=
>=
==
!=
Notes:
Compare String objects using the equals() method, not == or !=
&& and || use short-circuit evaluation. To see this, say boolean
canPigsFly
=
FALSE
and we evaluate (canPigsFly
&&
<some
Boolean
expression>). Since canPigsFly is
FALSE, the second part of the expression wont be evaluated.
The second operand of % (integer modulus) must be positive.
Dont compare doubles for equality. Instead, define a constant like so:
final
double
EPSILON
=
1E-6;
//
or
some
other
threshold
//
check
if
Math.abs(double1
double2)
<
EPSILON
Example two:
Often, blocks of code should loop while a condition holds (or fixed # of times)
Java iteration idioms: while, do-while, for
While loop: execute loop as long as condition is true (checked each iteration)
Example:
Do-While Loop
Unlike the while loop, the do-while loop executes at least once so long as condition is true.
The while loop prints aaaaaaaaaa whereas the do-while loop prints aaaaaaaaaaa (11 as)
Semantics:
<expression1>
is
<expression2>
is
<expression3>
is
Example:
int
i;
for
(i
=
0;
i
<
10;
i++)
{
System.out.println(i
=
+
i);
}
System.out.println(i
=
+
i);
Two-Dimensional Arrays
We can have two-dimensional arrays.
Example:
Notice:
Need to call import
java.util.ArrayList; at beginning of program
Off-by-one indexing: cannot call arrStrings.get(4);
Auto-boxing: we cannot create an ArrayList of doubles. We need to
replace double with wrapper class Double. (Recall the primitive data
types table)
Other parameterized data types include Lists, Sets, Maps, Stacks,
Queues, Trees (see chapters 1416 in [1])
try
{
//
Code
that
could
trigger
an
exception
}
catch
(IndexOutOfBoundsException
e)
//
Or
another
Exception
{
//
Code
that
responds
to
exception,
e.g.,
e.printStackTrace();
}
finally
{
//
Code
that
executes
regardless
of
whether
exception
occurs
}
There can be many catch blocks for different Exceptions, but there is only
one try block and one (optional) finally block. (See Section 7.4 in [1] for
the full hierarchy of Exceptions)
Outline
Getting Started
Java: The Basics
Java: ObjectOriented Programming
Android Programming
There are many possible Vehicles, e.g., Honda Accord, Mack truck, etc. These
are instances of the Vehicle blueprint
Many Vehicle states are specific to each Vehicle object, e.g., on/off, driver in
seat, fuel remaining. Other states are specific to the class of Vehicles, not any
particular Vehicle (e.g., keeping track of the last Vehicle ID # assigned).
These correspond to instance fields and static fields in a class.
Notice: we can operate a vehicle without knowing its implementation under
the hood. Similarly, a class makes public instance methods by which objects
of this class can be manipulated. Other methods apply to the set of all Vehicles
(e.g., set min. fuel economy). These correspond to static methods in a class
Notes:
Aliasing: If we set Vehicle myTruck
=
myCar, both myCar and myTruck
point to the same variable. Better to perform deep copy of
myCar and store the copy in myTruck
null reference: refers to no object, cannot invoke methods on null
Implicit parameter and the this reference
Inheritance (1)
Types of Vehicles: Motorcycle, Car, Truck, etc. Types of Cars:
Sedan, Coupe, SUV. Types of Trucks: Pickup, Flatbed.
Induces inheritance hierarchy
Subclasses inherit fields/methods from superclasses.
Subclasses can add new fields/methods, override those of
parent classes
For example, Motorcycles driveForward() method differs
from Trucks driveForward() method
Inheritance (2)
Inheritance denoted via extends keyword
public
class
Vehicle
{
public
void
driveForward
(double
speed)
{
//
Base
class
method
}
}
Inheritance (3)
public
class
Truck
extends
Vehicle
{
private
boolean
useAwd
=
true;
public
Truck(boolean
useAwd)
{
this.useAwd
=
useAwd;
}
public
void
driveForward(double
speed)
{
if
(useAwd)
{
//
Apply
power
to
all
wheels
}
else
{
//
Apply
power
to
only
front/back
wheels
}
}
}
Polymorphism
Suppose we create Vehicles and invoke the driveForward() method:
representation
equals(): Compares contents of Objects to see if
theyre the same
hashCode(): Hashes the Object to a fixed-length
String, useful for data structures like HashMap,
HashSet
Interfaces
otherwise
In your classes, you should implement Comparable to
facilitate Object comparison
For software projects, start from use cases (how customers will use
software: high level)
Then identify classes of interest
In each class, identify fields and methods
Class relationships should be identified: is-a (inheritance), has-a
(aggregation), implements interface, etc.
Outline
Getting Started
Java: The Basics
Java: ObjectOriented Programming
Android Programming
Introduction to Android
Popular mobile device
OS: 52% of U.S.
smartphone market [8]
Developed by Open
Handset Alliance, led by
Google
Google claims 900,000
Android device
activations [9]
Source: [8]
(not
App Manifest
Every Android app must include an
AndroidManifest.xml file describing functionality
The manifest specifies:
Apps Activities, Services, etc.
Permissions requested by app
Minimum API required
Hardware features required, e.g., camera with
autofocus
External libraries to which app is linked, e.g., Google
Maps library
Activity Lifecycle
Activity: key
building
block of Android apps
Extend Activity class,
override onCreate(),
onPause(), onResume()
methods
Dalvik VM can stop any
Activity without warning,
so saving state is important!
Activities need to be
responsive, otherwise
Android shows user App
Not Responsive warning:
Place lengthy operations in
Threads, AsyncTasks
Source: [12]
For Eclipse:
Make sure youve enabled LogCat, Devices views. Click a
connected device in Devices to see its log
Programs should log states via android.util.Logs
RelativeLayouts are quite complicated. See [13] for details
//
Set
up
WifiManager.
mWifiManager
=
(WifiManager)
getSystemService(Context.WIFI_SERVICE);
//
Create
listener
object
for
Button.
When
Button
is
pressed,
scan
for
//
APs
nearby.
Button
button
=
(Button)
findViewById(R.id.button);
button.setOnClickListener(new
View.OnClickListener()
{
public
void
onClick(View
v)
{
boolean
scanStarted
=
mWifiManager.startScan();
}
});
//
If
the
scan
failed,
log
it.
if
(!scanStarted)
Log.e(TAG,
"WiFi
scan
failed...");
@Override
protected
void
onResume()
{
super.onResume();
registerReceiver(mReceiver,
mIntentFilter);
}
@Override
protected
void
onPause()
{
super.onPause();
unregisterReceiver(mReceiver);
}
User Interface
Updating UI in code
private
void
setTextView(String
str)
{
TextView
tv
=
(TextView)
findViewById(R.id.textview);
tv.setMovementMethod(new
ScrollingMovementMethod());
tv.setText(str);
}
This code simply has the UI display
all collected WiFi APs, makes the
text information scrollable
UI Layout (XML)
<LinearLayout
xmlns:android="http://schemas.android.com/apk/
res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="@string/button_text"/>
<TextView
android:id="@+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/ap_list"
tools:context=".WiFiActivity"
android:textStyle="bold"
android:gravity="center">
</TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".WiFiActivity"
android:id="@+id/textview"
android:scrollbars="vertical">
</TextView>
</LinearLayout>
Example:
Concurrency: AsyncTasks
AsyncTask encapsulates asynchronous task that interacts with UI thread
in Activity:
public
class
AsyncTask<Params,
Progress,
Result>
{
protected
Result
doInBackground(ParamType
param)
{
//
code
to
run
in
background
publishProgress(ProgressType
progress);
//
UI
return
Result;
}
protected
void
onProgressUpdate(ProgressType
progress)
{
//
invoke
method
in
Activity
to
update
UI
}
}
Thank You
Any questions?
References (1)
1.
2.
3.
4.
5.
6.
7.
8.
9.
References (2)
10.
11.
12.
13.
http://bcs.wiley.com/he-bcs/Books?action=index&itemId=1118087887&bcsId=7006
B. Goetz, T. Peierls, J. Bloch, J. Bowbeer, D. Holmes, and D. Lea, Java Concurrency in
Practice, Addison-Wesley, 2006, online at
http://proquest.safaribooksonline.com/book/programming/java/0321349601
https://developer.android.com/guide/components/activities.html
https://developer.android.com/guide/topics/ui/declaring-layout.html#CommonLayouts