Developing Applications for Android - Lecture#2

40
Developing Applications for Android Muhammad Usman Chaudhry SZABIST CS4615 Lecture # 2

description

Slides from course, Developing Applications for Android, CS4615, SZABIST, Karachi.

Transcript of Developing Applications for Android - Lecture#2

Page 1: Developing Applications for Android - Lecture#2

Developing Applications for Android

Muhammad Usman ChaudhrySZABIST CS4615

Lecture # 2

Page 2: Developing Applications for Android - Lecture#2

Today - OOP Revision

● Classes & Obejcts Overview● Nested Classes

○ Static nested & Inner classes○ Local & anonymous classes

● Inheritance ● Method Overriding & Dynamic Polymorphism● Abstraction● Interfaces● Packages● Annotations & Javadocs

Muhammad Usman Chaudhry CS4615 SZABIST

Page 3: Developing Applications for Android - Lecture#2

Today - Design Patterns

● Design Patterns Overview● Context Pattern● Adapter Pattern● Separation of Concerns

○ Model-View-Controller

Muhammad Usman Chaudhry CS4615 SZABIST

Page 4: Developing Applications for Android - Lecture#2

Classes & Objects

● Coming code example will explain:○ Classes○ Objects○ Encapsulation○ Constructors○ Class Members & Methods○ Instance Members & Methods○ Entry Point○ Getter & Setters

Muhammad Usman Chaudhry CS4615 SZABIST

Page 5: Developing Applications for Android - Lecture#2

//Student.javaclass Student{

private String studentName; private static int count; public void setStudentName(String _studentName){ if(!_studentName.equals("")) this.studentName = _studentName; } public String getStudentName(){ return this.studentName; } public String getEncodedUrlForStudentName(){ return UrlEncoder.encode(this.getStudentName(),"UTF-8"); } ...

Muhammad Usman Chaudhry CS4615 SZABIST

Attribute

Setter

Getter

Access Modifier

Static Member

Validation

Instance Method

Not Recommended

Page 6: Developing Applications for Android - Lecture#2

... public static int getCount(){ return Student.count; }

public Student(){ this("No Name"); } public Student(String studentName){ this.setStudentName(studentName); } public static void main(String[] args){ Student stduent = new Student(); String name = student.getName(); int count = Student.getCount(); }}

Muhammad Usman Chaudhry CS4615 SZABIST

Class Method

Entry Point

Object of Type Student

Instance Method Call

Class Method Call

Default Constructor

Calling 1-argument constructor

1-argument Constructor

Page 7: Developing Applications for Android - Lecture#2

Nested Classes

● Java allows defining class within another class.● Nested classes are divided into 2 more

categories:○ Static Nested Classes (Declared Static)○ Inner Nested Classes (Non-static)

■ Local Classes■ Anonymous Classes

○ Both Inner & Static nested classes have member scope.

● Examples & Uses are in coming slides.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 8: Developing Applications for Android - Lecture#2

Example: Static & Inner Nested Classes

Muhammad Usman Chaudhry CS4615 SZABIST

//Outer class can only be public or package-privateclass OuterClass{ private int someVariable; //Modifier can be private, protected, public or package-private static class StaticNestedClass{ //Cannot access private members of outer class directly. } class InnerClass{ //Can access private members of outer class OuterClass oc = OuterClass.this; // implicit reference available int a = oc.someVariable; //can be done int b = OuterClass.this.someVariable; //is another way to access... } //Cannot declare static members within inner nested class.}

Page 9: Developing Applications for Android - Lecture#2

Example: Accessing Nested Inner Class

Muhammad Usman Chaudhry CS4615 SZABIST

//Accessing Nested Inner ClassOuterClass oc = new OuterClass(); //Either create new object or use previous instanceOuterClass.InnerClass innerClassObject = oc.new InnerClass(); //Way#1 OuterClass.InnerClass innerClassObject = new OuterClass().new InnerClass(); //Way#2

● Way#1 is using previous instance so all values of the object of outer class will be intact and accessible via inner class.

● Way#2 is creating new instance of outer class as well.

Page 10: Developing Applications for Android - Lecture#2

Example: Accessing Nested Static Class

Muhammad Usman Chaudhry CS4615 SZABIST

//Accessing Nested Static ClassOuterClass.StaticNestedClass sncObj = new OuterClass.StaticNestedClass();

● As simple as creating the normal object. No added syntax.

Page 11: Developing Applications for Android - Lecture#2

Local & Anonymous Inner Classes

● Inner class within 'body' of a method is known as local inner class.

● Inner class within 'body' of a method without naming it is known as anonymous inner class.

● Scope of local inner class is local to function.

● Scope of anonymous inner class is only to the point where it's declared.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 12: Developing Applications for Android - Lecture#2

Example: Local Inner Class

Muhammad Usman Chaudhry CS4615 SZABIST

class OuterClass{ private int someVariable; public OuterClass(){ //Local inner classes don't specify access modifiers class LocalInnerClass{ public void myInnerMethod(){ //implicit reference available to access members of outer class... int count = OuterClass.this.someVariable; } } LocalInnerClass lic = new LocalInnerClass(); lic.myInnerMethod(); }}

Page 13: Developing Applications for Android - Lecture#2

Example: Anonymous Inner Class

Muhammad Usman Chaudhry CS4615 SZABIST

public void someFunction(){ new Thread(new Runnable(){ @Override public void run(){ //do something here... } }).start(); }

class RunnableThread implements Runnable{ RunnableThread(){ //do something in constructor } public void run(){ //do something here... }}..//To access itRunnableThread myThread = new RunnableThread();new Thread(myThread).start();

● Left (Anonymous) Vs Right (Normal)● No clutter in coding

Page 14: Developing Applications for Android - Lecture#2

Why Use Nested Classes

● Logically grouping classes together.● Increase encapsulation.● Clean coding.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 15: Developing Applications for Android - Lecture#2

Important

● Java don't have anything exactly similar to Objective-C or .Net delegates, the closest thing is anonymous inner class which are used instead of delegates.

● The main trick is to create an interface with a single function and then implement it via anonymous inner class.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 16: Developing Applications for Android - Lecture#2

Inheritance

● When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class.

● A class that is derived from another class is called sub-class, inherited class (derived, extended, child etc.)

● Java does support multi-level inheritance.● There is no support for multiple inheritance in Java

and every class can extend up to one class at a time.● Lets go through examples in next slides.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 17: Developing Applications for Android - Lecture#2

Muhammad Usman Chaudhry CS4615 SZABIST

//A bicycle class : Example taken from Oracle Docs...public class Bicycle { public int cadence; public int gear; public int speed; public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } public void setCadence(int newValue) { cadence = newValue; } public void setGear(int newValue) { gear = newValue; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; }}

Page 18: Developing Applications for Android - Lecture#2

Muhammad Usman Chaudhry CS4615 SZABIST

public class MountainBike extends Bicycle { // the MountainBike subclass adds // one field public int seatHeight;

// the MountainBike subclass has one // constructor public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; } // the MountainBike subclass adds // one method public void setHeight(int newValue) { seatHeight = newValue; } }

Page 19: Developing Applications for Android - Lecture#2

Method Overriding & Dynamic Polymorphism

● Redefining superclass method in subclass.● An instance method in subclass with the same signature

(name, number, type of params & return type) as instance method in superclass overrides the superclass's method.

● We may access the functionality of methods and members of super class via 'super' keyword.

● In case reference variable is calling an overridden method the method to be invoked is determined by the object, your reference variable is pointing to. (dynamic polymorphism).

● Examples to follow in coming slides.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 20: Developing Applications for Android - Lecture#2

Muhammad Usman Chaudhry CS4615 SZABIST

//Class professionalclass Professional { public String name; public Professional(){ } public boolean isDisciplined(){ //professional level implementations }}

//Class programmerclass Programmer extends Professional{ public Programmer(){ } @Override public boolean isDisciplined(){ //professional rules also apply super.isDisciplined(); //programmer level implementations }}

//Calling allProfessional p = new Professional();

Programmer prog = new Programmer();

p.isDisciplined();//Normal call

//First professional is called, then //programmer's isDisciplined is called. prog.isDisciplined();

//without super.isDisciplined() statement//calling prog.isDisciplined(); will only call//programmer's isDisciplined() method.

//dynamic polymorphismProfessional pr = new Programmer();pr.isDisciplined();

Page 21: Developing Applications for Android - Lecture#2

Abstraction

● An abstract class cannot be instantiated.● Abstract class can be subclassed.● An abstract method, only has signatures.● If any class has abstract methods it must be declared

abstract itself.● Subclass must implement all the abstract methods of

abstract class otherwise it must be declared abstract as well.

● Abstract class may also contain abstract methods.● Examples in next slides.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 22: Developing Applications for Android - Lecture#2

Muhammad Usman Chaudhry CS4615 SZABIST

//Abstract class exampleabstract class GraphicObject { int x; int y; void moveTo(int newX, int newY) { //some implementation } abstract void draw(); abstract void resize();}

//Implementationclass Circle extends GraphicObject { void draw() { //circle specific implementation } void resize() { //circle specific resize }}class Rectangle extends GraphicObject { void draw() { //rectangle specific implementation } void resize() { //rectangle specific resizing }}

Page 23: Developing Applications for Android - Lecture#2

Interfaces

● Interfaces are implemented by other classes and extended by other interfaces.

● Unlike class inheritance an interface can extend multiple interfaces.

● Interface body contains signatures only. ● All methods in an interface are implicitly

public.● Example to follow.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 24: Developing Applications for Android - Lecture#2

Muhammad Usman Chaudhry CS4615 SZABIST

//Interface examplepublic Interface GraphicInterface { void draw(); void resize();}

//Implementationclass Circle implements GraphicInterface { void draw() { //circle specific implementation } void resize() { //circle specific resize }}class Rectangle extends GraphicInterface { void draw() { //rectangle specific implementation } void resize() { //rectangle specific resizing }}

Page 25: Developing Applications for Android - Lecture#2

Abstract Class Vs Interface

● Abstract class can contain fields that are not static & final.

● Similarly abstract class can contain implementations, while interface is signature only.

● One class can implement multiple interfaces. While the same class cannot extend multiple abstract classes.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 26: Developing Applications for Android - Lecture#2

Packages

● Grouping similar classes together is called package.

● It's similar to that of namespace in .Net● An example would be custom controls

related classes are in controls package, or graphics related classes in graphics package etc.

● import statement is used to include packages.

● Examples to follow.Muhammad Usman Chaudhry CS4615 SZABIST

Page 27: Developing Applications for Android - Lecture#2

Muhammad Usman Chaudhry CS4615 SZABIST

//Package example//Sample package package net.thepaksoft.appname; //current package

//all graphics related customized classesimport net.thepaksoft.appname.graphics.*;

//ListView classimport net.thepaksoft.appname.controls.ListView;

Page 28: Developing Applications for Android - Lecture#2

Annotations & Javadocs

● Annotation provide data about code, they don't have direct impact over it.

● Annotations are mostly used for:○ Information for compiler. //Suppress warnings etc.○ Compile time & deploy time processing.//Code generation.○ Runtime processing.//Examination at runtime

● Annotations are used in comments for Javadocs to generate automatic documentation against code.

● Examples to follow.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 29: Developing Applications for Android - Lecture#2

Muhammad Usman Chaudhry CS4615 SZABIST

// Javadoc comment follows /** * @deprecated * explanation of why it * was deprecated */ @Deprecated static void deprecatedMethod() { }}

// mark method as a superclass method // that has been overridden @Override int overriddenMethod() { }// use a deprecated method and tell // compiler not to generate a warning @SuppressWarnings("deprecation") void useDeprecatedMethod() { // deprecation warning // - suppressed objectOne.deprecatedMethod(); }

Page 30: Developing Applications for Android - Lecture#2

Design Patterns

● They're used to solve the common problems.● Classical design patterns include 3 categories and 23

patterns:○ Creational - Deals with creation of object.○ Structural - Deals with structure of object/class. ○ Behavioral - Communication between objects

● Bad patterns or approaches are known as anti-patterns as well.

● There are 100s of other patterns.● We'll study the most relevant and commonly used

under android.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 31: Developing Applications for Android - Lecture#2

Context Pattern in Android

● Interface to global information about application environment.

● It maintains current state of application/object.● Mostly used to get information about other part of

program. ● Used to access standard common resources.● Used to access components implicitly.● Implemented by Android System to provide access to

application specific resources and classes.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 32: Developing Applications for Android - Lecture#2

Context Pattern in Android

● We may get context by invoking any of these:○ getApplicationContext()○ getContext()○ getBaseContext()○ this (Current activity)

● And use above like:○ ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),...);

○ getApplicationContext().getSharedPreference(name,mode);

Muhammad Usman Chaudhry CS4615 SZABIST

Page 33: Developing Applications for Android - Lecture#2

Adapter Pattern in Android

● Aimed at binding view with data.● When your data changes your view changes as well.● No need to add/update data one by one into the view.● Android have following implementations for Adapter:

○ BaseAdapter inherits Adapter implements ListAdapter, SpinnerAdapter

○ ArrayAdatper○ ResrouceCursorAdapter

Muhammad Usman Chaudhry CS4615 SZABIST

Page 34: Developing Applications for Android - Lecture#2

Adapter Pattern Android (Code)

Muhammad Usman Chaudhry CS4615 SZABIST

ArrayList<HashMap> myList = new ArrayList<HashMap>();String[] data = new String[] { "line1","line2" } ;int[] idList = new int[] { R.id.text1, R.id.text2 } ;SimpleAdapter dataToView = new SimpleAdapter(this, myList, R.layout.two_lines, data, idList);setListAdapter( dataToView );

Page 35: Developing Applications for Android - Lecture#2

Separation of Concerns

● Appropriate layered approach● Separate Presentation, Business Logic, from

Design● Partial classes, under Smalltalk, .Net &

Ruby● MVC, MVP, MVVM etc. Patterns

Muhammad Usman Chaudhry CS4615 SZABIST

Page 36: Developing Applications for Android - Lecture#2

MVC - Model-View-Controller

● UI Presentation pattern● Separates View (UI) from Model (Business

Logic)● Separation of Concerns:

○ View is responsible for rendering UI.○ Model is responsible for business behavior.○ Controller is responsible for responding to UI

Actions & communication between Model & View.● All 3 can directly communicate with each

other.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 37: Developing Applications for Android - Lecture#2

MVC - Model-View-Controller

● Implementations as discussed in previous slides exist in many web frameworks like Rails & Yii etc.

● Implementation varies in some frameworks like Cocoa Touch, where:○ Controller is used as communication bridge

between Model & Views, as mentioned previously but Models & Views cannot communicate directly.

○ Views don't have knowledge of Model.○ Models have no knowledge of Views.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 38: Developing Applications for Android - Lecture#2

MVC in Android

● MVC is kind of built into Android● You may create as many 'Model' classes you

like to represent the business data. ● 'Views' are there in form of XML Layouts.● 'Controllers' are there in form of Activity

classes.

Muhammad Usman Chaudhry CS4615 SZABIST

Page 39: Developing Applications for Android - Lecture#2

That's All for Today

● Have great vacations & Eid Mubarak!

Muhammad Usman Chaudhry CS4615 SZABIST

Page 40: Developing Applications for Android - Lecture#2

Coming Up Next Week

● Dive into Android.○ Hello World○ SDK○ File Organization○ AVD○ DDMS○ LogCat○ Debugging○ Manifest○ And Much more...

● Totally interactive class.

Muhammad Usman Chaudhry CS4615 SZABIST