SlideShare une entreprise Scribd logo
1  sur  46
Android- Make It Simple 
-by Preeti Patwa
Agenda 
1. Simple Framework to serialize xml into java object. 
2. Android Process and Thread model. 
3. AsyncTask- best practices. 
4. Volley framework for networking. 
5. Demo of Running debugger in eclipse.
Simple Framework 
Simple is a high performance XML serialization and 
configuration framework for Java. Its goal is to provide an 
XML framework that enables rapid development of XML 
configuration and communication systems. It offers full object 
serialization and deserialization, maintaining each reference 
encountered. 
 Serialize - The process of translating data structures or 
object state into a format that can be stored.(eg. java object 
to xml ) 
 Deserialize – The opposite operation, extracting a data 
structure from a series of bytes.(eg. Xml data to java object)
Simple Framework : Deserializing xml to java 
object 
 The persister is given the class representing the serialized 
object and the source of the XML document. To deserialize 
the object the read method is used, which produces an 
instance of the annotated object. Eg 
 Xml file - 
<root id="123"><message>Example message</message></root> 
 Annotated class representing the serialized object 
@Root(name="root") 
public class Example {
Simple Framework : Deserialization cont... 
@Element(name="message") 
private String text; 
@Attribute(name="id", required = false) 
private int index; 
public String getMessage() { return text; } 
public int getId() { return index; }} 
 Deserializing the object - 
Serializer serializer = new Persister(); 
File source = new File("example.xml"); 
Example example = serializer.read(Example.class, source);
Simple Framework : Basic Annotation- 
 Reading root element @Root, (name=”*”,required=true| 
false) 
 Reading attributes @Attribute(name=”*”,required=true| 
false) 
 Reading a list of elements @ElementList(inline=true) 
 Reading an array of elements @ElementArray 
 Reading an ElementMap eg. <element 
key=”x”>abc</element> @ElementMap(entry="element", 
key="key", attribute=true)
Simple Framework : Basic Annotation Cont... 
 Default object serialization @Default(DefaultType.FIELD| 
DefaultType.PROPERTY) 
 Serializing with CDATA blocks @Element(Data=true) 
 Using XML namespaces 
@Namespace(reference="http://test/test1", prefix="pre") 
 Other Libraries to serialize objects to XML and back again: 
XStream and JIBX. 
 To know more visit: 
http://simple.sourceforge.net/
Android Process and Thread Model 
 Process : A running instance of a program is called 
Process.By default, all components of the same application 
run in the same process. 
 Component of aplicationce can customize which process it 
belongs to by giving android:process attribute in the 
corresponding entry of manifenst file 
 Process lifecycle is maintained using importance hierarchy- 
1. Foreground Process – activity having focus, services bound 
to an activity, or services in onStart(), onDestroy(), onCreate() 
or services start with startForeground() method.
Process Cont... 
2.Visible Process - activity not foreground but still active usually 
when onPause() is called 
3.Services Process – services started with startService() 
method as audio player. 
4.Background Process - A process holding an activity that's not 
currently visible to the user (the activity's onStop() method 
has been called). 
5.Empty Process - It doesn't hold any active application 
components, used for caching purposes, to improve startup 
time the next time a component needs to run in it.
Threads : 
 Thread is a basic unit of CPU utilization. 
 When an application is launched, the system creates a 
thread of execution for the application, called "main” or UI-thread. 
 All components that run in the same process are instantiated 
in the UI thread. 
 It is in charge of dispatching events to the appropriate user 
interface widgets. 
 If everything is happening in the UI thread, performing long 
operations such as network access or database queries will 
block the whole UI.
Thread Cont... 
 When the thread is blocked, no events can be dispatched, 
including drawing events. From the user's perspective, the 
application appears to hang. 
 If the UI thread is blocked for more than a few seconds 
(about 5 seconds currently) the user is presented with the 
infamous "application not responding" (ANR) dialog. **BAD 
USER EXPERIENCE** 
 Two rules to Android's single thread model: 
1.Do not block the UI thread 
2.Do not access the Android UI toolkit from outside the UI 
thread.
Thread Cont... 
public void onClick(View v) { 
new Thread(new Runnable() { 
public void run() { 
//1. Do networking or Database task 
//2. goback to UI thread for UI updation 
//2.1 - Activity.runOnUiThread(Runnable) 
//2.2 - View.post(Runnable) 
//2.3 - View.postDelayed(Runnable, long) 
//2.4 – Use Handler 
} 
}).start(); }
Activity.runOnUIThread 
MainActivity.this.runOnUIThread(new Runnable(){ 
public void run() 
{ 
//doUIWorkHere 
} 
});
View.post Or VIew.postDelayed 
 demoImageView.post(new Runnable() { 
public void run() { 
demoImageView.setImageBitmap(bitmap); 
} 
}); 
 View.onPostDelayed(Runnable r, long millisec) 
call the runnable after the time specified.
UI Thread :
Handler : 
 The Handler is the middleman between a new thread and the 
message queue. 
 A Handler allows you to send and process Message and 
Runnable objects associated with a thread's MessageQueue, 
(Thread that create it). 
 Message : Defines a message containing a description and 
arbitrary data object that can be sent to a Handler.(may 
contain 2 int, 1 object) 
 MessageQueue : Low-level class holding the list of messages 
to be dispatched by a Looper
Handler Cont... 
 There are two main uses for a Handler 
(1) to schedule messages and runnables to be executed 
as some point in the future 
(2) to enqueue an action to be performed on a different 
thread than your own. 
 Scheduling messages is accomplished with the 
post(Runnable), postAtTime(Runnable, long), 
postDelayed(Runnable, long), sendEmptyMessage(int), 
sendMessage(Message), 
sendMessageAtTime(Message, long), and 
sendMessageDelayed(Message, long) methods.
Handler : 
 The post versions allow you to enqueue Runnable 
objects to be called by the message queue when they 
are received; 
 The sendMessage versions allow you to enqueue a 
Message object containing a bundle of data that will be 
processed by the Handler's handleMessage(Message) 
method (requiring that you implement a subclass of 
Handler).ons allow you to enqueue a Message object 
containing a bundle of data that will be processed by the 
Handler's handleMessage(Message) method (requiring 
that you implement a subclass of Handler).
Handler : Using MessageQueue 
final Handler myHandler = new Handler(){ 
@Override 
public void handleMessage(Message msg) { 
updateUI((String)msg.obj);} }; 
(new Thread(new Runnable() { 
@Override 
public void run() { 
Message msg = myHandler.obtainMessage(); 
msg.obj = doLongOperation(); 
myHandler.sendMessage(msg); } 
})).start();
Handler : Using Runnable 
 final Handler myHandler = new Handler(); 
(new Thread(new Runnable() { 
@Override 
public void run() { 
final String res = doLongOperation(); 
myHandler.post(new Runnable() { 
@Override 
public void run() { 
updateUI(res);} }); 
})).start();
AsyncTask : 
 android.os.AsyncTask<Params, Progress, Result> 
 An asynchronous task is defined by a computation that runs 
on a background thread and whose result is published on the 
UI thread. 
 Helper class around Thread and Handler 
 The three generic types used by an asynchronous task are 
the following: 
1.Params - type of the parameters sent to the task upon execution. 
2.Progress, the type of the progress units published during the background 
computation. 
3.Result, the type of the result of the background computation.
AsyncTask Cont... 
 AsyncTask must be subclassed to be used. 
 Main Methods to be overridden- 
1. doInBackground(Params...) *//time consuming operation 
2. onPostExecute(Result...)//run on ui thread after 
doInBackground 
3.onPreExecute() //run on ui thread before doInBackground() 
4.onCancelled(Result result) run On ui thread after cancel
AsyncTask cont... 
5.onProgressUpdate(Progress...values) . 
 Running AsyncTask - 
MyAsyncTask myAsyncTask = new MyAsyncTask(); 
myAsyncTask.execute(); 
 Cancelling AsyncTask - 
myAsyncTask.cancel(true); //now onCancelled() will be called 
instead of onPostExecute() , keep on checking isCancelled() 
method in doInBackground inside a loop and break if it is 
true.
AsyncTask : Order Of Execution (troll) 
 Depends on API level 
1. When it first appeared in Cupcake (1.5) it handled 
background operations with a single additional thread (one by 
one). 
2. In Donut (1.6) it was changed, so that a pool of thread had 
begun to be used. And operations could be processed 
simultaneously until the pool had been exhausted. In such 
case operations were enqueued.
AsyncTask : Order Of Execution (troll) 
 Depends on API level 
1. When it first appeared in Cupcake (1.5) it handled 
background operations with a single additional thread (one by 
one). 
2. In Donut (1.6) it was changed, so that a pool of thread had 
begun to be used. And operations could be processed 
simultaneously until the pool had been exhausted. In such 
case operations were enqueued.
AsyncTask Comparison :
AsyncTask : Order Of Execution Cont. 
3.Since Honeycomb default behavior is switched back to use of 
a single worker thread (one by one processing). But the new 
method (executeOnExecutor) is introduced to give you a 
possibility to run simultaneous tasks if you wish (there two 
different standard executors: SERIAL_EXECUTOR and 
THREAD_POOL_EXECUTOR). 
 The way how tasks are enqueued also depends on what 
executor you use. In case of a parallel one you are restricted 
with a limit of 10 (new 
LinkedBlockingQueue<Runnable>(10)). In case of a serial 
one you are not limited (new ArrayDeque<Runnable>()).
AsyncTask Cont... 
 If there are less than core pool size threads currently 
active and a new job comes in, the executor will create a 
new thread and execute it immediately. 
 If there are at least core pool size threads running, it will 
try to queue the job and wait until there is an idle thread 
available 
 If it is not possible to queue the job (the queue can have 
a max capacity), it will create a new thread (upto 
maximum pool size threads) for the jobs to run in. Non-core 
idle threads can eventually be decommissioned 
according to a keep-alive timeout parameter.
AsyncTask cont... 
 Before Android 1.6, the core pool size was 1 and the 
maximum pool size was 10. Since Android 1.6, the core pore 
size is 5, and the maximum pool size is 128. The size of the 
queue is 10 in both cases. The keep-alive timeout was 10 
seconds before 2.3, and 1 second since then. 
 This is a very good reason why you should not use 
AsyncTasks for long-running operations - it will prevent other 
AsyncTasks from ever running.
AsyncTask cont... 
 Before Android 1.6, the core pool size was 1 and the 
maximum pool size was 10. Since Android 1.6, the core pore 
size is 5, and the maximum pool size is 128. The size of the 
queue is 10 in both cases. The keep-alive timeout was 10 
seconds before 2.3, and 1 second since then. 
 This is a very good reason why you should not use 
AsyncTasks for long-running operations - it will prevent other 
AsyncTasks from ever running.
AsyncTask cont... 
 Before Android 1.6, the core pool size was 1 and the 
maximum pool size was 10. Since Android 1.6, the core pore 
size is 5, and the maximum pool size is 128. The size of the 
queue is 10 in both cases. The keep-alive timeout was 10 
seconds before 2.3, and 1 second since then. 
 This is a very good reason why you should not use 
AsyncTasks for long-running operations - it will prevent other 
AsyncTasks from ever running.
AsyncTask Cont... 
public static void execute(AsyncTask as) { 
if (Build.VERSION.SDK_INT <= 
Build.VERSION_CODES.HONEYCOMB_MR1) { 
as.execute(); 
} else { 
as.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 
} 
}
Volley : Design Tradeoff 
Volley is a library that makes networking for Android apps easier 
and most importantly, faster. 
1. Great for RPC – style operation that populate the UI. 
2. Fine for background RPC. 
3. Terrible for large payloads.
Volley Network Framework : 
private RequestQueue mRequestQueue; 
mRequestQueue = Volley.newRequestQueue(this); 
JsonObjectRequest jr = new 
JsonObjectRequest(Request.Method.GET,url,null,new 
Response.Listener<JSONObject>() { 
@Override 
public void onResponse(JSONObject response) { 
Log.i(TAG,response.toString()); 
parseJSON(response); 
va.notifyDataSetChanged(); 
pd.dismiss();
Debugging Using Eclipse 
Debugging : 
 The process of identifying and fixing errors in software 
 Mainly used to describe run-time errors or incorrect results
Eclipse Debugging Features 
 Breakpoints 
 Step into 
 Step over 
 Step return 
 Step Filters 
 Watches 
 Run to line 
 Suspend/Resume/Terminate
Breakpoints 
 Breakpoints cause the thread of execution to suspend and 
return to the debugger 
 Setting breakpoints in Eclipse is easy, just double-click the 
left margin
Step Into 
 Executes single (highlighted) statement 
 If statement contains call to method, it steps into the method 
 To use: 
 Must be in Debug Perspective 
 Click from Debug Toolbar or press F5
Step Over 
 Executes single (highlighted) statement 
 If statement contains method call, the entire method is 
executed without stepping through it 
 To use: 
 Must be in Debug Perspective 
 Click from Debug toolbar or press F6
Step Return 
 All statements in current method are executed 
 Return to where method was called 
 To use: 
 Must be in Debug Perspective 
 Click from Debug toolbar or press F7
Step with Filters 
 User can specify which methods Step Filter will 
execute and return from 
 Usually you would want steps to be made only into 
methods of your own classes 
 To set filters: 
 Go through Window > Preferences > Java > Debug > Step 
Filtering
Watches 
 Watches allow you to view (and sometimes 
change) the value of a variable during execution 
 In Eclipse, watches are set automatically on 
variables in scope 
 Watches can be found in the Eclipse Debug 
perspective in the “Variables” window 
 Eclipse allows you to change the value of variables 
dynamically during runtime
Run to Line 
 Equivalent to setting a temporary breakpoint 
 CTRL+R
Suspend/Resume/Terminate 
 Suspend pauses the current thread of execution and breaks 
into the debugger 
 Resume resumes a suspended application 
 Terminate stops the program and debugging process 
 Hot Code Replace – supported by eclipse but not by DVM.
Demo
Questions?

Contenu connexe

Tendances

Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javajunnubabu
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped LockHaim Yadid
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threadsrchakra
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPLGyuwon Yi
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksWO Community
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Threading in iOS / Cocoa Touch
Threading in iOS / Cocoa TouchThreading in iOS / Cocoa Touch
Threading in iOS / Cocoa Touchmobiledeveloperpl
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New EvolutionAllan Huang
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in javaAbhra Basak
 

Tendances (20)

Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPL
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Threading in iOS / Cocoa Touch
Threading in iOS / Cocoa TouchThreading in iOS / Cocoa Touch
Threading in iOS / Cocoa Touch
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in java
 
Threads
ThreadsThreads
Threads
 
Threading
ThreadingThreading
Threading
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 

En vedette

Ci through collaboration and km
Ci through collaboration and kmCi through collaboration and km
Ci through collaboration and kmAndrew Muras, PMP
 
G7 mfl c night info 2012-2013
G7 mfl c night info 2012-2013  G7 mfl c night info 2012-2013
G7 mfl c night info 2012-2013 irenegu2009
 
Davis walker clint-visual_resumestoryboard
Davis walker clint-visual_resumestoryboardDavis walker clint-visual_resumestoryboard
Davis walker clint-visual_resumestoryboardCDWfullsail
 
Davis walker clint-visual_resumestoryboard
Davis walker clint-visual_resumestoryboardDavis walker clint-visual_resumestoryboard
Davis walker clint-visual_resumestoryboardCDWfullsail
 
Vuvera 2012 - 2013
Vuvera 2012 - 2013Vuvera 2012 - 2013
Vuvera 2012 - 2013Suzan Numan
 
Continuous Improvement thruogh Knowledge Management, Social Learning and Coll...
Continuous Improvement thruogh Knowledge Management, Social Learning and Coll...Continuous Improvement thruogh Knowledge Management, Social Learning and Coll...
Continuous Improvement thruogh Knowledge Management, Social Learning and Coll...Andrew Muras, PMP
 
Final projMARKET RESEARCH OF NEW PRODUCTect doc
Final projMARKET RESEARCH OF NEW PRODUCTect docFinal projMARKET RESEARCH OF NEW PRODUCTect doc
Final projMARKET RESEARCH OF NEW PRODUCTect docPiyush Sakhiya
 

En vedette (7)

Ci through collaboration and km
Ci through collaboration and kmCi through collaboration and km
Ci through collaboration and km
 
G7 mfl c night info 2012-2013
G7 mfl c night info 2012-2013  G7 mfl c night info 2012-2013
G7 mfl c night info 2012-2013
 
Davis walker clint-visual_resumestoryboard
Davis walker clint-visual_resumestoryboardDavis walker clint-visual_resumestoryboard
Davis walker clint-visual_resumestoryboard
 
Davis walker clint-visual_resumestoryboard
Davis walker clint-visual_resumestoryboardDavis walker clint-visual_resumestoryboard
Davis walker clint-visual_resumestoryboard
 
Vuvera 2012 - 2013
Vuvera 2012 - 2013Vuvera 2012 - 2013
Vuvera 2012 - 2013
 
Continuous Improvement thruogh Knowledge Management, Social Learning and Coll...
Continuous Improvement thruogh Knowledge Management, Social Learning and Coll...Continuous Improvement thruogh Knowledge Management, Social Learning and Coll...
Continuous Improvement thruogh Knowledge Management, Social Learning and Coll...
 
Final projMARKET RESEARCH OF NEW PRODUCTect doc
Final projMARKET RESEARCH OF NEW PRODUCTect docFinal projMARKET RESEARCH OF NEW PRODUCTect doc
Final projMARKET RESEARCH OF NEW PRODUCTect doc
 

Similaire à Tech talk

iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdfSudhanshiBakre1
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3DHIRAJ PRAVIN
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Aravindharamanan S
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 

Similaire à Tech talk (20)

iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Android session-5-sajib
Android session-5-sajibAndroid session-5-sajib
Android session-5-sajib
 
G pars
G parsG pars
G pars
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Lecture10
Lecture10Lecture10
Lecture10
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Dernier

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 

Dernier (20)

Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Tech talk

  • 1. Android- Make It Simple -by Preeti Patwa
  • 2. Agenda 1. Simple Framework to serialize xml into java object. 2. Android Process and Thread model. 3. AsyncTask- best practices. 4. Volley framework for networking. 5. Demo of Running debugger in eclipse.
  • 3. Simple Framework Simple is a high performance XML serialization and configuration framework for Java. Its goal is to provide an XML framework that enables rapid development of XML configuration and communication systems. It offers full object serialization and deserialization, maintaining each reference encountered.  Serialize - The process of translating data structures or object state into a format that can be stored.(eg. java object to xml )  Deserialize – The opposite operation, extracting a data structure from a series of bytes.(eg. Xml data to java object)
  • 4. Simple Framework : Deserializing xml to java object  The persister is given the class representing the serialized object and the source of the XML document. To deserialize the object the read method is used, which produces an instance of the annotated object. Eg  Xml file - <root id="123"><message>Example message</message></root>  Annotated class representing the serialized object @Root(name="root") public class Example {
  • 5. Simple Framework : Deserialization cont... @Element(name="message") private String text; @Attribute(name="id", required = false) private int index; public String getMessage() { return text; } public int getId() { return index; }}  Deserializing the object - Serializer serializer = new Persister(); File source = new File("example.xml"); Example example = serializer.read(Example.class, source);
  • 6. Simple Framework : Basic Annotation-  Reading root element @Root, (name=”*”,required=true| false)  Reading attributes @Attribute(name=”*”,required=true| false)  Reading a list of elements @ElementList(inline=true)  Reading an array of elements @ElementArray  Reading an ElementMap eg. <element key=”x”>abc</element> @ElementMap(entry="element", key="key", attribute=true)
  • 7. Simple Framework : Basic Annotation Cont...  Default object serialization @Default(DefaultType.FIELD| DefaultType.PROPERTY)  Serializing with CDATA blocks @Element(Data=true)  Using XML namespaces @Namespace(reference="http://test/test1", prefix="pre")  Other Libraries to serialize objects to XML and back again: XStream and JIBX.  To know more visit: http://simple.sourceforge.net/
  • 8. Android Process and Thread Model  Process : A running instance of a program is called Process.By default, all components of the same application run in the same process.  Component of aplicationce can customize which process it belongs to by giving android:process attribute in the corresponding entry of manifenst file  Process lifecycle is maintained using importance hierarchy- 1. Foreground Process – activity having focus, services bound to an activity, or services in onStart(), onDestroy(), onCreate() or services start with startForeground() method.
  • 9. Process Cont... 2.Visible Process - activity not foreground but still active usually when onPause() is called 3.Services Process – services started with startService() method as audio player. 4.Background Process - A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called). 5.Empty Process - It doesn't hold any active application components, used for caching purposes, to improve startup time the next time a component needs to run in it.
  • 10. Threads :  Thread is a basic unit of CPU utilization.  When an application is launched, the system creates a thread of execution for the application, called "main” or UI-thread.  All components that run in the same process are instantiated in the UI thread.  It is in charge of dispatching events to the appropriate user interface widgets.  If everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI.
  • 11. Thread Cont...  When the thread is blocked, no events can be dispatched, including drawing events. From the user's perspective, the application appears to hang.  If the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog. **BAD USER EXPERIENCE**  Two rules to Android's single thread model: 1.Do not block the UI thread 2.Do not access the Android UI toolkit from outside the UI thread.
  • 12. Thread Cont... public void onClick(View v) { new Thread(new Runnable() { public void run() { //1. Do networking or Database task //2. goback to UI thread for UI updation //2.1 - Activity.runOnUiThread(Runnable) //2.2 - View.post(Runnable) //2.3 - View.postDelayed(Runnable, long) //2.4 – Use Handler } }).start(); }
  • 14. View.post Or VIew.postDelayed  demoImageView.post(new Runnable() { public void run() { demoImageView.setImageBitmap(bitmap); } });  View.onPostDelayed(Runnable r, long millisec) call the runnable after the time specified.
  • 16. Handler :  The Handler is the middleman between a new thread and the message queue.  A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue, (Thread that create it).  Message : Defines a message containing a description and arbitrary data object that can be sent to a Handler.(may contain 2 int, 1 object)  MessageQueue : Low-level class holding the list of messages to be dispatched by a Looper
  • 17. Handler Cont...  There are two main uses for a Handler (1) to schedule messages and runnables to be executed as some point in the future (2) to enqueue an action to be performed on a different thread than your own.  Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods.
  • 18. Handler :  The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received;  The sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler).ons allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler).
  • 19. Handler : Using MessageQueue final Handler myHandler = new Handler(){ @Override public void handleMessage(Message msg) { updateUI((String)msg.obj);} }; (new Thread(new Runnable() { @Override public void run() { Message msg = myHandler.obtainMessage(); msg.obj = doLongOperation(); myHandler.sendMessage(msg); } })).start();
  • 20. Handler : Using Runnable  final Handler myHandler = new Handler(); (new Thread(new Runnable() { @Override public void run() { final String res = doLongOperation(); myHandler.post(new Runnable() { @Override public void run() { updateUI(res);} }); })).start();
  • 21. AsyncTask :  android.os.AsyncTask<Params, Progress, Result>  An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.  Helper class around Thread and Handler  The three generic types used by an asynchronous task are the following: 1.Params - type of the parameters sent to the task upon execution. 2.Progress, the type of the progress units published during the background computation. 3.Result, the type of the result of the background computation.
  • 22. AsyncTask Cont...  AsyncTask must be subclassed to be used.  Main Methods to be overridden- 1. doInBackground(Params...) *//time consuming operation 2. onPostExecute(Result...)//run on ui thread after doInBackground 3.onPreExecute() //run on ui thread before doInBackground() 4.onCancelled(Result result) run On ui thread after cancel
  • 23. AsyncTask cont... 5.onProgressUpdate(Progress...values) .  Running AsyncTask - MyAsyncTask myAsyncTask = new MyAsyncTask(); myAsyncTask.execute();  Cancelling AsyncTask - myAsyncTask.cancel(true); //now onCancelled() will be called instead of onPostExecute() , keep on checking isCancelled() method in doInBackground inside a loop and break if it is true.
  • 24. AsyncTask : Order Of Execution (troll)  Depends on API level 1. When it first appeared in Cupcake (1.5) it handled background operations with a single additional thread (one by one). 2. In Donut (1.6) it was changed, so that a pool of thread had begun to be used. And operations could be processed simultaneously until the pool had been exhausted. In such case operations were enqueued.
  • 25. AsyncTask : Order Of Execution (troll)  Depends on API level 1. When it first appeared in Cupcake (1.5) it handled background operations with a single additional thread (one by one). 2. In Donut (1.6) it was changed, so that a pool of thread had begun to be used. And operations could be processed simultaneously until the pool had been exhausted. In such case operations were enqueued.
  • 27. AsyncTask : Order Of Execution Cont. 3.Since Honeycomb default behavior is switched back to use of a single worker thread (one by one processing). But the new method (executeOnExecutor) is introduced to give you a possibility to run simultaneous tasks if you wish (there two different standard executors: SERIAL_EXECUTOR and THREAD_POOL_EXECUTOR).  The way how tasks are enqueued also depends on what executor you use. In case of a parallel one you are restricted with a limit of 10 (new LinkedBlockingQueue<Runnable>(10)). In case of a serial one you are not limited (new ArrayDeque<Runnable>()).
  • 28. AsyncTask Cont...  If there are less than core pool size threads currently active and a new job comes in, the executor will create a new thread and execute it immediately.  If there are at least core pool size threads running, it will try to queue the job and wait until there is an idle thread available  If it is not possible to queue the job (the queue can have a max capacity), it will create a new thread (upto maximum pool size threads) for the jobs to run in. Non-core idle threads can eventually be decommissioned according to a keep-alive timeout parameter.
  • 29. AsyncTask cont...  Before Android 1.6, the core pool size was 1 and the maximum pool size was 10. Since Android 1.6, the core pore size is 5, and the maximum pool size is 128. The size of the queue is 10 in both cases. The keep-alive timeout was 10 seconds before 2.3, and 1 second since then.  This is a very good reason why you should not use AsyncTasks for long-running operations - it will prevent other AsyncTasks from ever running.
  • 30. AsyncTask cont...  Before Android 1.6, the core pool size was 1 and the maximum pool size was 10. Since Android 1.6, the core pore size is 5, and the maximum pool size is 128. The size of the queue is 10 in both cases. The keep-alive timeout was 10 seconds before 2.3, and 1 second since then.  This is a very good reason why you should not use AsyncTasks for long-running operations - it will prevent other AsyncTasks from ever running.
  • 31. AsyncTask cont...  Before Android 1.6, the core pool size was 1 and the maximum pool size was 10. Since Android 1.6, the core pore size is 5, and the maximum pool size is 128. The size of the queue is 10 in both cases. The keep-alive timeout was 10 seconds before 2.3, and 1 second since then.  This is a very good reason why you should not use AsyncTasks for long-running operations - it will prevent other AsyncTasks from ever running.
  • 32. AsyncTask Cont... public static void execute(AsyncTask as) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR1) { as.execute(); } else { as.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }
  • 33. Volley : Design Tradeoff Volley is a library that makes networking for Android apps easier and most importantly, faster. 1. Great for RPC – style operation that populate the UI. 2. Fine for background RPC. 3. Terrible for large payloads.
  • 34. Volley Network Framework : private RequestQueue mRequestQueue; mRequestQueue = Volley.newRequestQueue(this); JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.i(TAG,response.toString()); parseJSON(response); va.notifyDataSetChanged(); pd.dismiss();
  • 35. Debugging Using Eclipse Debugging :  The process of identifying and fixing errors in software  Mainly used to describe run-time errors or incorrect results
  • 36. Eclipse Debugging Features  Breakpoints  Step into  Step over  Step return  Step Filters  Watches  Run to line  Suspend/Resume/Terminate
  • 37. Breakpoints  Breakpoints cause the thread of execution to suspend and return to the debugger  Setting breakpoints in Eclipse is easy, just double-click the left margin
  • 38. Step Into  Executes single (highlighted) statement  If statement contains call to method, it steps into the method  To use:  Must be in Debug Perspective  Click from Debug Toolbar or press F5
  • 39. Step Over  Executes single (highlighted) statement  If statement contains method call, the entire method is executed without stepping through it  To use:  Must be in Debug Perspective  Click from Debug toolbar or press F6
  • 40. Step Return  All statements in current method are executed  Return to where method was called  To use:  Must be in Debug Perspective  Click from Debug toolbar or press F7
  • 41. Step with Filters  User can specify which methods Step Filter will execute and return from  Usually you would want steps to be made only into methods of your own classes  To set filters:  Go through Window > Preferences > Java > Debug > Step Filtering
  • 42. Watches  Watches allow you to view (and sometimes change) the value of a variable during execution  In Eclipse, watches are set automatically on variables in scope  Watches can be found in the Eclipse Debug perspective in the “Variables” window  Eclipse allows you to change the value of variables dynamically during runtime
  • 43. Run to Line  Equivalent to setting a temporary breakpoint  CTRL+R
  • 44. Suspend/Resume/Terminate  Suspend pauses the current thread of execution and breaks into the debugger  Resume resumes a suspended application  Terminate stops the program and debugging process  Hot Code Replace – supported by eclipse but not by DVM.
  • 45. Demo