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.

Android Coding Standards

Android rules are not guidelines or recommendations, but strict rules. Contributions to Android generally will not be accepted if they do not adhere to these rules.


Not all existing code follows the rules, but all new code is expected to. Rule are available in ANROID RULES

Android Interview Questions - Activity


1. What is an Activity?
    ans:
        An Activity is an application component that provides a screen with which users can interact in order to do something

2. Activity Life Cycle and explain their states?
     ans:
      onCreate()      : Called when the activity is first created.This is where you should do all of your normal static set up — create views, bind data to lists, and so on.
      onStart()        : Called just before the activity becomes visible to the user.Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
      onResume()   : Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack.Always followed by onPause().
      onPause()      : Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes.
      onStop()        :  Called when the activity is no longer visible to the user. This may happen because it is being destroyed, or because another activity has been resumed and is covering it.
      onDestroy()   : Called before the activity is destroyed. This is the final call that the activity will receive.

3. What happen in onCreate()?
    ans:
      Called when the activity is first created.This is where you should do all of your normal static set up — create views, bind data to lists, and so on.

4. What happen in onCreate() and onStart()?
    ans:
       onStart() only the activity comes to visible.onCreate() it does the work of setting up  — create views, bind data to lists, and so on.

5. What happen in onStop() and onDestroy()?
     ans:
       onStop() is called before onDestroy() when there is  no visibility to the user its exists in the task.When onDestroy() is called it make sure the activity is destroyed.It is called when the BACK() button is clicked the activity pops out of the task.

6. In which stage of the activity life cycle do you want to commit the changes?
    ans:
       onPause();

7. Which stage of activity is certain to be called?
    ans:
      onPause();

8. How to stop an activity?
   ans:
      finish();

9. What is Fragments?(Not Important)
    ans:
      A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

10. What is Loaders?(Not Important)
  ans:
     Introduced in Android 3.0, loaders make it easy to asynchronously load data in an activity or fragment.

11. What is  task?
  ans:
     A task is a collection of activities that users interact with when performing a certain job.

12. Can task have other application activity inside it ? Give me an example ?
    ans:
     Yes,from any application we can call email client of android this is also falls in the current task.

13. Can u explain how the activity are loaded in Task?
     ans:
       When the current activity starts another, the new activity is pushed on the top of the stack and takes focus. The previous activity remains in the stack, but is stopped. When an activity stops, the system retains the current state of its user interface.Activities in the stack are never rearranged, only pushed and popped from the stack—pushed onto the stack when started by the current activity and popped off when the user leaves it using the BACK key.    

14. When does the state of the activity is saved?
      onStop();

15. Is all the activity state saved in application stack? If NO what should it does to recover the state?(Important)
     No, the system might destroy that activity completely if it needs to recover system memory. the system still knows that the activity has a place in the back stack, but when the activity is brought to the top of the stack the system must recreate it.

16. What should you do to retain the activity state?(Not Important)
   onSaveInstanceState();

17. How to start a task?
<activity ...="">
    <intent-filter ...="">
        <action android:name="android.intent.action.MAIN">
        <category android:name="android.intent.category.LAUNCHER">
    </category></action></intent-filter>
    ...
</activity>


18. Let there be three activity flow  A-&gt;B-&gt;C  I want to go to A how will i go?
     Please do a sample program for task. and put the comments


Hi guys i have summed up few Activity related interview question's and their answers.If any thing wrong please correct me and add your question's too?Lets all get benefited.

What is the difference between Service,Handler,AsyncTask ?


  • A service is an Android component that lives independently from any other components. Activities may come and go, but services can stick around, if you wish. They serve a number of roles, from managing state that multiple activities rely upon to serving as cron jobs to handling longer app widget updates.
  • AsyncTask is a class that arranges to do some work off the main application thread. From the implementer and user of the AsyncTask, how it performs that bit of magic is not generally important. In reality, it uses a thread pool and work queue. AsyncTask uses a Handler to help arrange for select bits of work to be done on the main application thread (e.g., notifying the user of progress updates).
  • Handler is a class that is tied tightly into the message queue and loop that forms the backbone of the main application thread. The primary purpose of a Handler in application code is to arrange for messages to be sent from background threads to the main application thread, mostly to arrange for updates to the UI, which cannot be done from background threads

What is a Service?


A service is an Android component that lives independently from any other components. Activities may come and go, but services can stick around.

A Service is not a separate process, it runs in the same process as the application it is part of.
A Service is not a thread.

Mostly Service is mistaken to be running in separate process but its always part of the main application process. If you want it to be run separately then use <a href="http://lifeasanandroiddeveloper.blogspot.com/2011/11/what-is-async-task.html">AsynTask</a> or<a href="http://developer.android.com/reference/android/app/IntentService.html"> IntentService</a>

What is Handler?

Handler is a class that is tied tightly into the message queue and loop that forms the backbone of the main application thread. The primary purpose of a Handler in application code is to arrange for messages to be sent from background threads to the main application thread, mostly to arrange for updates to the UI, which cannot be done from background threads.

For eg:

Handler handleVal = new Handler();

Runnable runVal = new Runnable() {
@Override
public void run() {
//Your back ground process
}
};
handleVal.post(runVal);

What is an Async Task?


AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

1. Params, the type of the parameters sent to the task upon execution.
2. Progress, the type of the progress units published during the background computation.
3. Result, the type of the result of the background computation.    

public class BackgroundTask extends AsyncTask<Void(Parms),Integer(Progress),Bitmap(Result)> {
@Override
protected void onPreExecute() {
//For eg start your progress bar here
}
@Override protected Bitmap doInBackground(Void... params) {
// Web service call
}
@Override protected void onCancelled() {
//for the task to be cancelled
}
@Override protected void onProgressUpdate(Integer... values) {
//show logs in a text field.
}
@Override protected void onPostExecute(Bitmap img) {
//End your progress bar here
}
}