Git basic commands

To view the git config settings

1) git config –list
2) git config user.name

Initializing a git repository and adding files
git init
git add .
git commit -m “comments”

Git pushing changes to an existing repository:
git remote add origin URL_OF_GIT_REPOSITORY
git push -u origin master

git log
git pull –rebase
git stash
git status

 

git discard all local changes/commits and pull from upstream

git reset --hard origin/master

git pull origin master

 

Tutorial : http://rogerdudler.github.io/git-guide/, http://kbroman.org/github_tutorial/pages/fork.html

Advertisements

Serialization in Java

Serialization enables us to represent an object as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Classes and methods for serialization:

ObjectOutputStream class contains many write methods for serializing an object.
public final void writeObject(Object x) throws IOException

Above method serializes an Object and sends it to the output stream.

ObjectInputStream class contains the following method for deserializing an object:
public final Object readObject() throws IOException, ClassNotFoundException
The return value is Object, so you will need to cast it to its appropriate data type.

 

For a class to be serialized successfully, two conditions must be met:

  • The class must implement the java.io.Serializable interface.
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

 

When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

Serialization of class
public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name + " " + address);
   }
}

Serializing an object
import java.io.*;
public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      
      try
      {
         FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

Deserializing an object:
import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}


The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method.

For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class.

If the JVM can’t find a class during the deserialization of an object, it throws a ClassNotFoundException.

 

Class Refactoring with Serialization and serialVersionUID

Serialization in java permits some changes in the java class if they can be ignored. Some of the changes in class that will not affect the deserialization process are:

  • Adding new variables to the class
  • Changing the variables from transient to non-transient, for serialization it’s like having a new field.
  • Changing the variable from static to non-static, for serialization it’s like having a new field.

But for all these changes to work, the java class should have serialVersionUID defined for the class.

If the class doesn’t define serialVersionUID, it’s getting calculated automatically and assigned to the class. Java uses class variables, methods, class name, package etc to generate this unique long number. If you are working with any IDE, you will automatically get a warning that “The serializable class Employee does not declare a static final serialVersionUID field of type long”.

We can use java utility “serialver” to generate the class serialVersionUID, for Employee class we can run it with below command.

SerializationExample/bin$serialver -classpath . com.journaldev.serialization.Employee

serialVersionUID tells the deserialization process that the new class is the new version of the same class and should be deserialized of possible.

Declaration of serialVersionUID in a class:
private static final long serialVersionUID = 2087368867376448459L;

 

Java Externalizable Interface:

Sometimes we want to obscure the object data to maintain it’s integrity. We can do this by implementing java.io.Externalizable interface and provide implementation of writeExternal() and readExternal() methods to be used in serialization process.

@Override
public void writeExternal(ObjectOutput out) throws IOException {
	out.writeInt(id);
	out.writeObject(name+"xyz");
	out.writeObject("abc"+gender);
}

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
	id=in.readInt();
	//read in the same order as written
	name=(String) in.readObject();
	if(!name.endsWith("xyz")) throw new IOException("corrupted data");
	name=name.substring(0, name.length()-3);
	gender=(String) in.readObject();
	if(!gender.startsWith("abc")) throw new IOException("corrupted data");
	gender=gender.substring(3);
}

If these methods are present in the class, they are used for serialization purposes.

readObject(ObjectInputStream ois): If this method is present in the class, ObjectInputStream readObject() method will use this method for reading the object from stream.

writeObject(ObjectOutputStream oos): If this method is present in the class, ObjectOutputStream writeObject() method will use this method for writing the object to stream. One of the common usage is to obscure the object variables to maintain data integrity.

Object writeReplace(): If this method is present, then after serialization process this method is called and the object returned is serialized to the stream.

Object readResolve(): If this method is present, then after deserialization process, this method is called to return the final object to the caller program. One of the usage of this method is to implement Singleton pattern with Serialized classes.

Links for further details: http://www.journaldev.com/2452/serialization-in-java, http://www.tutorialspoint.com/java/java_serialization.htm

Javascript Objects

Javascript variables:       var person = “John Doe”;

Javascript objects are variables too. But objects can contain many values.The values are written as name : value pairs.

eg. var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};

Object properties can be both primitive values, other objects, and functions.

Creating new objects:
1) Using an Object Literal
2) Using the JavaScript Keyword new
3) Using an object constructor

Javascript Properties:

1)  person.age
2)  person[“age”]
3)  x = “age”; person[x]

Delete properties:    delete person.age

Javascript Object Prototypes:

Every JavaScript object has a prototype. The prototype is also an object.
All JavaScript objects inherit their properties and methods from their prototype.

eg. Person.prototype.nationality = “English”;
eg. Person.prototype.name = function()  {
return this.firstName + ” ” + this.lastName;
};

Links to reference post : http://www.w3schools.com/js/js_object_definition.asp

Object Cloning in Java

A clone is an exact copy of the original. In java, it essentially means the ability to create an object with similar state as the original object.


By default, java cloning is ‘field by field copy’
i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. So, JVM when called for cloning, do following things:

1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.

2) If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

 

How to clone in Java??
A) You must implement Cloneable interface.
B) You must override clone() method from Object class. [Its weird. clone() method should have been in Cloneable interface.]

public class Employee implements Cloneable{

    private int empoyeeId;
    private String employeeName;
    private Department department;

    public Employee(int id, String name, Department dept)
    {
        this.empoyeeId = id;
        this.employeeName = name;
        this.department = dept;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    //Accessor/mutators methods will go there
}

// Department class
public class Department
{
    private int id;
    private String name;
 
    public Department(int id, String name)
    {
        this.id = id;
        this.name = name;
    }
    //Accessor/mutators methods will go there
}


public class TestCloning {
 
    public static void main(String[] args) throws CloneNotSupportedException
    {
        Department dept = new Department(1, "Human Resource");
        Employee original = new Employee(1, "Admin", dept);
        //Lets create a clone of original object
        Employee cloned = (Employee) original.clone();
        //Let verify using employee id, if cloning actually workded
        System.out.println(cloned.getEmpoyeeId());
 
        //Verify JDK's rules
 
        //Must be true and objects must have different memory addresses
        System.out.println(original != cloned);
 
        //As we are returning same class; so it should be true
        System.out.println(original.getClass() == cloned.getClass());
 
        //Default equals method checks for refernces so it should be false. If we want to make it true,
        //we need to override equals method in Employee class.
        System.out.println(original.equals(cloned));
    }
}
Output:
1
true
true
false



public class TestCloning { 
    public static void main(String[] args) throws CloneNotSupportedException {
        Department hr = new Department(1, "Human Resource");
        Employee original = new Employee(1, "Admin", hr);
        Employee cloned = (Employee) original.clone();
 
        //Let change the department name in cloned object and we will verify in original object
        cloned.getDepartment().setName("Finance");
 
        System.out.println(original.getDepartment().getName());
    }
}
Output: Finance


 

Shallow Cloning

This is default implementation in java. In overridden clone method, if you are not cloning all the object types (not primitives), then you are making a shallow copy.

All above examples are of shallow copy only, because we have not cloned the Department object on Employee class’s clone method.

 

Deep cloning

It is the desired behavior in most the cases. We want a clone which is independent of original and making changes in clone should not affect original.

//Modified clone() method in Employee class
@Override
protected Object clone() throws CloneNotSupportedException {
    Employee cloned = (Employee)super.clone();
    cloned.setDepartment((Department)cloned.getDepartment().clone());
    return cloned;
}

I modified the Employee classes clone() method and added following clone method in Department class.
//Defined clone method in Department class.
@Override
protected Object clone() throws CloneNotSupportedException {
    return super.clone();
}

Now testing our cloning code gives desired result and name of department will not be modified.
public class TestCloning {
    public static void main(String[] args) throws CloneNotSupportedException {
        Department hr = new Department(1, "Human Resource");
        Employee original = new Employee(1, "Admin", hr);
        Employee cloned = (Employee) original.clone();
 
        //Let change the department name in cloned object and we will verify in original object
        cloned.getDepartment().setName("Finance");
 
        System.out.println(original.getDepartment().getName());
    }
}
Output:
Human Resource

 

So deep cloning requires satisfaction of following rules.

*  No need to separately copy primitives.
*  All the member classes in original class should support cloning and in clone method of  original class in context should call super.clone() on all member classes.
*  If any member class does not support cloning then in clone method, one must create a new instance of that member class and copy all its attributes one by one to new member class object. This new member class object will be set in cloned object.

 

 

Using copy constructors

Copy constructors are special constructors in a class which takes argument for its own class type. So, when you pass an instance of class to copy constructor, then constructor will return a new instance of class with values copied from argument instance. Lets see this in example:

public class PointOne {
    private Integer x;
    private Integer y;
 
    public PointOne(PointOne point){
        this.x = point.x;
        this.y = point.y;
    }
}

This method looks simple and it is until comes inheritance. When you define a class by extending above class, you need to define a similar constructor there also. In child class, you need to copy child specific attributes and pass the argument to super class’s constructor. Lets see how?

public class PointTwo extends PointOne{
    private Integer z;
 
    public PointTwo(PointTwo point){
        super(point); //Call Super class constructor here
        this.z = point.z;
    }
}

So, are we fine now? NO. The problem with inheritance is that exact behavior is identified only in run time. So, in our case if some class passed the instance of PointTwo in constructor of PointOne. In this case, you will get the instance of PointOne in return where you passed instance of PointTwo as argument. Lets see this in code:

class Test
{
    public static void main(String[] args)
    {
        PointOne one = new PointOne(1,2);
        PointTwo two = new PointTwo(1,2,3);
 
        PointOne clone1 = new PointOne(one);
        PointOne clone2 = new PointOne(two);
 
        //Let check for class types
        System.out.println(clone1.getClass());
        System.out.println(clone2.getClass());
    }
}
Output:
class corejava.cloning.PointOne
class corejava.cloning.PointOne

 
Links: http://mrbool.com/how-to-implement-cloning-in-java-using-cloneable-interface/28410,
http://stackoverflow.com/questions/4081858/about-java-cloneable, http://www.artima.com/intv/bloch13.html,
http://coderevisited.com/cloneable-interface-in-java/,

Good article on object cloning in java: http://howtodoinjava.com/core-java/cloning/a-guide-to-object-cloning-in-java/

ConcurrentHashMap in Java

Why we need ConcurrentHashMap when we already had Hashtable ?

Hashtable provides concurrent access to the Map.Entries objects by locking the entire map to perform any sort of operation (update,delete,read,create).

ConcurrentHashMap class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details. So the main purpose of this class is to provide the same functionality as of Hashtable but with a performance comparable to HashMap.

 

ConcurrentHashMap:

 

For detail explanation refer to : http://javahungry.blogspot.com/2015/02/how-concurrenthashmap-works-in-java-internal-implementation.html

Fail fast vs fail safe iterator

What is Concurrent Modification ?

When one or more thread is iterating over the collection, in between, one thread changes the structure of the collection (either adding the element to the collection or by deleting the element in the collection or by updating the value at particular position in the collection) is known as Concurrent Modification

 

Fail fast Iterator

Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Fail-fast iterator can throw ConcurrentModificationException in two scenarios :

Single Threaded Environment : After the creation of the iterator , structure is modified at any time by any method other than iterator’s own remove method.
 
Multiple Threaded Environment:  If one thread is modifying the structure of the collection while other thread is iterating over it.

According to  Oracle docs , the fail-fast behavior of an iterator cannot be guarantee, fail-fast behavior of iterators should be used only to detect bugs.

 

How  Fail  Fast Iterator  come to know that the internal structure is modified ?

Iterator read internal data structure (object array) directly . The internal data structure(i.e object array) should not be modified while iterating through the collection. To ensure this it maintains an internal  flag “mods” .Iterator checks the “mods” flag whenever it gets the next value (using hasNext() method and next() method). Value of mods flag changes whenever there is an structural modification. Thus indicating iterator to throw ConcurrentModificationException.

 

Fail Safe Iterator :

Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure.  So , original data structure remains  structurally unchanged .Hence , no ConcurrentModificationException throws by the fail safe iterator.

Two  issues associated with Fail Safe Iterator are :

1. Overhead of maintaining the copied data structure i.e memory.

2.  Fail safe iterator does not guarantee that the data being read is the data currently in the original data structure.

 

Fail safe iterator is ordinarily too costly, but may be more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don’t want to synchronize traversals, yet need to preclude interference among concurrent threads.

The “snapshot” style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.

The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove(), set(), and add()) are not supported. These methods throw UnsupportedOperationException.

 

eg. HashMap has a fail fast iterator while ConcurrentHashMap uses a fail slow iterator.

 

For detail description and examples please refer to the post: http://javahungry.blogspot.com/2014/04/fail-fast-iterator-vs-fail-safe-iterator-difference-with-example-in-java.html

Javascript basics

1) Javascript classes and object oriented programming basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

 

 

2) JS functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

The parameters of a function call are the function’s arguments. Arguments are passed to functions by value.

If the function changes the value of an argument, this change is not reflected globally or in the calling function.

However, object references are values, too, and they are special: if the function changes the referred object’s properties, that change is visible outside the function.

 

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

 

var multiply = function func_name(x, y) {
   return x * y;
};

There is a distinction between the function name and the variable the function is assigned to.

The function name cannot be changed, while the variable the function is assigned to can be reassigned.

The function name can be used only within the function’s body.

Attempting to use it outside the function’s body results in an error (or undefined if the function name was previously declared via a var statement).

 

 

Nods.js Basics

CommonJS Module format

Each file in a node is its own module.

The require function is used to import a module. (eg. require(‘./abc’))

 

Installing external yargs node module to take command line args

npm install yargs –save  (to save dependencies in package.json file)

 

Postman chrome extension for viewing the http request and response messages

nodejs ht

 

FileSystem Module:

Non Blocking call to read a file

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});

Blocking call to read a file

var fs = require("fs"); 
var data = fs.readFileSync('input.txt');
console.log(data.toString());

 

Events Module:

// Import events module
var events = require('events');

// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

// Bind event and even handler as follows
eventEmitter.on('eventName', eventHandler);

// Fire an event 
eventEmitter.emit('eventName');

====================================================================
Streams
Streams are objects that let you read data from a source or write data to a destination in continous fashion. In Node.js, there are four types of streams.
Readable, Writable, Duplex, Transform.

Each type of Stream is an EventEmitter instance and throws several events at different instance of times.

Events thrown by the streams.
data, end, error, finish.

Read Stream Example

var fs = require("fs");
var data = '';

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Set the encoding to be utf8. 
readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
   data += chunk;
});
readerStream.on('end',function(){
   console.log(data);
});
readerStream.on('error', function(err){
   console.log(err.stack);
});
console.log("Program Ended");

Write stream example

var fs = require("fs");
var data = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
    console.log("Write completed.");
});
writerStream.on('error', function(err){
   console.log(err.stack);
});
console.log("Program Ended");

Piping Streams
Piping is a mechanism where we provide output of one stream as the input to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream. There is no limit on piping operations.

var fs = require("fs");

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);

console.log("Program Ended");

Chaining StreamsChanining is a mechanism to connect output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.

var fs = require("fs");
var zlib = require('zlib');

// Compress the file input.txt to input.txt.gz
fs.createReadStream('input.txt')
  .pipe(zlib.createGzip())
  .pipe(fs.createWriteStream('input.txt.gz'));
  
console.log("File Compressed.");

===============================================================
Buffer Module:

Buffer class provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.

Buffer class is a global class and can be accessed in application without importing buffer module.


Node Buffer can be constructed in a variety of ways.

1) var buf = new Buffer(10);
2) var buf = new Buffer([10, 20, 30, 40, 50]);
3) var buf = new Buffer("Simply Easy Learning", "utf-8");


To write into a Node Buffer:
  write returns the number of bytes written

buf = new Buffer(256);
len = buf.write("Simply Easy Learning");
console.log("Octets written : "+  len);


To convert a Node Buffer into JSON object:
Returns a JSON-representation of the Buffer instance.
buf.toJSON()

Concatenation:  Buffer.concat([buffer1,buffer2]);

Compare Buffers : buffer1.compare(buffer2);

Copy Buffers: buffer1.copy(buffer2);

Buffer length: buffer.length;

Slice Buffer: buffer.slice(0,9);

===============================================================

Global Objects: Node.js global objects are global in nature we do not need to include these objects in our application, rather we can use them directly.
These objects are modules, functions, strings and object itself.

__filename
The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file
console.log( __filename );
__dirname
The __dirname represents the name of the directory that the currently executing script resides in.
console.log( __dirname );
Console:console is a global object and is used to print different levels of messages to stdout and stderr. There are built-in methods to be used for printing informational, warning and error messages.

It is used in synchronous way when destination is file or a terminal and asynchronous way when destination is a pipe.

eg.
console.info("Program Started");
var counter = 10;
console.log("Counter: %d", counter);

console.time("Getting data");

 

Process: The process object is a global object and can be accessed from anywhere. There are number of useful methods available through a process object.

The process object is an instance of EventEmitter and emits following events:

exit, beforeExit, uncaughtException, Signal Events

Process object also provides many useful properties and method reference.

 

Global Functions:

setTimeout(cb, ms)
The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds.
This function returns an opaque value that represents the timer which can be used to clear the timer.
clearTimeout(t):Global function is used to stop a timer that was previously created with setTimeout().
setInterval(cb, ms)The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds.
clearInterval(t): Is used to clear an interval.

 

================================================================================
Web Module

var http = require('http');
// creating server
http.createServer(......);
http.listen(port_no);

// creating client
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  
};

var req = http.request(options, callback);
req.end();

===============================================================================
Callback functions: In Node Application, any async function accepts a callback as a last parameter and the callback function accepts error as a first parameter.

Android Questions

1)  What is ContentProvider and what is being used for?
A ContentProvider manages access to a structured set of data. It encapsulates the data and provide mechanisms for defining data security. ContentProvider is the standard interface that connects data in one process with code running in another process.

2) Under what condition could the code sample below crash your application? How would you modify the code to avoid this potential problem? Explain your answer.

    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
    sendIntent.setType(HTTP.PLAIN_TEXT_TYPE); // “text/plain” MIME type
    startActivity(sendIntent);

Sol:

An implicit intent specifies an action that can invoke any app on the device able to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can. If there is more than one application registered that can handle this request, the user will be prompted to select which one to use.

However, it is possible that there are no applications that can handle your intent. In this case, your application will crash when you invoke startActivity(). To avoid this, before calling startActivity() you should first verify that there is at least one application registered in the system that can handle the intent. To do this use resolveActivity() on your intent object:

    // Verify that there are applications registered to handle this intent
    // (resolveActivity returns null if none are registered)
    if (sendIntent.resolveActivity(getPackageManager()) != null) {
        startActivity(sendIntent);
    } 

 

http://stackoverflow.com/questions/22479211/intent-resolveactivity-null-but-launching-the-intent-throws-an-activitynotfou

From what I could see, intent.resolveActivity() will return true if there is ANY activity resolving this intent. Even if this activity is not exported (which makes it unusable for all practical purposes in case it’s not from your package). Android’s API doesn’t care to mention that, so you have to figure it out by yourself, and make sure that the activity you’re trying to launch is indeed exported.

ActivityInfo activityInfo = intent.resolveActivityInfo(pm, intent.getFlags());
if (activityInfo.exported) {
    doSomething();
}


3) The last callback in the lifecycle of an activity is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory. Usually, the system will call onPause() and onStop() before calling onDestroy(). Describe a scenario, though, where onPause() and onStop() would not be invoked.

Sol:

onPause() and onStop() will not be invoked if finish() is called from within the onCreate() method. This might occur, for example, if you detect an error during onCreate() and call finish() as a result. In such a case, though, any cleanup you expected to be done in onPause() and onStop() will not be executed.

Although onDestroy() is the last callback in the lifecycle of an activity, it is worth mentioning that this callback may not always be called and should not be relied upon to destroy resources. It is better have the resources created in onStart() and onResume(), and have them destroyed in onStop() and onPause, respectively.

4) Suppose that you are starting a service in an Activity as follows:

Intent service = new Intent(context, MyService.class);             
startService(service);

where MyService accesses a remote server via an Internet connection.

If the Activity is showing an animation that indicates some kind of progress, what issue might you encounter and how could you address it?

Sol:

Responses from a remote service via the Internet can often take some time, either due to networking latencies, or load on the remote server, or the amount of time it takes for the remote service to process and respond to the request.

As a result, if such a delay occurs, the animation in the activity (and even worse, the entire UI thread) could be blocked and could appear to the user to be “frozen” while the client waits for a response from the service. This is because the service is started on the main application thread (or UI thread) in the Activity.

The problem can (and should) be avoided by relegating any such remote requests to a background thread or, when feasible, using an an asynchronous response mechanism.


Android framework offers several classes that help you off-load operations onto a separate thread running in the background. The most useful of these is IntentService. (https://developer.android.com/training/run-background-service/index.html)

Note well: Accessing the network from the UI thread throws a runtime exception in newer Android versions which causes the app to crash.

 

5) Normally, in the process of carrying out a screen reorientation, the Android platform tears down the foreground activity and recreates it, restoring each of the view values in the activity’s layout.

In an app you’re working on, you notice that a view’s value is not being restored after screen reorientation. What could be a likely cause of the problem that you should verify, at a minimum, about that particular view?

Sol:

You should verify that it has a valid id. In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.
6) What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?

Sol:

An AsyncTask is not tied to the life cycle of the Activity that contains it. So, for example, if you start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask will not die but instead goes on living until it completes.

Then, when the AsyncTask does complete, rather than updating the UI of the new Activity, it updates the former instance of the Activity (i.e., the one in which it was created but that is not displayed anymore!). This can lead to an Exception (of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity).

There’s also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activty, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.

For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea . Rather, for long-running background tasks, a different mechanism (such as a service) should be employed.

7) What is an Intent? Can it be used to provide data to a ContentProvider? Why or why not?
Sol:

The Intent object is a common mechanism for starting new activity and transferring data from one activity to another. However, you cannot start a ContentProvider using an Intent.

When you want to access data in a ContentProvider, you must instead use the ContentResolver object in your application’s Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.

8) What is the difference between a fragment and an activity? Explain the relationship between the two.

Sol:

An activity is typically a single, focused operation that a user can perform (such as dial a number, take a picture, send an email, view a map, etc.). Yet at the same time, there is nothing that precludes a developer from creating an activity that is arbitrarily complex.

Activity implementations can optionally make use of the Fragment class for purposes such as producing more modular code, building more sophisticated user interfaces for larger screens, helping scale applications between small and large screens, and so on. Multiple fragments can be combined within a single activity and, conversely, the same fragment can often be reused across multiple activities. This structure is largely intended to foster code reuse and facilitate economies of scale.

A fragment is essentially a modular section of an activity, with its own lifecycle and input events, and which can be added or removed at will. It is important to remember, though, that a fragment’s lifecycle is directly affected by its host activity’s lifecycle; i.e., when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all of its fragments.

9) What is difference between Serializable and Parcelable ? Which is best approach in Android ?

Sol:

Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations.

Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient than Serializable, and to get around some problems with the default Java serialization scheme.

10) What is the difference between Service and IntentService? How is each used?
Sol:

Service is the base class for Android services that can be extended to create any service. A class that directly extends Service runs on the main thread so it will block the UI (if there is one) and should therefore either be used only for short tasks or should make use of other threads for longer tasks.

IntentService is a subclass of Service that handles asynchronous requests (expressed as “Intents”) on demand. Clients send requests through startService(Intent) calls. The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. Writing an IntentService can be quite simple; just extend the IntentService class and override the onHandleIntent(Intent intent) method where you can manage all incoming requests.

Source: https://www.toptal.com/android/interview-questions


11) What are “launch modes”? What are the two mechanisms by which they can be defined? What specific types of launch modes are supported?

Sol:

A “launch mode” is the way in which a new instance of an activity is to be associated with the current task.

Launch modes may be defined using one of two mechanisms:

  • Manifest file. When declaring an activity in a manifest file, you can specify how the activity should associate with tasks when it starts. Supported values include:
    • standard (default). Multiple instances of the activity class can be instantiated and multiple instances can be added to the same task or different tasks. This is the common mode for most of the activities.
    • singleTop. The difference from standard is, if an instance of the activity already exists at the top of the current task and the system routes the intent to this activity, no new instance will be created because it will fire off an onNewIntent() method instead of creating a new object.
    • singleTask. A new task will always be created and a new instance will be pushed to the task as the root. However, if any activity instance exists in any tasks, the system routes the intent to that activity instance through the onNewIntent() method call. In this mode, activity instances can be pushed to the same task. This mode is useful for activities that act as the entry points.
    • singleInstance. Same as singleTask, except that the no activities instance can be pushed into the same task of the singleInstance’s. Accordingly, the activity with launch mode is always in a single activity instance task. This is a very specialized mode and should only be used in applications that are implemented entirely as one activity.
  • Intent flags. Calls to startActivity() can include a flag in the Intent that declares if and how the new activity should be associated with the current task. Supported values include:
    • FLAG_ACTIVITY_NEW_TASK. Same as singleTask value in Manifest file (see above).
    • FLAG_ACTIVITY_SINGLE_TOP. Same as singleTop value in Manifest file (see above).
    • FLAG_ACTIVITY_CLEAR_TOP. If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent(). There is no corresponding value in the Manifest file that produces this behavior.


12) Enumerate the three key loops when monitoring an activity

Sol:

Entire lifetime – activity happens between onCreate and onDestroy
Visible lifetime – activity happens between onStart and onStop
Foreground lifetime – activity happens between onResume and onPause


13) What role does Dalvik play in Android development?

Sol : Dalvik serves as a virtual machine, and it is where every Android application runs. Through Dalvik, a device is able to execute multiple virtual machines efficiently through better memory management.


14) When does ANR occur?

Sol: The ANR dialog is displayed to the user based on two possible conditions. One is when there is no response to an input event within 5 seconds, and the other is when a broadcast receiver is not done executing within 10 seconds.


15) What is AIDL?

Sol: AIDL, or Android Interface Definition Language, handles the interface requirements between a client and a service so both can communicate at the same level through interprocess communication or IPC. This process involves breaking down objects into primitives that Android can understand. This part is required simply because a process cannot access the memory of the other process.

Data types supported by AIDL are:

AIDL has support for the following data types:
-string
-charSequence
-List
-Map
-all native Java data types like int,long, char and Boolean


16)  What is a visible activity?

Sol: A visible activity is one that sits behind a foreground dialog. It is actually visible to the user, but not necessarily being in the foreground itself.


17) Is it possible to use or add a fragment without using a user interface?

Sol: Yes, it is possible to do that, such as when you want to create a background behavior for a particular activity. You can do this by using add(Fragment,string) method to add a fragment from the activity.


18) What is a Sticky Intent?

Sol: A Sticky Intent is a broadcast from sendStickyBroadcast() method such that the intent floats around even after the broadcast, allowing others to collect data from it.


19) What is the difference between a regular bitmap and a nine-patch image?

Sol: In general, a Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.

20) What is AAPT?

Sol: AAPT is short for Android Asset Packaging Tool. This tool provides developers with the ability to deal with zip-compatible archives, which includes creating, extracting as well as viewing its contents.

21) What all configuration changes can cause restart of the activity?

Sol:
1) orientation change
2) changing the default language
3) Inserting your device into a display dock
4) modifying the device’s default font scaling factor

We can use configChanges to prevent restart of the activity for certain configurations.

<activity android:name=".ProgressTestActivity"
     android:label="@string/app_name"
     android:configChanges="orientation|keyboardHidden|keyboard">
</activity>

Avoid using the configChanges attribute if possible. It is typically better to use other means to handle configuration changes, like the Android loader framework or headless retained fragments.

Working between fork and upstream repository

Merging changes from upstream repository to fork repository:

1) Configure a remote that points to the upstream repository in Git.

i) Open Git Bash.

ii) List the current configured remote repository for your fork.

git remote -v
origin  https://github.com/YOUR_USERNAME/YOUR_FORK.git (fetch)
origin  https://github.com/YOUR_USERNAME/YOUR_FORK.git (push)

iii) Specify a new remote upstream repository that will be synced with the fork.

git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git

iv) Verify the new upstream repository you've specified for your fork.

git remote -v
origin https://github.com/YOUR_USERNAME/YOUR_FORK.git (fetch)
origin https://github.com/YOUR_USERNAME/YOUR_FORK.git (push)
upstream  https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git (fetch)
upstream  https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git (push)

2) Sync a fork

i) Change the current working directory to your local project.

ii) Fetch the branches and their respective commits from the upstream repository. Commits to master will be stored in a local branch, upstream/master.

git fetch upstream
remote: Counting objects: 75, done.
remote: Compressing objects: 100% (53/53), done.
remote: Total 62 (delta 27), reused 44 (delta 9)
Unpacking objects: 100% (62/62), done.
From https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY
 * [new branch]      master     -> upstream/master

iii) Check out your fork's local master branch.

git checkout master
Switched to branch 'master'

iv) Merge the changes from upstream/master into your local master branch. This brings your fork's master branch into sync with the upstream repository, without losing your local changes.

git merge upstream/master
Updating a422352..5fdff0f
Fast-forward
 README                    |    9 -------
 README.md                 |    7 ++++++
 2 files changed, 7 insertions(+), 9 deletions(-)
 delete mode 100644 README
 create mode 100644 README.md

If your local branch didn't have any unique commits, Git will instead perform a "fast-forward":

git merge upstream/master
Updating 34e91da..16c56ad
Fast-forward
 README.md                 |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

3) Push the Git changes to your git repository

git push

 

Post to refer for above steps: https://help.github.com/articles/syncing-a-fork/, https://help.github.com/articles/configuring-a-remote-for-a-fork/

 

 

 

 

https://help.github.com/categories/collaborating-on-projects-using-issues-and-pull-requests/

https://help.github.com/articles/configuring-a-remote-for-a-fork/