SlideShare una empresa de Scribd logo
1 de 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?

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Similar a Android XML to Java Objects

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
 

Similar a Android XML to Java Objects (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
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

Android XML to Java Objects

  • 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