Monday, November 7, 2011

Data Structure - Queue(JAVA) using array


For theoretical reference you check wiki.

http://en.wikipedia.org/wiki/Queue_%28data_structure%29

Java you can refer the code.



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class QueueKrk {

 private static final int MAX = 3;
 private static int[] QUEUE = new int[MAX];
 private static int top = -1;
 private static int rear = 0;

 private enum Function {
  PUSH, POP, PRINTALL
 };

 private static void push() {
  if (top < MAX -1) {
   System.out.println("Enter the value to added to the queue");
   int value = readValue();
   QUEUE[++top] = value;
  } else {
   System.out.println("The queue has reached the maximum value");
  }
 }

 private static void peek() {
  if(top >= rear){
   rear++;
  }else{
   System.out.println("Nothing to Peek");
  }

 }

 private static void printAll() {
  if (top >= rear) {
   int i = 0;
   for (i = rear; i <= top; i++) {
    System.out.println(QUEUE[i]);
   }
  } else {
   System.out.println("The queue is empty");
  }
 }

 private static int readValue() {
  int input = 0;
  try {
   BufferedReader br = new BufferedReader(new InputStreamReader(
     System.in));
   input = Integer.parseInt(br.readLine());
  } catch (NumberFormatException nfe) {
   System.err.println("Invalid Format!");
   System.exit(0);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return input;
 }

 public static void main(String[] args) {
  init();
 }

 private static void init() {
  System.out.println("For Push enter 0, Peek enter 1 and 2 to print all. For exit enter non number");
  int selection = readValue();
  optionSelection(selection);
 }

 private static void optionSelection(int selection) {
  Function function = null;
  try {
   function = Function.values()[selection];
  } catch (ArrayIndexOutOfBoundsException ex) {
   System.out.println("Enter either '0' or '1' or '2' for push, Peek , view all respectively");
   init();
  }
  switch (function) {
  case PUSH:
   push();
   init();
   break;
  case POP:
   peek();
   init();
   break;
  case PRINTALL:
   printAll();
   init();
   break;
  default:
   break;
  }
 }

}



Data Structure - Stack (JAVA) using array

For theoretical reference you can see wiki link. 
http://en.wikipedia.org/wiki/Stack_%28data_structure%29


Java Stack using array .

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StackKrk {

 private static final int MAX = 3;// constant for the size of the stack.
 private static final int[] STACK = new int[MAX]; 
 private static int TOP = 0; // Flag for the stack position.
 private  enum Function{PUSH, POP, PRINTALL};
 
 public static void main(String[] args) {
  init();
 }
 
 private static void init(){
  System.out.println("For Push enter 0, Pop enter 1 and 2 to print all. For exit enter non number");
  int selection = readValue();
  
  optionSelection(selection);
 }
 
 private static void optionSelection(int selection){
  Function function = null;
  try{
   function = Function.values()[selection];
  }catch(ArrayIndexOutOfBoundsException ex){
   System.out.println("Enter either '0' or '1' or '2' for push, pop , view all respectively");
   init();
  }
  switch (function) {
  case PUSH:
   push();
   init();
   break;
  case POP:
   pop();
   init();
   break;
  case PRINTALL:
   printAll();
   init();
   break;
  default:
   
   break;
  }
 }

 private static int readValue() {
  int input = 0;
  try {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   input = Integer.parseInt(br.readLine());
  } catch (NumberFormatException nfe) {
   System.err.println("Invalid Format!");
   System.exit(0);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return input;
 }

 private static void push() {
  if (TOP == MAX) {
   System.out.println("Reached the maximum stack value");
  } else {
   System.out.println("Enter the value to be pushed ::>");
   int value = readValue();
   STACK[TOP++] = value;
  }
 }
 
 private static void pop() {
  if (TOP == 0) {
   System.out.println("The stack is empty");
  } else {
   System.out.println("The poped element of the stack ::>" + STACK[--TOP]);
   STACK[TOP] = 0;
  }
 }
 private static void printAll(){
  for(int i=0; i<=TOP-1; i++){
   System.out.println("Value in the stack position["+i+"]  "+STACK[i]);
  }
    
 }


}



Sunday, November 6, 2011

Using GSON Effectively

Program of Deserialize/Serialize JSON.I am writing it below. First download the Gson then add it to the eclipse project.

Step 1: Create a Dog class with getters and setters as below.
package myobject;
public class Dog {
String name;
int age
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

Step 2: Write a common GsonSerializer as below with generics so any class type can be passed.

package common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
//Generics is used so any class type can be passed
public class GsonSerializer<T> {
public T Deserialize(String json, Class classOfT) {
Gson gn = new GsonBuilder().create();
return (T) gn.fromJson(json, classOfT);
}
public String Serialize(T object) {
Gson gn = new GsonBuilder().create();
return gn.toJson(object);
}
}
 3: Write a main method for calling the example
package gsoncaller;
import myobject.Dog;
import common.GsonSerializer;
public class MyGsonCaller {
public static void main(String[] args) {
Dog dog = new Dog();
dog.setAge(1);
dog.setName("mela");
GsonSerializer<Dog> serializer = new GsonSerializer<Dog>();
serializer.Serialize(dog);
System.out.println("My json string ::>" + serializer.Serialize(dog));
dog = serializer.Deserialize(serializer.Serialize(dog), Dog.class);
String name = dog.getName();
int age = dog.getAge();
System.out.println("Name ::>" + name);
System.out.println("Age ::>" + age);
}
}
The out put is:

My json string ::>{"name":"mela","age":1}
Name ::>mela
Age ::>1





Friday, November 4, 2011

Eclipse short cut keys


Highlighted the most useful shortcut keys.

1. Navigation
Shortcut Description
CTRL + SHIFT + R Open / Search for resources, e.g. files
CTRL + SHIFT + T Open / Search for Types
CTRL + E Allows to select an editor from the currenlty open editors
CTRL + F8 Shortcut for switching perspectives
ALT + LEFT ARROW KEY or ALT + RIGHT ARROW KEY Go to prev/ next editor position in history
Ctrl-PageUp/PageDown Previous/next tab
F3 Go to declaration of this variable
CTRL + SHIFT + P Go to matching bracket
CTRL + Q Go to editor area and position the cursor at the last changed position

2. Search
Shortcut Description
Ctrl + . Go to next problem
Ctrl + , Go to previous problem
F3 on a variable Goto Declaration of this variable
F4 on a variable Show type hierarchy
CTRL + J , CTRL +k Incremental search, find next
CTRL+ SHIFT +k Decremental search,find previous
CTRL + SHIFT + G Search for reference in the workspace

3. Run
Shortcut Description
Ctrl F11 Run last launched
Alt + Shift + X - J Run as Java application

4. Editing
Shortcut Description
CTRL + 1 Quickfix, dependend on cursor position. See Quickfix for details.
CTRL + Space Content assist/ code completion, see Content Assist for details.
CTRL + T Show inline inline inheritance tree of the current Java class
CTRL + O Show inline all methods of the current class, press CTRL+O again to show the inherited methods
F12 Focuses the editor (especially helpful if you working with Fast Views
Ctrl + M Maximize Java editor
CTRL + Shift + F Format source code
CTRL + Shift + O Organize the imports / Will import the missing imports.
CTRL + Q Last edited position

5. Arrow Keys
Shortcut Description
CTRL + Left Move one element to the left
CTRL + Right Move one element to the right
CTRL + ALT + Up/Down Copy line
ALT + Up / Down Move line up / down
ALT + SHIFT Up / Down Select the previous / next syntactical element
ALT + SHIFT Up / Down / Left / Right Extending / Reducing the selection of the previous / next syntactical element
CTRL + Up / Down Scroll up / down a line in the editor

6. Delete
Shortcut Description
Ctrl + D Deletes line
CTRL + SHIFT + DELETE Delete until end of line
CTRL + DELETE Delete next element
CTRL + BACKSPACE Delete previous element

7. Variable assignment
Shortcut Description
Ctrl + 2 + L Assign statement to new local variable
Ctrl + 2 + F Assign statement to new field

8. Programming
Coding
Shortcut Description
Shift + F2 Call the Javadoc for the selected type / class / method
Alt+Shift + N + Letter Type shortcut for the command, e.g. njc to create a new Java class or npip to create a new Plugin project.
Alt + Shift + Z Surround block with try and catch

9. Refactoring
Shortcut Description
ALT- SHIFT +R Rename
CTRL+2,R Rename locally (in file), faster then ALT- SHIFT +R
ALT- SHIFT + T Opens the quick refactoring menu

10. Debugging
Shortcut Description
F11 Debug last run
Ctrl + Shift + B Toggle breakpoint
F5 Single Step (Down)
F6 Single Step (Jump)
F7 Up

Android Interview Questions - Intent and Intent Filters


1. What is an Intent?
     Three of the core components of an application — activities, services, and broadcast receivers — are activated through messages, called intents,passive data structure holding an abstract description of an operation to be performed — or, often in the case of broadcasts, a description of something that has happened and is being announced.

2. How will start an Activity?
       startActivity(),startActivityForResult(),setResult()

3. What are the kinds of Intents?
     Implicit Intent and Explicit Intents

4. Explain Explicit and Implicit Intents?
      Explicit intent names the component, e.g. the Java class which should be called.
     Implicit intents asked the system to perform a service without telling the system which Java class should do this service.

5. What is Intent Filters?
   Intent filters are typically defined via the "AndroidManifest.xml" file.where Android system will determine suitable applications for an implicit intent and if several applications exists offer the user the choice to open one.  If a component does not define intent filters it can only be called by explicit intents.

6. What are the object consulted against Intent Filter?
        Action, Data, Category

7.  What is an Action?
    Adds an action to an intent filter. An <intent-filter> element must contain one or more <action> elements. If it doesn't contain any, no Intent objects will get through the filter.
 <intent-filter . . . >
    <action android:name="com.example.project.SHOW_CURRENT" />
    <action android:name="com.example.project.SHOW_RECENT" />
</intent-filter>

8 What is a Category?
Adds a category name to an intent filter. The role of category specifications within a filter.
<intent-filter . . . >
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    . . .
</intent-filter>

9. What is Data?
Adds a data specification to an intent filter. The specification can be just a data type (the mimeType attribute), just a URI, or both a data type and a URI. A URI is specified by separate attributes for each of its parts:
<intent-filter . . . >
    <data android:mimeType="video/mpeg" android:scheme="http" . . . />
    <data android:mimeType="audio/mpeg" android:scheme="http" . . . />
    . . .
</intent-filter>


Android Parcelable Vs Serializable

Java Serializable:
Serializable comes from standard Java and is much easier to implement all you need to do is implement the Serializable interface and add override two methods.
private void writeObject(java.io.ObjectOutputStream out)     throws IOException private void readObject(java.io.ObjectInputStream in)     throws IOException, ClassNotFoundException
The problem with Serializable is that it tries to appropriately handle everything under the sun and uses a lot reflection to make determine the types that are being serialized. So it becomes a beefy Object.


Androids Parcelable
Android Inter-Process Communication (AIPC) file to tell Android how is should marshal and unmarshal your object.It is less generic and doesn't use reflection so it should have much less overhead and be a lot faster.
public class MyParcelable implements Parcelable {
     private int mData;

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }
     public static final Parcelable.Creator<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };
     
     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }

Thursday, November 3, 2011

Android Application Efficient Development - Trace View

Traceview has been integrated into Eclipse plug-in with DDMS. The start/stop profiling button will open traces in Eclipse directly instead of launching the standalone tool.

Inclusive Time:
     The time spent in the method plus the time spent in any called functions.
Exclusive Time:
     The time spent in the method.

  • A timeline panel -- describes when each thread and method started and stopped

Each thread’s execution is shown in its own row, with time increasing to the right. Each method is shown in another color (colors are reused in a round-robin fashion starting with the methods that have the most inclusive time). The thin lines underneath the first row show the extent (entry to exit) of all the calls to the selected method.
  • A profile panel -- provides a summary of what happened inside a method.
The inclusive and exclusive times (as well as the percentage of the total time).The calling methods as "parents" and called methods as "children." When a method is selected (by clicking on it), it expands to show the parents and children. Parents are shown with a purple background and children with a yellow background. The last column in the table shows the number of calls to this method plus the number of recursive calls. The last column shows the number of calls out of the total number of calls made to that method. In this view, we can see that there were 14 calls  looking at the timeline panel shows that one of those calls took an unusually long time. If any doubts please put a comment.