Android4me

Monday, 5 May 2014

How to take screen shot via programmatically particular view in Android

How to take screen shot  via programmatically particular view in Android

This post about how take screen shot particular via program.see the below example.

I have create three views
1.map
2.button
3.imageview
I tried to take screen shot of Map view.

Activity code

package com.vj.screencapture;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import android.support.v4.app.FragmentActivity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;


public class MainActivity extends FragmentActivity {
        ImageView im;
         LinearLayout linerlay;
         GoogleMap gMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        SupportMapFragment mapFrag = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
          gMap = mapFrag.getMap();
          gMap.setMyLocationEnabled(true);
          gMap.getUiSettings().setZoomControlsEnabled(true);
          gMap.getUiSettings().setCompassEnabled(true);
          linerlay = (LinearLayout)findViewById(R.id.linearLayout);
       
          im = (ImageView)findViewById(R.id.imageView1);
        Button btn = (Button)findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View v) {
                            View v1 = im.getRootView().findViewById(R.id.map);
                 v1.setDrawingCacheEnabled(true);
                 Bitmap bm = v1.getDrawingCache();
                 BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
                           im.setImageBitmap(bm);
                     }
              });
      
    }


  
}


Before Taking  Screen Shot


Before Take Screen Shot of Map View


View v1 = im.getRootView().findViewById(R.id.map);
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
im.setImageBitmap(bm);


xml code.


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.vj.screencapture.MainActivity"
    tools:ignore="MergeRootFrame" >

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <fragment
            android:id="@+id/map"
            android:layout_width="356dp"
            android:layout_height="250dip"
            class="com.google.android.gms.maps.SupportMapFragment" />

        <Button
            android:id="@+id/button1"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/map_capture_btn" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="200dp" />
    </LinearLayout>

</FrameLayout>




Friday, 2 May 2014

Top 50 Android Interview Questions And Answers


1) What is Android?

It is an open-sourced operating system that is used primarily on mobile devices, such as cell phones and tablets. It is a Linux kernel-based system that’s been equipped with rich components that allows developers to create and run apps that can perform both basic and advanced functions.


2) What Is the Google Android SDK?

The Google Android SDK is a toolset that developers need in order to write apps on Android enabled devices. It contains a graphical interface that emulates an Android driven handheld environment, allowing them to test and debug their codes.


3) What is the Android Architecture?

Android Architecture is made up of 4 key components:

- Linux Kernel
- Libraries
- Android Framework
- Android Applications


4) Describe the Android Framework.

The Android Framework is an important aspect of the Android Architecture. Here you can find all the classes and methods that developers would need in order to write applications on the Android environment.


5) What is AAPT?

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.


6) What is the importance of having an emulator within the Android environment?

The emulator lets developers “play” around an interface that acts as if it were an actual mobile device. They can write and test codes, and even debug. Emulators are a safe place for testing codes especially if it is in the early design phase.


7) What is the use of an activityCreator?

An activityCreator is the first step towards the creation of a new Android project. It is made up of a shell script that will be used to create new file system structure necessary for writing codes within the Android IDE.


8 ) Describe Activities.

Activities are what you refer to as the window to a user interface. Just as you create windows in order to display output or to ask for an input in the form of dialog boxes, activities play the same role, though it may not always be in the form of a user interface.


9) What are Intents?

Intents displays notification messages to the user from within the Android enabled device. It can be used to alert the user of a particular state that occurred. Users can be made to respond to intents.


10) Differentiate Activities from Services.

Activities can be closed, or terminated anytime the user wishes. On the other hand, services are designed to run behind the scenes, and can act independently. Most services run continuously, regardless of whether there are certain or no activities being executed.


11) What items are important in every Android project?

These are the essential items that are present each time an Android project is created:

- AndroidManifest.xml

- build.xml

- bin/

- src/

- res/

- assets/


12) What is the importance of XML-based layouts?

The use of XML-based layouts provides a consistent and somewhat standard means of setting GUI definition format. In common practice, layout details are placed in XML files while other items are placed in source files.


13) What are containers?

Containers, as the name itself implies, holds objects and widgets together, depending on which specific items are needed and in what particular arrangement that is wanted. Containers may hold labels, fields, buttons, or even child containers, as examples.


14) What is Orientation?

Orientation, which can be set using setOrientation(), dictates if the LinearLayout is represented as a row or as a column. Values are set as either HORIZONTAL or VERTICAL.


15) What is the importance of Android in the mobile market?

Developers can write and register apps that will specifically run under the Android environment. This means that every mobile device that is Android enabled will be able to support and run these apps. With the growing popularity of Android mobile devices, developers can take advantage of this trend by creating and uploading their apps on the Android Market for distribution to anyone who wants to download it.


16) What do you think are some disadvantages of Android?

Given that Android is an open-source platform, and the fact that different Android operating systems have been released on different mobile devices, there’s no clear cut policy to how applications can adapt with various OS versions and upgrades. One app that runs on this particular version of Android OS may or may not run on another version. Another disadvantage is that since mobile devices such as phones and tabs come in different sizes and forms, it poses a challenge for developers to create apps that can adjust correctly to the right screen size and other varying features and specs.


17) What is adb?

Adb is short for Android Debug Bridge. It allows developers the power to execute remote shell commands. Its basic function is to allow and control communication towards and from the emulator port.


18) What are the four essential states of an activity?

- Active – if the activity is at the foreground

- Paused – if the activity is at the background and still visible

- Stopped – if the activity is not visible and therefore is hidden or obscured by another activity

- Destroyed – when the activity process is killed or completed terminated


19) What is ANR?

ANR is short for Application Not Responding. This is actually a dialog that appears to the user whenever an application have been unresponsive for a long period of time.


20) Which elements can occur only once and must be present?

Among the different elements, the and elements must be present and can occur only once. The rest are optional, and can occur as many times as needed.


21) How are escape characters used as attribute?

Escape characters are preceded by double backslashes. For example, a newline character is created using ‘\\n’


22) What is the importance of settings permissions in app development?

Permissions allow certain restrictions to be imposed primarily to protect data and code. Without these, codes could be compromised, resulting to defects in functionality.


23) What is the function of an intent filter?

Because every component needs to indicate which intents they can respond to, intent filters are used to filter out intents that these components are willing to receive. One or more intent filters are possible, depending on the services and activities that is going to make use of it.


24) Enumerate the three key loops when monitoring an activity?

- Entire lifetime – activity happens between onCreate and onDestroy

- Visible lifetime – activity happens between onStart and onStop

- Foreground lifetime – activity happens between onResume and onPause


25) When is the onStop() method invoked?

A call to onStop method happens when an activity is no longer visible to the user, either because another activity has taken over or if in front of that activity.


26) Is there a case wherein other qualifiers in multiple resources take precedence over locale?

Yes, there are actually instances wherein some qualifiers can take precedence over locale. There are two known exceptions, which are the MCC (mobile country code) and MNC (mobile network code) qualifiers.


27) What are the different states wherein a process is based?

There are 4 possible states:

- foreground activity

- visible activity

- background activity

- empty process


28) How can the ANR be prevented?

One technique that prevents the Android system from concluding a code that has been responsive for a long period of time is to create a child thread. Within the child thread, most of the actual workings of the codes can be placed, so that the main thread runs with minimal periods of unresponsive times.


29) What role does Dalvik play in Android development?

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.


30) What is the AndroidManifest.xml?

This file is essential in every application. It is declared in the root directory and contains information about the application that the Android system must know before the codes can be executed.


31) What is the proper way of setting up an Android-powered device for app development?

The following are steps to be followed prior to actual application development in an Android-powered device:

-Declare your application as “debuggable” in your Android Manifest.

-Turn on “USB Debugging” on your device.

-Set up your system to detect your device.


32) Enumerate the steps in creating a bounded service through AIDL.

1. create the .aidl file, which defines the programming interface

2. implement the interface, which involves extending the inner abstract Stub class as well as implanting its methods.

3. expose the interface, which involves implementing the service to the clients.


33) What is the importance of Default Resources?

When default resources, which contain default strings and files, are not present, an error will occur and the app will not run. Resources are placed in specially named subdirectories under the project res/ directory.


34) When dealing with multiple resources, which one takes precedence?

Assuming that all of these multiple resources are able to match the configuration of a device, the ‘locale’ qualifier almost always takes the highest precedence over the others.


35) When does ANR occur?

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.


36) What is AIDL?

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.


37) What data types are supported by AIDL?

AIDL has support for the following data types:

-string

-charSequence

-List

-Map

-all native Java data types like int,long, char and Boolean


38) What is a Fragment?

A fragment is a part or portion of an activity. It is modular in a sense that you can move around or combine with other fragments in a single activity. Fragments are also reusable.


39) What is a visible activity?

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.


40) When is the best time to kill a foreground activity?

The foreground activity, being the most important among the other states, is only killed or terminated as a last resort, especially if it is already consuming too much memory. When a memory paging state has been reach by a foreground activity, then it is killed so that the user interface can retain its responsiveness to the user.


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

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.


42) How do you remove icons and widgets from the main screen of the Android device?

To remove an icon or shortcut, press and hold that icon. You then drag it downwards to the lower part of the screen where a remove button appears.


43) What are the core components under the Android application architecture?

There are 5 key components under the Android application architecture:

- services

- intent

- resource externalization

- notifications

- content providers


44) What composes a typical Android application project?

A project under Android development, upon compilation, becomes an .apk file. This apk file format is actually made up of the AndroidManifest.xml file, application code, resource files, and other related files.


45) What is a Sticky Intent?

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.


46) Do all mobile phones support the latest Android operating system?

Some Android-powered phone allows you to upgrade to the higher Android operating system version. However, not all upgrades would allow you to get the latest version. It depends largely on the capability and specs of the phone, whether it can support the newer features available under the latest Android version.


47) What is portable wi-fi hotspot?

Portable Wi-Fi Hotspot allows you to share your mobile internet connection to other wireless device. For example, using your Android-powered phone as a Wi-Fi Hotspot, you can use your laptop to connect to the Internet using that access point.


48) What is an action?

In Android development, an action is what the intent sender wants to do or expected to get as a response. Most application functionality is based on the intended action.


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

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.


50) What language is supported by Android for application development?

The main language supported is Java programming language. Java is the most popular language for app development, which makes it ideal even for new Android developers to quickly learn to create and deploy applications in the Android environment.

Core Java Interview Questions and Answers

Core Java Interview Questions and Answers
1.Whta is Final Variable?
If you make any variable as final, you cannot change the value of final variable.
2.What is final Method?
Final method can’t be overridden.
3.What is Final class ?
Final Class Can’t be inherited.
4.What is Constructor ?
Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation.
5.What is the puspose of default constructor?
The Default Constructor  provide the default values to the objects.The java compiler creates a default constructor only if there is no constructor in the class.
6.Can you make a constructor final?
No,Constructor can’t be final.
7.What is static variable ?
* Static variable is used to refer the common property of all objects (that is not unique for each object)
* Static variable gets memory only once in class area at the time of class loading.
8.What is Static Method
* A ststic method belongs to the class rather than object of a class.
* A static method can be invoked without the need for creating an instance of a class.
* static method can access static data member and can change the value of it.
9. Why main method is static?
Because object is not required to call static method if It were non static method, jvm creats object first then call main() method that will lead to the problem of extra memory allocation.
10.What is static block?
* Is used to initialize the static data member.
* It is excuted before main method at the time of classloading.
11. What is difference between static (Class)method and instance method?
Static Method
*A method i.e. declared as static is known as static method.
*Object is not  required to call static method.
* Non-static (Instance) members cannot be accessed in static context(Static block and static nested class) directly.
Instance Method.
·         A method i.e. not declared as static is know as instance method.
·         Object is required to call instance methods.
·         Static and non-static variable both can be accessed in instance methods.
12.Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class.
13. What is method overloading?
If  a class have multiple methods by same name but different parameters, it is known as method overloading. It increases the readability of the program.
14.Can we overload main() method?
Yes , ofcourse! You can have many main() methods in a class by overloading the main method.
15. What is method overriding?
* If a subclass  provides a specifiv implementation of a method that is already provided by its parent class,it is known as method overloading.
* It is used for runtime polymorphism and to provide the specific implementation of the method.
16.Can we override static method?
No, you can’t override the static method because they are the part of class not oject.
17. Why we cannot override static method?
It is because the static  method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.


18. Difference between method Overloading and Overriding?
1.Overloading
*.Method overloading increases the readability of the program.
*.Method overloading is occurs within the class.
*In this case, parameter must be different.
2.Overriding
* Method overriding provides the specific  implementation of the method that is already provided by its super class.
* Method overriding occurs in two classes that have IS-A relationship.
* In this case, parameter must be same.
19. What is polymorphism?
* Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather that at compile-time.
*In this process, an overridden method is called through the reference variable of a superclass.
*The determination of the method to be called is based on the object being referres to by the reference variable.
20.What is Abstraction?
*Abstraction is a process of hiding the implementation details and showing only functionality to the user.
* Abstraction lets you focus on what the object does instead of how it does it.
21. What is abstract class ?
*A class that is declared as abstract is known as abstract class.
* It needs to be extended and its method implemented.
* It cannot be instantiated.


22.can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.
23. Can you use abstract and final both with a method?
No Because abstract method needs to be overridden whereas you can’t override final method.
24.What is Interface?
*Interface is a blueprint of a class that have static constants and abstract methods.
* it can be used to achive fully abstraction and multiple inheritance.
25. Can you declare an interface method static ?
No, because methods of an interface is abstract bydefault, and static and abstract keywords can’t be used together.
26.What is different between abstract class and interface?
1.Abstract Class
 *An abstract class can have method body(non-abstract methods).
*An abstract class can have instance variables.
*An abstract class can have constructor.
*An abstract class can have static methods.
*You can extends one abstract class.
2.Interface
*Interface have only abstract methods.
*An interface cannot have instance variable.
*Interface cannot have constructor.
*Interface cannot have static methods.
*You can implement multiple interfaces.
27.What  is package?
*A package is a group of similar type of class interfaces and subpackages.
*It provides access protection and removes naming collision.
28. What is Exception Handling?
*Exception handling is a mechanism to handle  errors.
*It is mainly used to handle checked exception.
29.What is difference  between checked exception and Unchecked Exception?
1.Checked Exception
*The classes that extend throwable class except RuntimeException and Error are Known as checked excetion e.g.IOExcetion,SQLExcetion etc. Checked exception are checked at complie-time.
2.Unchecked Exception.
The classes that extend RuntimeExcetion are known as unchecked exception
e.g. ArithmeticException,NullpointerException etc.
*Unchecked exception are not checked at complie-time.
30.What is Difference Between throw and throws?
1.throw
*throw is used to expilicity throw an exception.
*checked exception can not be propagated with throw only.
* throw is followed by an instance.
*throw is used within the method.
*you cannot throw multiple exception.
2.throws
*throws is used to declare an exception
*checked exception can be propagated with throws.
* throws is followed by lcass.
*throws is used with the method signature.
*You can declare multiple exception e.g.
public void method() throws IOException,SQLException.

31.What is the meaning of immutable in terms of String?
*The simple meaning of immutable is unmodifiable or unchangeable.
*Once string object has been created, its values can’t be changed.
32.basic difference between string and string buffer object?
*String is an immutable object.
*String is a mutable object.
33.Difference between StringBuffer and StringBuilder?
String Buffer is synchronized whereas StringBuilder is not synchronized.
34.What is multithreading?
Multithreading is a process of executing multiple threads simultaneously.
 Its main advantage is:
*Threads share the same address space.
*Thread is lightweight.
*Cost of communication between process is low.
35.What is thread?
*A thread is a lightweight subprocess.It is a separate path of execution .
*It is called separate path of execution because each thread runs in a separate stack frame.
36.What is synchronization?
Synchronization is the capability of control the access of multiple threads to any shared resource .
It is used
1.To prevent thread interference.
2.To prevent consistency problem.
37.What is the purpose of synchronized block?
1.Synchronized block is used to lock an object for any shared resource.
2.Scope of synchronized  block is smaller than the method.
38.What is Garbage Collection?
*Garbage collection is a process of reclaiming the runtime unused objects.
*It is performed for memory management.
39.What is the purpose of finalize() method?
*finalize() method is invoked just before the object is garbage collected.
 * It is used to send request to JVM to perform garbage collection.
40.Different between final,finally and finalize?
Final: final is a keyword , final can be variable , method or class. You can,t change the value of final variable, can’t override final method, can’t inherit final class.
Finally : finalyy block is used in exception handling. Finally block is always executed.
Finalize():  finalize() method is used in garbage collection. finalize()     method is invoked just before the oject is garbage collected. The finalize() method  can be used to perform any cleanup processing.
41.What is serialization ?
Serialization is a process of writing the state of an object into a byte stream.
42.What is difference between ArrayList and Vector?
1.ArrayList
*ArrayList is not synchronized.
2.ArrayList  is not a legacy class.
3.ArrayList increases its size by 50% of the array size.
2.Vector
*Vector is synchronized
*Vector is a legacy class.
3.Vector increases its size by doubling the array size




43.Different Between HashMap and Hashtable?
1.HashMap
*HashMap is not synchronized
*HashMap can contain one null key and multiple null values.
2.Hashtable
*Hashtable is synchronized.
*hashtable cannot contain any null key nor value.
44.Different Between Iterator and Enumeration?
1.Iterator
*Iterator can traverse legacy and non-legacy elements.
*Iterator is fail-fast
*Iterator is slower than Enumeration
2.Enumeration
*Enumeration can traverse only legacy elements.
*Enumeration is not fail-fast.
*Enumeration is faster than Iterator.
45.What is singleton class?
Singleton class means that any given time only one instance of the class is present,in one JVM.