Showing posts with label Android Interview questions. Show all posts
Showing posts with label Android Interview questions. Show all posts

Monday, 30 May 2016

Android Interview Questions and Answers -Part 2

1)Difference between listview and recyclerview 

i) ViewHolder Pattern

In a ListView, it was recommended to use the ViewHolder pattern but it was never a compulsion. In case of RecyclerView, this is mandatory using the RecyclerView.ViewHolder class. This is one of the major differences between the ListView and the RecyclerView.

It makes things a bit more complex in RecyclerView but a lot of problems that we faced in the ListView are solved efficiently.

Reuse cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

ii) LayoutManager

This is another massive enhancement brought to the RecyclerView. In a ListView, the only type of view available is the vertical ListView. There is no official way to even implement a horizontal ListView.

Now using a RecyclerView, we can have a

i) LinearLayoutManager - which supports both vertical and horizontal lists,

ii) StaggeredLayoutManager - which supports Pinterest like staggered lists,

iii) GridLayoutManager - which supports displaying grids as seen in Gallery apps.

And the best thing is that we can do all these dynamically as we want.

iii) Item Animator

ListViews are lacking in support of good animations, but the RecyclerView brings a whole new dimension to it. Using the RecyclerView.ItemAnimator class, animating the views becomes so much easy and intuitive.

iv) Item Decoration

In case of ListViews, dynamically decorating items like adding borders or dividers was never easy. But in case of RecyclerView, the RecyclerView.ItemDecorator class gives huge control to the developers but makes things a bit more time consuming and complex.

v) OnItemTouchListener

Intercepting item clicks on a ListView was simple, thanks to its AdapterView.OnItemClickListener interface. But the RecyclerView gives much more power and control to its developers by the RecyclerView.OnItemTouchListener but it complicates things a bit for the developer.

In simple words, the RecyclerView is much more customizable than the ListView and gives a lot of control and power to its developers.


What is final in Java? 

Final in java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase performance of Java application.

What is final keyword in Java?

Final keyword, final variable, final method and class in java exampleFinal is a keyword or reserved word in java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise compilation error if you try to re-initialized final variables in java.

What is final variable in Java?
Any variable either member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant. Here is an example of final variable in Java

public static final String LOAN = "loan";
LOAN = new String("loan") //invalid compilation error

Final variables are by default read-only.


What is final method in Java
Final keyword in java can also be applied to methods. A java method with final keyword is called final method and it can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time. Here is an example of final method in Java:

class PersonalLoan{
 public final String getName(){
     return "personal loan";
 }
}
class CheapPersonalLoan extends PersonalLoan{
    @Override
    public final String getName(){
        return "cheap personal loan"; //compilation error: overridden method is final
    }
}

What is final Class in Java

Java class with final modifier is called final class in Java. Final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes. Here is an example of final class in java

final class PersonalLoan{

}

class CheapPersonalLoan extends PersonalLoan{  //compilation error: cannot inherit from final class

}

Benefits of final keyword in Java

Here are few benefits or advantage of using final keyword in Java:

1. Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.

2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.

3. Final keyword allows JVM to optimized method, variable or class.


Final and Immutable Class in Java

Final keyword helps to write immutable class. Immutable classes are the one which can not be modified once it gets created and String is primary example of immutable and final class which I have discussed in detail on Why String is final or immutable in Java. Immutable classes offer several benefits one of them is that they are effectively read-only and can be safely shared in between multiple threads without any synchronization overhead. You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in java.

Example of Final in Java

Java has several system classes in JDK which are final, some example of final classes are String, Integer, Double and other wrapper classes. You can also use final keyword to make your code better whenever it required. See relevant section of java final tutorial for example of final variable, final method and final class in Java.

Important points on final in Java

1. Final keyword can be applied to member variable, local variable, method or class in Java.
2. Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.

3. You can not reassign value to final variable in Java.

4. Local final variable must be initializing during declaration.

5. Only final variable is accessible inside anonymous class in Java.

6. Final method can not be overridden in Java.

7. Final class can not be inheritable in Java.

8. Final is different than finally keyword which is used on Exception handling in Java.

9. Final should not be confused with finalize() method which is declared in object class and called before an object is garbage collected by JVM.

10. All variable declared inside java interface are implicitly final.

11. Final and abstract are two opposite keyword and a final class can not be abstract in java.

12. Final methods are bonded during compile time also called static binding.

13. Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".

14. Making a class, method or variable final in Java helps to improve performance because JVM gets an opportunity to make assumption and optimization.

15. As per Java code convention final variables are treated as constant and written in all Caps e.g.

private final int COUNT=10;

16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection. For example:

private final List loans = new ArrayList();
loans.add(“home loan”);  //valid
loans.add("personal loan"); //valid
loans = new Vector();  //not valid

That’s all on final in Java. We have seen what final variable, final method is and final class in Java and what does those mean. In Summary whenever possible start using final in java it would result in better and faster code.

Difference between Hashtable and HashMap in Java

Hashtable vs HashMap in Java
Hashtable and HashMap are two hash based collection in Java and used to store objects as key value pair. Despite being hash based and similar in functionality there are a significant difference between Hashtable and HashMap and without understanding those difference if you use Hashtable in place of HashMap than you may run into series of subtle programs which is hard to find and debug.Unlike Difference between ArrayList and HashMap,  Difference between Hashtable and HashMap are more subtle because both are similar kind of collection. Before seeing difference between HashMap and Hashtable let's see some common things between HashMap and Hashtable in Java.



Similarities between Hashtable and HashMap in Java
There are lot of similar things between Hashtable and HashMap in Java which is good to know and these also helps to find exactly what is different between HashMap and Hashtable in Java:

1) Both Hashtable and HashMap implements java.util.Map interface.
2) Hashtable and HashMap both are a hash based collection and works on the principle of hashing.
3) Hashtable and HashMap both provide constant time performance for put and get method if objects are distributed uniformly across bucket.
4) From JDK 4 both Hashtable and HashMap are part of Java collection framework.

Difference between Hashtable and HashMap in Java
What is Difference between HashMap and Hashtable in Java CollectionDespite being so similar there are some differences between Hashtable and HashMap in Java which separates them completely, let's have a look :
1) First and most significantly different between Hashtable and HashMap are that HashMap is not thread-safe  while Hashtable is a thread-safe collection.

2) The second important difference between Hashtable and HashMap is performance since HashMap is not synchronized it perform better than Hashtable.

3) The third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.

These were some important difference on Hashtable and HashMap in Java. If you know any other difference which is not included here then feels free to add them in the comment section. Remember this is an important question on Java interview and good to prepare it well.

AIDL

Each Android app run in it’s own process. So one application can’t directly access another app’s memory space. If you want to access some data from one application to another application, then we need to use  inter process communication (IPC) like other platforms. So in Android IPC is otherwise known as AIDL. For this purpose Android provides a technique called Android Interface Definition Language (AIDL). It is a lightweight implementation of IPC just like C/C++ languages.

So to communicate between process or you say between applications, we need to implement AIDL in our Android application. In other words you can say the AIDL technique is a light weighted client server architecture in form of a service, which helps multiple applications to communicate between them self.  To do so we need the below steps.

1. AIDL interface- Define a AIDL interface which will be the interface between your applications.
2. Implement the the remote service- Remote service holds your data/method to expose to other applications for accessing data.

3. Expose the remote service to other local clients- The data/method we need to share with other applications needs to be expose so that other application can access and share data from the remote service.


Java - How to use Singleton Class ?
The Singleton's purpose is to control object creation, limiting the number of obejcts to one only. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources.

Example 
// File Name: Singleton.java
public class Singleton {

   private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}
Here is the main program file where we will create singleton object:



// File Name: SingletonDemo.java
public class SingletonDemo {
   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}

Difference between Singleton Pattern vs Static Class in Java

 similarities 
both can be used without creating object
both provide only one instance

1)Why you use Singleton instead of Static Methods?
2)Can you replace Singleton with static class?
3)what are differences between Singleton pattern and static in Java?

static class is a Java class, which only contains static methods

While Singleton classes are those, which has only one instance during application life cycle 

1) Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.

2) One more difference between Singleton and static is, ability to override. Since static methods in Java cannot be overridden, they leads to inflexibility. On the other hand, you can override methods defined in Singleton class by extending it.

3) Static classes are hard to mock and consequently hard to test than Singletons, which are pretty easy to mock and thus easy to test. It’s easier to write JUnit test for Singleton than static classes, because you can pass mock object whenever Singleton is expected, e.g. into constructor or as method arguments.

4) If your requirements needs to maintain state than Singleton pattern is better choice than static class, because
maintaining  state in later case is nightmare and leads to subtle bugs.

5) Singleton classes can be lazy loaded if its an heavy object, but static class doesn't have such advantages and always eagerly loaded.

6) Many Dependency Injection framework manages Singleton quite well e.g. Spring, which makes using them very easy.

These are some differences between static class and singleton pattern, this will help to decide between two, which situation arises. In next section we will when to choose Singleton pattern over static class in Java.


Main advantage of Singleton over static is that former is more object oriented than later. With Singleton, you can use Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. If we talk about java.lang.Runtime, which is a Singleton in Java, call to getRuntime() method return different implementations based on different JVM, but guarantees only one instance per JVM, had java.lang.Runtime an static class, it’s not possible to return different implementation for different JVM.

That’s all on difference between Singleton and static class in Java. When you need a class with full OO capability , chose Singleton, while if you just need to store bunch of static methods together, than use static class.

What is Singleton class? Have you used Singleton before?

Singleton is a class which has only one instance in whole application and provides a getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.


Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?

Here they check whether candidate has enough experience on usage of singleton or not. Does he is familiar of advantage/disadvantage or alternatives available for singleton in Java or not.

Answer : Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class , since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility classes like Popup in GUI application, if you want to show popup with message you can have one PopUp class on whole GUI application and anytime just get its instance, and call show() with message.


Can you write code for getInstance() method of a Singleton class in Java?

Most of the java programmer fail here if they have mugged up the singleton code because you can ask lots of follow-up question based upon the code they have written. I have seen many programmer write Singleton getInstance() method with double checked locking but they are not really familiar with the caveat associated with double checking of singleton prior to Java 5.

Answer : Until asked don’t write code using double checked locking as it is more complex and chances of errors are more but if you have deep knowledge of double checked locking, volatile variable and lazy loading than this is your chance to shine. I have shared code examples of writing singleton classes using enum, using static factory and with double checked locking in my recent post Why Enum Singletons are better in Java, please see there.

Singleton design pattern Interview Questions in Java


Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer?

This is really nice question and I mostly asked to just quickly check whether candidate is aware of performance trade off of unnecessary locking or not. Since locking only make sense when we need to create instance and rest of the time its just read only access so locking of critical section is always better option. read more about synchronization on How Synchronization works in Java
Answer : This is again related to double checked locking pattern, well synchronization is costly and when you apply this on whole method than call to getInstance() will be synchronized and contented. Since synchronization is only needed during initialization on singleton instance, to prevent creating another instance of Singleton, It’s better to only synchronize critical section and not whole method. Singleton pattern is also closely related to factory design pattern where getInstance() serves as static factory method.



What is lazy and early loading of Singleton and how will you implement it?

This is another great Singleton interview question in terms of understanding of concept of loading and cost associated with class loading in Java. Many of which I have interviewed not really familiar with this but its good to know concept.

Answer : As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.



Give me some examples of Singleton pattern from Java Development Kit?

This is open question to all, please share which classes are Singleton in JDK. Answer to this question is java.lang.Runtime
Answer : There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:
Java.lang.Runtime with getRuntime() method 
Java.awt.Toolkit with getDefaultToolkit() 
Java.awt.Desktop with getDesktop() 



What is double checked locking in Singleton?

One of the most hyped question on Singleton pattern and really demands complete understanding to get it right because of Java Memory model caveat prior to Java 5. If a guy comes up with a solution of using volatile keyword with Singleton instance and explains it then it really shows it has in depth knowledge of Java memory model and he is constantly updating his Java knowledge.

Answer : Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization. See here to learn more about double-checked-locking in Java. 

public static Singleton getInstance(){
     if(_INSTANCE == null){
         synchronized(Singleton.class){
         //double checked locking - because second check of Singleton instance with lock
                if(_INSTANCE == null){
                    _INSTANCE = new Singleton();
                }
            }
         }
     return _INSTANCE;
}

Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.



How do you prevent for creating another instance of Singleton using clone() method?

This type of questions generally comes some time by asking how to break singleton or when Singleton is not Singleton in Java.

Answer : Preferred way is not to implement Cloneable interface as why should one wants to create clone() of Singleton and if you do just throw Exception from clone() method as “Can not create clone of Singleton class”.



How do you prevent for creating another instance of Singleton using reflection?

Open to all. In my opinion throwing exception from constructor is an option.
Answer: This is similar to previous interview question. Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”



How do you prevent for creating another instance of Singleton during serialization?

Another great question which requires knowledge of Serialization in Java and how to use it for persisting Singleton classes. This is open to you all but in my opinion use of readResolve() method can sort this out for you.
Answer: You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance. I have shared code on how to do it in my post Enum as Singleton in Java. This is also one of the reason I have said that use Enum to create Singleton because serialization of enum is taken care by JVM and it provides guaranteed of that.


When is Singleton not a Singleton in Java?

There is a very good article present in Sun's Java site which discusses various scenarios when a Singleton is not really remains Singleton and multiple instance of Singleton is possible. 


Apart from these questions on Singleton pattern, some of my reader contribute few more questions, which I included here. Thank you guys for your contribution.


Why you should avoid the singleton anti-pattern at all and replace it with DI?

Answer : Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container.


Why Singleton is Anti pattern 

With more and more classes calling getInstance() the code gets more and more tightly coupled, monolithic, not testable and hard to change and hard to reuse because of not configurable, hidden dependencies. Also, there would be no need for this clumsy double checked locking if you call getInstance less often (i.e. once).


How many ways you can write Singleton Class in Java?

Answer : I know at least four ways to implement Singleton pattern in Java
Singleton by synchronizing getInstance() method
Singleton with public static final field initialized during class loading.
Singleton generated by static nested class, also referred as Singleton holder pattern.
From Java 5 on-wards using Enums


How to write thread-safe Singleton in Java?

Answer : Thread safe Singleton usually refers to write thread safe code which creates one and only one instance of Singleton if called by multiple thread at same time. There are many ways to achieve this like by using double checked locking technique as shown above and by using Enum or Singleton initialized by class loader.






Thursday, 14 January 2016

Web Services in Android

What is Web Service?

A web service is a standard used for exchanging information between applications or systems of heterogeneous type. Software applications written in various programming languages and running on various platforms can use web services to exchange information over Internet using http protocol.
This inter-operability can be achieved between Java and Dot net applications, or PHP and Java applications.

Why Web Service?

Here are the reasons for using Web Service:

Expose method as a service over network:
Web service is a chunk of code written in some programming language (Say C# or Java) that can be invoked remotely through http protocol. Once the Web methods are exposed publically, any applications can invoke it and use the functionality of the web methods.

Application Inter-operability – Connect heterogeneous applications:
With the help of web service, heterogeneous applications (Java and Dot Net / Java and PHP application) can communicate with each other. Web service written in Java can be invoked from PHP by passing the required parameters to web methods. This makes the applications platform and technology independent.

Standardized protocol:
Web Services uses standardized industry standard protocol for the communication which must be adhered and followed by the applications creating Web Service.  
                                                     
Cost effective communication:
Web service is using SOAP over HTTP protocol for communication which is much cheaper than systems.

What is the need of using Web Service in Android applications?

Existing Web applications are in a need of creating mobile applications to show their presence in mobile platform as well. Almost all web applications are having their Mobile applications created in Android, IOS or Windows platform.

Exposing the existing functionalities of the applications is bit tough as all the functionalities have to re-written in the respective platforms.

But it can be easily achieved with much ease by creating Web Service and expose the existing functionalities as web methods to Mobile platforms.

Here are the few advantages of using Web Service in Android:

Make client more lightweight:
Adding a web service layer makes the client more lightweight, both in terms of the required CPU power and the bandwidth used during the processing. Most of the processing to be done in client end can be separated and put inside a web service layer which will be extremely helpful for end-users in terms of:
Using less CPU increases the battery life
Using less bandwidth reduces monthly payments over data charge.

Re-usage of existing functionalities:
While designing the web service, we could also get significant benefits by reusing the existing functionalities by exposing them as web methods.

Remote DB hit made simple:
DB residing remotely can be hit from inside Android applications through Web Service calls.
Making Web Service call from Android applications allows us to add functionality outside the scope of a DB like caching data, applying business rules over the data etc.,

Types of web services.

1) xml
2) json
3) soap
3) rest

Which one is better XML or JSON ?

XML and JSON both are the data interchange formats accessed over WEB. Both of these formats have their own pros/cons. No one is replacement of other. Use the right tool for the right job.

XML: Extensible Markup Language

1. An open standard for describing data defined by the World Wide Web Consortium (W3C).

2. XML lets Web developers and designers create customized tags that offer greater flexibility in organizing and presenting information.

3. XML defines rules to mark-up a document in a way that allows the author to express semantic meaning in the mark-up. XML does not necessarily restrict the author to certain tags (elements) as HTML does.

4. Internet media type: application/xml

JSON: JavaScript Object Notation

1. A lightweight text-based open standard designed for human-readable data interchange.

2. A text-based format for exchanging objects.

3. It is an alternative to XML that is more concise because, unlike XML,  it is not a markup language that requires open and close tags.

4. It is derived from the object literals of JavaScript.

5. Design goals were for it to be minimal, portable, textual, and a subset of JavaScript.

6. Internet media type: application/json


JSON is built on two structures:

1. A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

2. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Below are the differences between XML and JSON.

XML vs JSON

1.  JSON format is lightweight over XML.

2. JSON is recognized natively by JavaScript.

3. JSON can contain integers, strings, lists, arrays. XML is just elements and nodes that need to be parsed into integers and so on before it can be consumed.

4. The most important disadvantage of JSON is that the format is very hard to read for humans, and that, of course,    every single comma, quote, and bracket should be in exactly the correct place. While this is also true of XML, JSON’s welter of complicated-looking syntax, like the }}]} at the end of the data snippet, may frighten the newbies and make for complicated debugging.

5. Serialization format for your data, JSON is smaller, lighterweight and generally faster than XML.

6. JSON is best for consumption of data in web applications from webservices for its size and ease of use, especially due to the built-in support in JavaScript.
Imagine the computation overhead for parsing an xml fragment compared to the instant lookup in JSON.

7. XML is still great. JSON’s just the “latest and greatest” compared to XML.

8. For configurations file XML is better choice to make because it more human readable.

9. A browser JSON is faster to serialize/deserialize as it’s simpler, more compact and more importantly natively supported.

10. XML is document-oriented. JSON is data-oriented. JSON can be mapped more easily to object-oriented systems.

11. XML and JSON both use Unicode.That help in support for internationalization.

12. JSON does not have afeature, so it is not well suited to act as a carrier of sounds or images or other large binary payloads. JSON is optimized for data.

13. XML documents can contain any imaginable data type – from classical data like text and numbers, or multimedia objects such as sounds, to active formats like Java applets or ActiveX components.

14. JSON is a better data exchange format. XML is a better document exchange format. Use the right tool for the right job.

15. XML requires translating the structure of the data into a document structure. This mapping can be complicated. JSON structures are based on arrays and records. That is what data is made of. XML structures are based on elements (which can be nested), attributes (which cannot), raw content text, entities, DTDs, and other meta structures.

16. JSON is not extensible because it does not need to be. JSON is not a document markup language, so it is not necessary to define new tags or attributes to represent data in it.

Summary:

1. For Data delivery between servers and browsers, JSON is better choice.
2. For storing Information in configuration files on the server side, XML is better choice.
3. On Browser Side: The speed and ease with which JSON is parsed and the ease of simple data          retrieval from JavaScript object; makes JSON is a better choice.
4. Server Side: The querying data and format changes; makes XML a better choice.

Querying data: Using XPath, it’s possible to get direct access to a part of multiple parts of an XML data structure; no such interface exists for JSON. To get data from a JSON structure, you must know exactly where it is or else iterate over everything until you find it.

Format changes: You have your data in one format but you want it in another. If the data is in XML, you can write an XSLT template and run it over the XML to output the data into another format: HTML, SVG, plain text, comma-delimited, even JSON. When you have data in JSON, it’s pretty much stuck there. There’s no easy way to change it into another data format.

5. Security: JSON is less secure because of absence of JSON parser in the Browser; only way is to use eval() function. For security reasons on the browser side XML is better choice.

6. To extract data from database; XML is the only choice.

Below is the example:
I used to explain each one’s usage in the Browser. This usage will also show you which one is easy to use on the browser side.

Example Data Operations:

XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <data>
        <id>1</id>                   
        <name>PHP </name>
    </data>
    <data>
        <id>2</id>                   
        <name>Table of Contents</name>
    </data>
<root>

JSON

 {
                "data": [
                           {
                                "id" :    "1",
                                "name" :    "PHP"                           
                            },
                            {
                                "id" :    "2",
                                "name" :    "Table of Contents"
                            }
]}



What is REST ?

REST describes a set of architectural principles by which data can be transmitted over a standardized interface (such as HTTP). The acronym REST stands for Representational State Transfer, this basically means that each unique URL is a representation of some object.
REST asks developers to use HTTP methods explicitly and in a way that’s consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping:
To create a resource on the server, use POST.
To retrieve a resource, use GET.
To change the state of a resource or to update it, use PUT.
To remove or delete a resource, use DELETE.

Advantages of using RESTful webservice:

RESTful Web services are designed with less dependence on proprietary middleware (for example, an application server) than the SOAP- and WSDL-based kind.

As per the RESTful interface design, XML or JSON over HTTP is a powerful interface that allows internal applications, such as Asynchronous JavaScript + XML/JSON (Ajax)-based custom user interfaces, to easily connect, address, and consume resources.

The great fit between Ajax and REST has increased the amount of attention REST is getting these days.

Exposing a system’s resources through a RESTful API is a flexible way to provide different kinds of applications with data formatted in a standard way. It helps to meet integration requirements that are critical to building systems where data can be easily combined (mashups) and to extend or build on a set of base, RESTful services into something much bigger.

What is SOAP?
SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate operating systems (such as Windows and Linux) to communicate using Hypertext Transfer Protocol (HTTP) and its Extensible Markup Language (XML).

SOAP defines the XML-based message format that Web service-enabled applications use to communicate and inter-operate with each other over the Web. The heterogeneous environment of the Web demands that applications support a common data encoding protocol and message format. SOAP is a standard for encoding messages in XML that invoke functions in other applications.

SOAP:
Pros:
Langauge, platform, and transport agnostic
Designed to handle distributed computing environments
Is the prevailing standard for web services, and hence has better support from other standards (WSDL, WS-*) and tooling from vendors
Built-in error handling (faults)
Extensibility

Cons:
Conceptually more difficult, more "heavy-weight" than REST
More verbose
Harder to develop, requires tools

REST
Pros:
Language and platform agnostic
Much simpler to develop than SOAP
Small learning curve, less reliance on tools
Concise, no need for additional messaging layer
Closer in design and philosophy to the Web.

Cons:
Assumes a point-to-point communication model--not usable for distributed computing environment where message may go through one or more intermediaries
Lack of standards support for security, policy, reliable messaging, etc., so services that have more sophisticated requirements are harder to develop ("roll your own")
Tied to the HTTP transport model.

SOAP vs REST 

Difference between Stack Overflow error and Out of memory error in android?

Difference between Stack Overflow  error and  Out of memory error in android?

When you start JVM you define how much RAM it can use use for processing. JVM divides this into certain memory locations for its processing purpose, two of those are Stack & Heap.

Out of memory error  is related to Heap. If you have large objects (or) referenced objects in memory, then you will see Out of memory error . If you have strong references to objects, then GC can't clean the memory space allocated for that object. When JVM tries to allocate memory for new object and not enough space available it throws Out of memory error because it can't allocate required amount of memory.

How to avoid: Make sure unnecessary objects are available for GC.

Stack Overflow  error is related to stack. All your local variables and methods calls related data will be on stack. For every method call one stack frame will be created and local as well as method call related data will be placed inside the stack frame. Once method execution is completed, stack frame will be removed. ONE WAY to reproduce this is, have infinite loop for method call, you will see Stack Overflow  error, because stack frame will be populated with method data for every call but it won't be freed (removed).

How to avoid:
Make sure method calls are ending (not in infinite loop).


Here are few differences between stack and heap memory in Java:

1) Main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable,  they are always created inside heap space in Java.

2) Each Thread in Java has there own stack which can be specified using -Xss JVM parameter, similarly you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of heap and -Xmx is maximum size of java heap.

3) If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space.

4) If you are using Recursion on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is lot lesser than size of  heap memory in Java.

5) Variables stored in stacks are only visible to the owner Thread, while objects created in heap are visible to all thread. In other words stack memory is kind of private memory of Java Threads, while heap memory is shared among all threads.

Difference between debug.apk and release.apk  android ?

The difference between debug and release builds is for example, that you can get the log output from the debug build but not from the release build.

Debug builds can be signed with the default keystore, the release builds have to be signed with your created keystore.

The Android build process signs your application differently depending on which build mode you use to build your application.

There are two build modes: debug mode and release mode.

You use debug mode when you are developing and testing your application.

You use release mode when you want to build a release version of your application that you can distribute directly to users or publish on an application marketplace such as Google Play.

When you build in debug mode the Android SDK build tools use the Keytool utility (included in the JDK) to create a debug key. Because the SDK build tools created the debug key, they know the debug key's alias and password. Each time you compile your application in debug mode, the build tools use the debug key along with the Jarsigner utility (also included in the JDK) to sign your application's .apk file. Because the alias and password are known to the SDK build tools, the tools don't need to prompt you for the debug key's alias and password each time you compile.

When you build in release mode you use your own private key to sign your application. If you don't have a private key, you can use the Keytool utility to create one for you. When you compile your application in release mode, the build tools use your private key along with the Jarsigner utility to sign your application's .apk file. Because the certificate and private key you use are your own, you must provide the password for the keystore and key alias.

The debug signing process happens automatically when you run or debug your application using Eclipse with the ADT plugin. Debug signing also happens automatically when you use the Ant build script with the debug option. You can automate the release signing process by using the Eclipse Export Wizard or by modifying the Ant build script and building with the release option.


Thursday, 24 September 2015

Building Apps with Over 65K Methods

As the Android platform has continued to grow, so has the size of Android apps. When your application and the libraries it references reach a certain size, you encounter build errors that indicate your app has reached a limit of the Android app build architecture.


About the 65K Reference Limit

Android application (APK) files contain executable byte code files in the form of Dalvik  Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536, including Android framework methods, library methods, and methods in your own code. Getting past this limit requires that you configure your app build process to generate more than one DEX file, known as a multidex configuration.

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can use the multidex support library, which becomes part of the primary DEX file of your app and then manages access to the additional DEX files and the code they contain.

Multidex support for Android 5.0 and higher

Android 5.0 and higher uses a runtime called ART which natively supports loading multiple dex files from application APK files. ART performs pre-compilation at application install time which scans for classes(..N).dex files and compiles them into a single .oat file for execution by the Android device. For more information on the Android 5.0 runtime, see Introducing ART.

Avoiding the 65K Limit


Before configuring your app to enable use of 65K or more method references, you should take steps to reduce the total number of references called by your app code, including methods defined by your app code or included libraries. The following strategies can help you avoid hitting the dex reference limit:
  • Review your app's direct and transitive dependencies - Ensure any large library dependency you include in your app is used in a manner that outweighs the amount of code being added to the application. A common anti-pattern is to include a very large library because a few utility methods were useful. Reducing your app code dependencies can often help you avoid the dex reference limit.
  • Remove unused code with ProGuard - Configure the ProGuard settings for your app to run ProGuard and ensure you have shrinking enabled for release builds. Enabling shrinking ensures you are not shipping unused code with your APKs.
Using these techniques can help you avoid the build configuration changes required to enable more method references in your app. These steps can also decrease the size of your APKs, which is particularly important for markets where bandwidth costs are high.

Configuring Your App for Multidex with Gradle


The Android plugin for Gradle available in Android SDK Build Tools 21.1 and higher supports multidex as part of your build configuration. Make sure you update the Android SDK Build Tools tools and the Android Support Repository to the latest version using the SDK Manager before attempting to configure your app for multidex.
Setting up your app development project to use a multidex configuration requires that you make a few modifications to your app development project. In particular you need to perform the following steps:
  • Change your Gradle build configuration to enable multidex
  • Modify your manifest to reference the MultiDexApplication class
Modify your app Gradle build file configuration to include the support library and enable multidex output, as shown in the following Gradle build file snippet:
public class App extends android.support.multidex.MultiDexApplication {
//your code here
}

Limitations of the multidex support library

The multidex support library has some known limitations that you should be aware of and test for when you incorporate it into your app build configuration:
  • The installation of .dex files during startup onto a device's data partition is complex and can result in Application Not Responding (ANR) errors if the secondary dex files are large. In this case, you should apply code shrinking techniques with ProGuard to minimize the size of dex files and remove unused portions of code.
  • Applications that use multidex may not start on devices that run versions of the platform earlier than Android 4.0 (API level 14) due to a Dalvik linearAlloc bug (Issue 22586). If you are targeting API levels earlier than 14, make sure to perform testing with these versions of the platform as your application can have issues at startup or when particular groups of classes are loaded. Code shrinking can reduce or possibly eliminate these potential issues.
  • Applications using a multidex configuration that make very large memory allocation requests may crash during run time due to a Dalvik linearAlloc limit (Issue 78035). The allocation limit was increased in Android 4.0 (API level 14), but apps may still run into this limit on Android versions prior to Android 5.0 (API level 21).
  • There are complex requirements regarding what classes are needed in the primary dex file when executing in the Dalvik runtime. The Android build tooling updates handle the Android requirements, but it is possible that other included libraries have additional dependency requirements including the use of introspection or invocation of Java methods from native code. Some libraries may not be able to be used until the multidex build tools are updated to allow you to specify classes that must be included in the primary dex file.