Wednesday, 29 June 2011

OOPS Concepts With Real Time Examples

This is the most asked Question in a technical interview in any domain.. OOPs Concept is very very important.. Today I will explain OOPs concept with real Life Example that will help you to grasp the concept well and excel in the interviews...



Objects: Object is the basic unit of object-oriented programming.Objects are identified by its unique name. An object represents a particular instance of a class. There can be more than one instance of an object. Each instance of an object can hold its own relevant data.

An Object is a collection of data members and associated member functions also known as methods.

Classes: Classes are data types based on which objects are created.Objects with similar properties and methods are grouped together to form a Class. Thus a Class represent a set of individual objects. Characteristics of an object are represented in a class as Properties. The actions that can be performed by objects becomes functions of the class and is referred to as Methods.

Example #1:

For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents individual Objects.In this context each Car Object will have its own, Model,Year of Manufacture, Colour, Top Speed, Engine Power etc.,which form Properties of the Car class and the associated actions i.e., object functions like Start, Move, Stop form the Methods of Car Class.No memory is allocated when a class is created. Memory is
allocated only when an object is created, i.e., when an instance of a class is created.

Example #2:

An architect will have the blueprints for a house....those blueprints will be plans that explain exactly what properties the house will have and how they are all layed out.  However it is just the blueprint, you can't live in it.  Builders will look at the blueprints and use those blueprints to make a physical house.  They can use the same blueprint to make as many houses as they want....each house will have the same layout and properties.  Each house can accommodate it's own families...so one house might have the Smiths live in it, one house might have the Jones live in it.

The blueprint is the class...the house is the object.  The people living in the house are data stored in the object's properties.

Abstraction: Abstraction means showing essential features and hiding non-essential features to the user.

For Example: Yahoo Mail...

When you provide the user name and password and click on submit button..It will show Compose,Inbox,Outbox,Sentmails...so and so when you click on compose it will open...but user doesn't
know what are the actions performed internally....It just Opens....that is essential; User doesn't know internal actions ...that is non-essential things...

For Example:Tv Remote..
Remote is a interface between user and tv..right. which has buttons like 0 to 10 ,on /of etc but we dont know circuits inside remote...User does not  need to know..Just he is using essential thing that is remote.


Encapsulation: Encapsulation means which binds the data and code (or) writing operations and methods in single unit (class).

For Example:
A car is having multiple parts..like steering,wheels,engine...etc..which binds together to form a single object that is car. So, Here multiple parts of cars encapsulates itself together to form a single object that is Car.

In real time we are using Encapsulation for security purpose...

Encapsulation = Abstraction + Data Hiding.


Inheritance: Deriving a new class from the existing class,is called Inheritance.
Derived(sub class) class is getting all the features from Existing (super class\base class) class and also incorporating some new features to the sub class.

For Example:

class Address
{
String name;
Srting H.no;
String Street name;
}
class LatestAddress extends Address
{
String City;
String State;
String Country;
}
public class Vishal
{
{
LatestAddress la = new LatestAddress();
//Assign variable accordingly...
}
}

In the above Example class LatestAddress getting all features from the Address class.
In the LatestAddress class we have total 6 properties..3 are inherited from Address class and 3 properties are
incorporated. So In the class Vishal we are declaring the object of class LatestAddress and then assign new variables using the properties of the previous base classes... So this is a nice example of inheritance..

Polymorphism :

Polymorphism means ability to take more than one form that an operation can exhibit different behavior at different instance depend upon the data passed in the operation.

1.We behave differently in front of elders, and friends. A single person is behaving differently at different time.

2.A software engineer can perform different task at different instance of time depending on the task assigned  to him .He can done coding , testing , analysis and designing depending on the task assign and the requirement.

3.Consider the stadium of common wealth games. Single stadium but it perform multiple task like swimming, lawn tennis etc.

4. If a girl is married and mother of 2 children doing teaching job then  she is a women first ,, teacher in a school when she is in school,,wife of someone at home,, mother of her children,, and obvious daughter of someone & may be girl friend of someone (just kidding) means a woman plays different roles at different times dats the polymorphism (many forms).

Summary:
OOPs have following features:

1. Object             - Instance of Class
2. Class               - Blue print of Object
3. Encapsulation    - Protecting our Data
4. Polymorphism   - Different behaviors at different instances
5. Abstraction        - Hiding our irrelevant Data
6. Inheritence        - One property of object is acquiring to another property of object

Content From:dotnetvishal

Monday, 27 June 2011

FrameLayout in Android

FrameLayout is designed to display a single item at a time. You can have multiple elements within a FrameLayout but each element will be positioned based on the top left of the screen. Elements that overlap will be displayed overlapping. I have created a simple XML layout using FrameLayout that shows how this works.

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView
        android:src="@drawable/ic_launcher"
        android:scaleType="fitCenter"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"/>
    <TextView
        android:text="http://androidsurya.blogspot.in/"
        android:textSize="30sp"
        android:textColor="@android:color/holo_blue_bright"
        android:textStyle="bold"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:gravity="center"/>
</FrameLayout>



 


Here is the result of this XML.

You can see I had both the ImageView and TextView fill the parent in both horizontal and vertical layout. Gravity specifies where the text appears within its container, so I set that to center. If I had not set a gravity then the text would have appeared at the top left of the screen.
FrameLayout can become more useful when elements are hidden and displayed programmatically. You can use the attribute android:visibility in the XML to hide specific elements. You can call setVisibility from the code to accomplish the same thing. The three available visibility values are visible, invisible (does not display, but still takes up space in the layout), and gone (does not display, and does not take space in the layout).





AbsoluteLayout in Android

AbsoluteLayout is based on the simple idea of placing each control at an absolute position.  You specify the exact x and y coordinates on the screen for each control.  This is not recommended for most UI development (in fact AbsoluteLayout is currently deprecated) since absolutely positioning every element on the screen makes an inflexible UI that is much more difficult to maintain.  Consider what happens if a control needs to be added to the UI. You would have to change the position of every single element that is shifted by the new control.

Here is a sample Layout XML using AbsoluteLayout.
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_x="10px"
        android:layout_y="5px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_x="10px"
        android:layout_y="110px"
        android:text="First Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:layout_x="150px"
        android:layout_y="100px"
        android:width="100px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_x="10px"
        android:layout_y="160px"
        android:text="Last Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
        <EditText
        android:layout_x="150px"
        android:layout_y="150px"
        android:width="100px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</AbsoluteLayout>
Note how each element has android:layout_x and android:layout_y specified. Android defines the top left of the screen as (0,0) so the layout_x value will move the control to the right, and the layout_y value will move the control down. Here is a screenshot of the layout produced by this XML.
AbsoluteLayout

Sunday, 26 June 2011

Create an Android Emulator Device in eclipse

The Android tools include an emulator. This emulator behaves like a real Android device in most cases and allow you to test your application without having a real device. You can emulate one or several devices with different configurations. Each configuration is defined via an "Android Virtual Device" (AVD). To define an AVD press the device manager button, press "New" and enter the following.

AVD


New AVD


Settings for a new AVD

We will select the box "Enabled" for Snapshots. This will make the second start of the virtual device much faster.
At the end press the button "Create AVD".This will create the device and display it under the "Virtual devices". To test if your setup is correct, select your device and press "Start".
After (a long time) your device should be started.

Running AVD

Android AbsoluteLayout Example

A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:
  • Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
  • Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.
Write the XML:
Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements.
Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout.

Example:

XML layout that uses a vertical LinearLayout to hold a TextView and a Button:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Hello, I am a TextView" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" />
</LinearLayout>


After you've declared your layout in XML, save the file with the .xml extension, in your Android project's res/layout/ directory, so it will properly compile. 
 
Load the XML Resource:
When you compile your application, each XML layout file is compiled into a View resource. You should load the layout resource from your application code, in your Activity.onCreate() callback implementation. Do so by calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name
For example, if your XML layout is saved as main_layout.xml, you would load it for your Activity like so:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);
}
The onCreate() callback method in your Activity is called by the Android framework when your Activity is launched (see the discussion about lifecycles, in the Activities document).

This information from Android developers site(for more information):-http://developer.android.com/guide/topics/ui/declaring-layout.html#load

An Android layout is a class that handles arranging the way its children appear on the screen.  Anything that is a View (or inherits from View) can be a child of a layout. All of the layouts inherit from ViewGroup (which inherits from View) so you can nest layouts.  You could also create your own custom layout by making a class that inherits from ViewGroup.
The standard Layouts are:
AbsoluteLayout
FrameLayout
LinearLayout
RelativeLayout
TableLayout



Monday, 20 June 2011

Apply Theme in Android

In Android SDK so many  predefine themes are theier, you can change the theme by adding a code in the file AndroidManifest.xml in your Project.

Inside Application tag to take effect on whole Application:
<application android:icon="@drawable/icon" android:label="@string/app_name"
 android:theme="@android:style/Theme.Black"
 >


Inside Activity tag to take effect on individual Activity:
  <activity android:name=".TestThemeActivity"
              android:label="@string/app_name"
              android:theme="@android:style/Theme.Light"
              >

How to Set Screen Orientation portrait or landscape

Their is 2 ways to set Screen Orientation:

First Way:
In Android manifest file(manifest.xml)just add this to the activity attribute tag for portrait add this
android:screenOrientation="portrait"
For landscape :
android:screenOrientation="landscape"

Second Way:
Using code also we can set  Screen Orientation .
In Activity onCreate() method 
For Landscape:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
For  portrait:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
But you must add these line in OnCreate() and before setContentView(). in your Activity.

Sunday, 19 June 2011

Important Android component's

An Android application consists out of the following parts:

  • Activity - Represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application.
  • Views - The User interface of an Activities is build with widgets classes which inherent from "android.view.View". The layout of the views is managed by "android.view.ViewGroups".
  • Services - perform background tasks without providing an UI. They can notify the user via the notification framework in Android.
  • Content Provider - provides data to applications, via a content provider your application can share data with other applications. Android contains a SQLite DB which can serve as data provider
  • Intents are asynchronous messages which allow the application to request functionality from other services or activities. An application can call directly a service or activity (explicit intent) or ask the Android system for registered services and applications for an intent (implicit intents). For example the application could ask via an intent for a contact application. Application register themself to an intent via an IntentFilter. Intents are a powerful concept as they allow to create loosely coupled applications.
  • Broadcast Receiver - receives system messages and implicit intents, can be used to react to changed conditions in the system. An application can register as a broadcast receiver for certain events and can be started if such an event occurs.

Other Android parts are Android Widgets or Live Folders and Live Wallpapers . Live Folders display any source of data on the homescreen without launching the corresponding application.

Security and permissions
Android defines certain permissions for certain tasks. For example if the application want to access the Internet it must define in its configuration file that it would like to use the related permission. During the installation of an Android application the user get a screen in which he needs to confirm the required permissions of the application.

Saturday, 18 June 2011

AndroidManifest.xml in Android.

AndroidManifest.xml

An Android application is described the file "AndroidManifest.xml". This file must declare all activities, services, broadcast receivers and content provider of the application. It must also contain the required permissions for the application. For example if the application requires network access it must be specified here. "AndroidManifest.xml" can be thought as the deployment descriptor for an Android application.

    
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="de.vogella.android.temperature"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Convert"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="9" />

</manifest> 
   

The "package" attribute defines the base package for the following Java elements. It also must be unique as the Android Marketplace only allows application for a specfic package once. Therefore a good habit is to use your reverse domain name as a package to avoid collisions with other developers.
"android:versionName" and "android:versionCode" specify the version of your application. "versionName" is what the user sees and can be any string. "versionCode" must be an integer and the Android Market uses this to determine if you provided a newer version to trigger the update on devices which have your application installed. You typically start with "1" and increase this value by one if you roll-out a new version of your application.
"activity" defines an activity in this example pointing to the class "de.vogella.android.temperature.Convert". For this class an intent filter is registered which defines that this activity is started once the application starts (action android:name="android.intent.action.MAIN"). The category definition (category android:name="android.intent.category.LAUNCHER" ) defines that this application is added to the application directory on the Android device. The @ values refer to resource files which contain the actual values. This makes it easy to provide different resources, e.g. strings, colors, icons, for different devices and makes it easy to translate applications.
The "uses-sdk" part of the "AndroidManifest.xml" defines the minimal SDK version your application is valid for. This will prevent your application being installed on devices with older SDK versions.

R.java, Resources and Assets

The directory "gen" in an Android project contains generated values. "R.java" is a generated class which contains references to resources of the "res" folder in the project. These resources are defined in the "res" directory and can be values, menus, layouts, icons or pictures or animations. For example a resource can be an image or an XML files which defines strings.
If you create a new resources, the corresponding reference is automatically created in "R.java". The references are static int values, the Android system provides methods to access the corresponding resource. For example to access a String with the reference id "R.string.yourString" use the method getString(R.string.yourString)); Please do not try to modify "R.java" manually.
While the directory"res" contains structured values which are known to the Android platform the directory "assets" can be used to store any kind of data. In Java you can access this data via the AssetsManager and the method getAssets().

Activities and Layouts

The user interface for Activities is defined via layouts. Layouts are at runtime instances of "android.view.ViewGroups". The layout defines the UI elements, their properties and their arragement. UI elements are based on the class "android.view.View". ViewGroup is a subclass of View A and a layout can contain UI components (Views) or other layouts (ViewGroups). You should not nestle ViewGroups to deeply as this has a negativ impact on performance.
A layout can be defined via Java code or via XML. You typically uses Java code to generate the layout if you don't know the content until runtime; for example if your layout depends on content which you read from the internet.
XML based layouts are defined via a resource file in the folder "/res/layout". This file specifies the view groups, views, their relationship and their attributes for a specific layout. If a UI element needs to be accessed via Java code you have to give the UI element an unique id via the "android:id" attribute. To assign a new id to an UI element use "@+id/yourvalue". By conversion this will create and assign a new id "yourvalue" to the corresponding UI element. In your Java code you can later access these UI elements via the method findViewById(R.id.yourvalue).
Defining layouts via XML is usually the preferred way as this separates the programming logic from the layout definition. It also allows to define different layouts for different devices. You can also mix both approaches.

Activities and Lifecyle

The operating system controls the life cycle of your application. At any time the Android system may stop or destroy your application, e.g. because of an incoming call. The Android system defines a life cycle for an activities via pre-defined methods. The most important methods are:
  • onSaveInstanceState() - called if the activity is stopped. Used to save data so that the activity can restore its states if re-started
  • onPause() - always called if the Activity ends, can be used to release ressource or save data
  • onResume() - called if the Activity is re-started, can be used to initiaze fields

The activity will also be restarted if a so called "configuration change" happens. A configuration change for examples happens if the user changes the orientation of the device (vertical or horizontal). The activity is in this case restarted to enable the Android platform to load different resources for these configuration, e.g. layouts for vertical or horizontal mode. In the emulator you can simulate the change of the orientation via CNTR+F11.
You can avoid a restart of your application for certain configuration changes via the configChanges attribute on your activity definition in your AndroidManifest.xml. The following activity will not be restarted in case of orientation changes or position of the physical keyboard (hidden / visible).

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

Android SQLite Database Viewer or Debuging with Stetho

Every Android Developer uses SQLite Database to store data into the Android Application data. But to view the data in SQLite have a lot of...