Saturday, June 18, 2016

Android Projects with Code

Android Projects with code:

This blog can be really useful:
1. If you are looking out for android projects to put in your resume.
2.If you are looking for android project code with complete explanation.
3.If you are searching for job on android experience and looking out for projects.

List of android projects available with us with code and documentation:

1. Event Scheduler reminder application - android application
2. Daily expense tracker 
3. Internet FM radio - Live songs streaming from server
4. MedKart - purchasing medicines online
5. Mobile Theft Security
6. Help Zone - Nearest hospital help
7. Safe drive detection - while drive bikes
8. SMS scheduler
9. Interest and EMI calculator
10. Birthday Wisher
11. EBookReader
12. Educational Game For Kids
13. Finance Management
14. Mobile Attendance management system.
15. Mobile Job Portal
16. Shopping List
17. Restaurant Management System

Fee: Code with documentation INR 2000/-
        Code + Documentation + Skype Explanation INR 5000/-

For more details, contact Satish@+91-9740588499.

Saturday, January 24, 2015

Experienced Android Interview Questions - 4

Company - Tarang

1. How do you join 2 Notifications?
//Below are the steps to create notifications.
//create variables
NotificationManager nm;
Notification n;
//initialize all the variables.
//step1: create notification manager object
nm = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
//step2: prepare the ticker text and ticker icon
n = new Notification(R.drawable.ic_launcher,
"Urgent Msg", System.currentTimeMillis());
//step3: create intent to start activity
Intent in = new Intent(getApplicationContext(),
MyNotifcationActivity.class);
//spte4: prepare the pending intent for above intent
PendingIntent pi = PendingIntent.getActivity(
getApplicationContext(),
0,
in,
0);
//step5: set the latest event information & pass the pi
n.setLatestEventInfo(getApplicationContext(),
"Urgent Message",
"Please click here to read the message",
pi);

n.flags = n.flags | Notification.FLAG_AUTO_CANCEL;
//step6: use notification mgr to notify or to push
nm.notify(1, n); //1 is the id of this notification.
-------------------------------------------------------------
Now if you want to merge two notifications, when you are notifying
       next time, use same id of previous notification. "1"


2. How do you insert data into SQLite DB.
//create a table with some columns in SQLiteOpenHelper
db.execSQL("Create table emp(_id integer primary key," +
"ename text, esal integer);");

/*function to insert values into emp table.
  *this function assumes user will pass two values to insert
 *to insert into emp table */

public void insertEmp(String name, int sal){
//we will create content values to insert
ContentValues cv = new ContentValues();
cv.put("ename", name);
cv.put("esal", sal);
//now we have to insert
sdb.insert("emp", null, cv);
}

Company - Tavant

1. How do you register a Fragment?
To register a fragment with an xml file, go to xml file and use <fragment> tag with name as the complete package qualifier name of your fragment class. For eg:

<fragment android:id="@+id/myfrag"
   android:name="com.skillgun.fragments.MyFrag"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="2"/>

Once you load this xml file using your activity, automatically Android will load an instance of your Fragment class (i.e object of MyFrag class)

2. In Manifest file what is config.uses and config.orientation/config.keyboard
Generally when ever there is a configuration change in the phone, like screen orientation changes [or] soft keyboard availability [or] language changes, in these scenarios android will automatically kill and restart your activity to take the new resources effective.

But you have the choice of requesting android to not restart your activity, and you can handle configuration changes on your own.
This can be done by using android:configChanges property in your activity tag, of your manifest.xml file.

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

The above activity tag says to android that, don't kill and restart my activity in case of screen orientation or keyboard availability.
Instead android will call  onConfigurationChanged() of your activity.

<uses-configuration> tag indicates what all hardware and software features are required for your application.

3. In HTTP request what header will do?
HTTP Request header can have various things based on your requirement.

It can have
1. content-type.
   for eg content-type is json or xml
2. you can also give authorization token in header.
3. you can also set "accept-charset" for the header.

4. Implement Async Task functionality (touching UI from worker thread), by using Handlers.
// Here is an example of creating our own handlers to do inter thread communication. I am creating a service which extends an intentservice.
// Since we can't touch UI from intentservice, we are creating a handler
// to communicate with main thread to touch UI by using handlers.

public class MyService1 extends IntentService {

MyHandler mh; // variable for our handler

@Override
public void onCreate() {
// create Handler for with MainThread's looper
mh = new MyHandler(getMainLooper());
super.onCreate();
}
// implement Handler to communicate with Main thread.
class MyHandler extends Handler{
public MyHandler(Looper lp){
super(lp);
}
@Override
public void handleMessage(Message msg) {
// What ever logic you write here, will get executed
                        // in Main thread's context, since it is having main
                        // thread's looper
Toast.makeText(getApplicationContext(),
"intent service", 0).show();
super.handleMessage(msg);
}
}

public MyService1() {
super("My-Wthread");
}

@Override
protected void onHandleIntent(Intent intent) {
Message m = mh.obtainMessage();
m.arg1 = 1;
// send message to our handler, which will push to main thread.
mh.sendMessage(m);
}
}

5. What is URI?
URI : Uniform Resource Indicator. Used to access or send data in Android.

Just like how we access the data stored in the web servers by using URLs (Uniform Resource Locators), Similarly we send or receive data in Android by using URI's

Some of the examples for URI's:
for telephone numbers we use "tel:<number>"
for content stored in databases we use "content:// ...."
for emails we use "email: <email>"

This is similar to how we access gmail by using "http://gmail.com"

6. What is system.out.println? Why we use this in Java? (java)
This line System.out.println() is used to print the arguments passed to it on standard output.
System is the final class, out is the public static final variable of PrintStream class, and println() is the function of PrintStream class.

7. How do you iterate data from your cursor if your cursor have some data?
Cursor c = mdb.getAllEmp(); // lets say this will get all the rows of your employee table.

if(c!=null){ // first check if cursor is not null
while(c.moveToNext()){   // this line will move the cursor to next valid record, proceed until last record is reached.
                           // here read the cursor values.. and proceed
                           ...
                        }
                 }
                             

8. How do you load fragment into Activity?
1.Create a layout for your fragment
2.Implement a fragment by defining a class for your fragment code, by extending Fragment class.
3.Return your fragment layout from your fragment's life cycle funciton onCreateView()
4.Define an xml file for your activity, which has <fragment> tag, which will contain your fragment class

Now run your program, once android sees <fragment> tag in your activity's layout file, it will go and create object for your fragment and loads it into
your activity.


9. What is Handler.message and Handler.post?
These are the mechanisms to do inter thread communication.
For example we have thread-1 and thread-2, now thread-2 want to communicate with thread-1.
For this we have to create a handler for thread-1 using its looper. 
Once we create handler for thread-1, thread-2 can use that handler to send messages to thread-1.
Handler.Message is the class which we use to create messages to send to other threads.
Handler.post() is the method, which we use to post a Runnable Interface object to a thread's handler.
You can use Handler.sendMessage() to send a simple messages created by Handler.Message class.


Example of sending message to other threads:
// First create a handler implementation
class MyHandler extends Handler{
public MyHandler(Looper l){
super(l);
}
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), 
"thread created", 
0).show();
super.handleMessage(msg);
}
}

// create object for your handler , pass other thread's looper.
MyHandler mh = new MyHandler(getMainLooper());
// create a message
Message m = new Message();
m.arg1 = 1;
// pass that message to handler (mh) , which is connected to other thread.
mh.sendMessage(m);

10. How do you know whether your screen is in landscape/portrait mode to load fragments
// Solution : To know if you are in landscape or portrait mode

if(myCurrentActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) 
{
    // code to do for Portrait Mode
} else {
    // code to do for Landscape Mode         
}

11. What is the use of os.message?
This is the class used to create messages to pass between two threads.
Refer to above questions on how to do inter thread communication to understand Messages.

Experienced Android Interview Questions - 3

Company - provab

1. why to extend application class, how to access common variables in all activities? What is the use of Application class?
There are two contexts in Android.
1. Activity level context
2. Application level context

Application level context will be created while creating your application. There will be only one application context shared for all the components of your application.
So if you want to share some temporary variables with all the components of your application, then create your own class which extends Application class. Use setters and getters to share some variables in that class.

Note: Make sure that you give android:name as your class which extended Application class,in the <application .. >tab of manifest file.

The other uses of Application class is, if you want to do some task before loading your first activity, then write it in Application class's onCreate() method. Application class also has some useful methods which will get triggered in case of low memory, which you can use to check if your app is running on low memory to alert user.

2. what is viewholder?
ViewHolder is a technique used in Adapter's getView() method,
to reduce the no of findViewById() calls.
Adapters are intelligent enough to reuse the old views while user scrolls throught the adapter view elements. Programmer should check if convertView is not null, then reuse it rather than creating a new view for that row.
Apart from this we can optimize it more by reducing number of findViewById() calls by moving all those into ViewHolder class.
Programmer can also move some reusable components like arrays or database query results also into ViewHolder to avoid unncessery function calls.


3. what is beanclass?
A bean class is a plain old java class, which has
1. no argument constructor
2. all its fields as private with setters and getters
3. and implements Serializable.

Basically bean class can be used as an object which itself can hold other states and objects.
It implements serializable enabling the programmer to transfer it out of java memory, like into some streams, or hard disk, or database, or to some network. It enable java programmer to not loose an objects state while transferring into streams.

4. what is offline synchronization?
5. Do you know how to do facebook integration?
6. how will you create camera view to take picture with out intent and camera button?
7. how to upload apps to play store?
8. I have a list view with 100 items. But I want to show only 10 items initially and when I scroll down or up, then only I want to display the items dynamically. How to do it?
9. Why java allows only one public class in a given file?
10. If I close the application, will it destroy all the static variables?
Don't rely on static variables, because static variables may not be cleand properly on the application exit. 
Static variables will be created when the class containing them is loaded first or used first. They will be destroyed once JVM unloads that class from the memory.
But Android has a concept of empty process, which says your app may not be removed from the memory if it is frequently used by user, in which case your static variables will not be cleard of completely.
Better to rely on Application class which will be created properly on application startup time and will be cleard of once user exits app. This is the best way to share some temporary variables between the components.

Note: Static variables are considered as anti-design of android apps from ages.

Still if you want to rely on static variables due to some reasons, then try to understand what is the scope of that variable and try to initialize some null values to it on shutting down the last component which is accessing that variable. But again it is a complicated logic.

11. How to access variables globally, in all the activities of an application?

12. In MVC architecture, where is database stored?
In MVC (Model-View-Controller) architecture Model will interact with Database part.

13.How to handle when GPRS is not available while registering any form.(store or update data)
14. While running application if any call comes how to handle and which method is called?
15. Can we call SQLiteOpenHelper class from onStop() method of Activity?
16. How AsyncTask is useful? How it is different from normal thread?
17. How will you detect the exit of an application in android?
18. How to close all the components of an application and exit the application?

Friday, January 23, 2015

Experienced Android Interview Questions - 2

company - mportal

1. What is an Interface and What is an Abstract class? (java)
Abstract class: is an incomplete class. This is a kind of a house under construction which is not yet completed.
                            Since abstract classes are incomplete, you can't create any object for that class. It doesn't make any sense to create object.
                            But any one can inherit abstract classes to give extra definition for that class to make it more concrete.
                            Abstract class can contain 0 or more number of abstract methods. If it is having at least one abstract method, then
                            we have to make that class as abstract class.
                             A class will become abstract class, if we know only partial implementation of that class.
                             Abstract class can contain method definitions.

Interface: as name suggests, it is an interface between your class and out side world.
                  interfaces can contain only constants, method declarations, and nested types. It can't contain method definitions.
                  Just like an abstract class, you can't create object for an interface.
                  You can imagine interface just like a header file in c program. It tells what all the functionalities supported by your interface.
                 

2. Explain about Async Task with one use case
Async Task: is a way to achieve multi threading in android. It has some advantages over normal java threads.
                       1. You don't need to use any Thread keyword, every thing will be taken care by AsyncTask class internally.
                            It creates threads internally.
                        2. Since android follows single threaded UI model, where other threads can't touch UI components directly.
                             But from async task you can directly touch UI components from all the functions except from doInBackGround().

AsyncTask class will have 4 functions.
a. onPreExecute() - this is the first function to be called before calling doInBackGround(). This runs in UI thread. You can touch ui from this.
b. doInBackGround() - this runs in background thread created by AsyncTask class. Don't touch ui from this method.
                                         Write background heavy logic in this function, as it runs in background thread.
c. onProgressUpdate() - this function is used to update UI while performing background functionality. to execute this call publishProgress()
                                             this also runs in UI thread.
d. onPostExecute() - once doInBackGround() is finished this function will be called. If you want to update any UI after doInBackGround() use this                                
                                     function. This also runs in main ui thread.

Async task use case: If you want to upload some images to facebook server and want to update UI (progress bar) while uploading images using progress bar, then you can use AsyncTask.

3. What is Mutable and Imutable explain with examples? (java)
There are many concepts related to mutability and immutability.

General meaning:
Mutable : means changeable;   Immutable : means unchangeable.

Some of the Immutable concepts:
----------------------------------------------
Immutable classes : are also known as final classes. A class which you can't inherit (can't change the definition by extending it) is called as
immutable class. In some languages it is also called as shield classes. Eg: String class in java is immutable class, you can't inherit it.
use case: If you don't want any one to inherit your class and change the basic functionality of your class, then make it as immutable class.
This can be achieved by making your class as final class by using "final" keyword before your class.

Immutable variables (also know as final variables): also known as constants
Any variable that is declared as final, you can't modify its value.
eg: public static final double pi = 3.14; // we know that pi value will always remain same 3.14, no body can change its value. So we are declaring it as final , ie constant. So that no one can change its value.

Immutable methods (final methods): says, no body can modify or change my functionality.
Inherited classes (derived classes) can't override immutable methods.
use case: Framework generally gives lot of basic functionality where derived classes can't change. such kind of methods are made as final methods by using "final" keyword before that method name.

Immutable objects: (Note: don't misunderstand this with immutable variables)
an object for which we can't change the states(data) of it once it is set. If we can achieve this , then that object is called as immutable object.
For eg: String str = "hello";
In the above example hello is immutable, no body can change it. If you try to change it it will create a new string object.
String objects are examples of immutable objects.

4. Can class be immutable? (java)
Yes, a class can be immutable. You can make a class as final to make it immutable

Immutable classes : are also known as final classes. A class which you can't inherit (can't change the definition by extending it) is called as
immutable class. In some languages it is also called as shield classes. Eg: String class in java is immutable class, you can't inherit it.
use case: If you don't want any one to inherit your class and change the basic functionality of your class, then make it as immutable class.
This can be achieved by making your class as final class by using "final" keyword before your class.


5. Difference between Final ,Finally and Finalize (java)
final - means immutable. eg: final classes, final methods, final variables.
           once you say final, it is the final definition of that component, no one can change it.

finally - is used with try-catch block to make sure that you are cleaning all the system resources properly when an exception occurs.
             what ever the code you write, will be executed with out fail once try block exits.

finalize - is the method that will be executed(called) before that object is being garbage collected.
                Garbage collector will make sure that it will finalize() method of an object, before it cleans that object.
                Garbage collector will clean only java resources and java memory. In your program if you are using any non java resources like files,  
                sockets, graphic contexts, or allocating memory using a c program then garbage collector will not clean all those resources.
                It is the responsibility of the programmer to clean them properly, For that we use finalize method.
                Note: Don't depend too much on finalize() method to clean non java resources.

6. What is thread? Why we use Thread? (java)
Thread: is independent dispatch-able unit to cpu. each thread can execute an independent module in parallel with CPU.
               Thread is also known as light weight process. Each process can contain multiple threads.
               Threads will share the resources of its process.

Why to use a thread: Generally your CPU might have the capability of running multiple tasks at a time by using its threads.
                                      But programmer has to support this by creating multiple threads for his program where ever it is possible.
                                      If your program is having two modules, and there is no dependency between those two modules, then
                                      your program can run faster if you run both the modules at a time (in parallel). This can be done only
                                      if you are running those two modules in two different threads.

7. Tell me about Main Components in Android?
Android main components are Activity, service, Broadcast Receiver, and Content Provider.
For details information about these components please refer to developer.android.com

8. What are the layouts in Android?
Layouts are viewgroups, which can contain child views in it.
There are 4 basic layouts in android.

1. linear layout: displays child views in linear fashion (either horizontally or vertically).
2. frame layout: displays child views in stack architecture (one on top of each other). It is also used as place holder for the elements.
3. relative layout: displays child views in relative position to other child views. This is heavily used layout in android.
4. absolute layout: displays child views with absolute position. This is deprecated because of its absolute positioning.

9. What is a Broadcast Receiver?
Broadcast Receiver: is the component of android which gets triggered when ever android systems sends a broadcast announcement.
                                      Generally, when ever an important event happens in the phone (like battery low), android system will send a broad
                                      cast message to all the applications. Who ever is interested to catch that message can use Broadcast Receiver to
                                      handle that message.

Note: Broadcast receiver has a time limitation of 10 seconds. What ever you want to do in a receiver, you have to finish it off in 10 seconds.
           Else android may force close your receiver.

10. What is an Intent?
Intent: is a message passing mechanism between 2 components of android.
There are 2 use cases of intents.

1. You can start other component using intent, except content provider.
    eg: you can start one activity from other activity by using intent. 
           You can also start a service from an activity.

2. You can use intent to pass some data from one component to other component.
    Eg: you can pass username and password from login screen to home screen of your application.

There are two types of intents are there in android. a. Explicit intent b. Implicit intent.

11. How do you know whether GPS is on or Off in your moble?
//declare location manager
LocationManager lm;
//define location listner
private LocationListener ll = new LocationListener() {
@Override
public void onProviderEnabled(String provider) {
//called when user enables gps or wifi in the phone
}
@Override
public void onProviderDisabled(String provider) {
// called when user disables gps or wifi in the phone
}
};

//create location manager object
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//request for location updates
lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 
0, 0, ll);


12. If GPS is not on is there any other way to find the location?
If GPS is not available, then you can use NETWORK_PROVIDER which uses wi-fi signals or cell tower information to find out your mobile location.

13. What is a ViewGroup?
ViewGroup : is an invisible container of other child views or other view groups. Eg: LinearLayout is a viewgroup, which can contain other views in it.

14. How do we solve Resolution Problem
There are many solutions for this resolution problem:

1. Always use dps, don't use pixels
2. Use nine patch (.9.png) images in places of normal images. Normal png images won't stretch properly.
3. Use relative layouts where ever it is possible.
4. Don't give hard coded width and height, always mention height and width relative to parent view or layout.



Experienced Android Interview Questions - 1

Company : Beeonics

1. If you have multiple Broadcast receivers how do you identify for which application is it coming?
Ans:  if the question is how does Android sends broadcasted message to different application, then it is based on the action, data, and category present in the intent.
Android will perform action test, data & type test, and category test. If all the test are passing with any of the intent filters of receivers, then those receivers will be triggered.
If multiple receivers intent-filters are matching with the intent then all the receivers will be triggered. But there is no specific order if priority is not set in the intent filter.

2. How do you check memory leaks?
go to ddms, get the heap profiling dump.
generally .hprof files will be in /data/misc folder.
save the heap dump profile to desktop.
Now use eclipse memory analyzer to analyze the memory of your app.

source: http://developer.android.com/tools/debugging/ddms.html
source: http://kohlerm.blogspot.in/2009/04/analyzing-memory-usage-off-your-android.html


3. Do you require any key for development?
If you are planning to release any application into the market, then it is mandatory to sign your application with private key.
But at the initial stages, you can use debug key which is located in c:\users\<username>\.android folder.
But remember you can't release an application which is signed with your debug key. You have to sign with a private key obtained with keytool
command. keytool is a .bat file available in java\jdk\bin folder.

You can use keytool to create your own private key with password.
Note: Important to remember that don't ever forget your key and password, else it would become impossible to upgrade your application.
To upgrade your application you have to sign with same application.

More about how to create private key and how to use keytool, please refer to below official android link.
http://developer.android.com/tools/publishing/app-signing.html

4. How do you upload app into playstore?
If you want to upload an app into google play store, then follow below steps.
1. Create a private key to sign your application.
   Note: to create private key, use keytool command.
2. sign your application with private key.
   Go to file->export-> and select your private keystore to sign.
3. Go to https://play.google.com/apps/publish/signup/
4. If you are uploading your first app, then you have to pay one time reg
   fee of $25.
5. Go to developer console
6. Click on add new application +
7. Add apk and title , and follow with rest of the process.

5. How do you start push Notifications?
If this question is about sending a push notification to the client mobiles from the server, then Server side program has to be configured to use GCM (Google Cloud Messaging). Once the server is configured to use GCM and client android app also configured with GCM client framework, then GCM will automatically push the notifications from server to the client mobile by using GCM framework.

More about using GCM framework to send push notifications from server to client (android phones), follow this official android link.
http://developer.android.com/google/gcm/index.html
http://android-developers.blogspot.in/2013_06_01_archive.html

6. What is debugging mode?
You can build your application in 2 modes.
1. Debug Mode : Generally we use debug mode when we develop and test our application.
2. Release Mode : We use release mode, when we are about to release our application into play store.

Company : digipay
1. Can we create .apk file without eclipse?If yes how?
1. use javac to compile your java files
2. use dx tool to convert all .class files to single dex file
3. use aapt tool or apkbuilder tool to generate .apk file, which contains    manifest, .dex, and res.
   .apk is equivalent to .jar in java.
   aapt tool and dx tools are in android-sdk/platform-tools.
4. sign the apk file by using jarsigner tool of jdk/bin
5. zipalign your signed apk by using zipalign tool of android-sdk/tools

2. Can we show multiple activity at a time? If no why? Also asked what is activity?
In android activities are piled up on each other in a stack based architecture. System will display the activity which is on top of the activity stack, hence it is no possible to show 2 activities at a time.

But there is an option called ActivityGroup, which can contain and run multiple embedded activities in a screen. One such kind of ActivityGroup is TabActivity.
Note: TabActivity and ActivityGroup are deprecated, better to use Fragments to club multiple screens in a screen.

Fragment is the new technique added in 3.0 onwards, which are basically used to club different screens(panes) in a single wider screen sizes like Tablets.

Note: Don't use TabHost and TabActivity, as they are deprecated.
In place of them use ActionBar and fragments. ActionBar is something like TabHost in old versions. ActionBar also contains tabs, on clicking which it will display different fragments.

3. What is ADB? Any commands?
4. What is android? Where we can use android OS other than mobiles, tabs etc?
Android is O.S and framework to develope applicatins for mobiles and tablets.
Android is based on Linux O.S.
Android can be used in tvs, automobiles, and wears like watches, glasses etc.
Android is also used in kitchen utensils which is also called Google's smart kitchen.
Android can also be used in robots, washing machines, etc.

4. How to support text views for multiple screens?Suppose one mobile 3 inch another 7 inch?
When we are using a textview there is a possibility that our app may be downloaded into various screen size devices.
Based on the screen sizes we have to make sure our textview should grow and shrink, similarly the text size also should look compatible with the screen size. Below is the solution for this problem.

various screen sizes have various folders for dimensions.
eg:
res/values/dimens.xml will contain screen properties for normal screens.
res/values-sw600dp/dimens.xml will contain screen properties for screen width category 600 dp.
So try to declare different text sizes for different screen widths.
This will work perfectly with all screen sizes.

Note: Using sp or dp will not fix your issue.
Note: If you are not specifiying sp or dp, then giving wrap content or match_parent would be the best suggestion to solve the problem

5. what is aidl?
6. what is adapter?
7. What is min and max sdk version?
Manifest file has an option to tell what is the minium sdk version , and maximum sdk version your app can be downloded.
It simply says what all the various phone ranges your app supports or can be downloadable.

There is one more option target sdk, which says I have compiled and cross checked with this version and I am targeting for this version.
So that android system won't add any compatible library when your app is downloaded into a phone which is same as your target sdk version.


8. give one example for anr?

company: ivy mobility
1. Difference between Set and Array List? (java)
set interface: 1. Sets can't contain duplicate values (just like a mathematical set), 
                         2. Sets inherits collection and adds method to avoid duplications

There are 3 Set implementations:

1. hashset
   - uses hash table/ hashmap internally to store values, 
   - it is very fast compared to other two set implementations, 
   - it will not have any order while reading, 
   - it will not contain any duplicate elements, 
   - it is not synchronized by default
   - will not guarantee any order over time
   - iteration order/ reading order is not predictable.
     the order in which u entered may differ while reading.

2. treeset
   - internally uses red-black tree to store the values, 
   - it will maintain ascending order
   - it is slowest of all other 2 set implementations.
   - rest of the properties remain same

3. linkedhash set
   - internally uses hash table with linked list to store values.
   - same as hashset but order in which user entered will be persisted.
   - it is neither fast nor slow comparatively.
   - rest of the properties remain same.


list
----
 - it is ordered (maintains the insertion order) & may contain duplicate values
 - inherits from collection, and add functions for indexof, search functionalities.

List implementations
1. arraylist  (better performance) - same as vector .. 
2. linked list (better performace in some circumstances)


2. What is an Interface? Explain with realtime use case? (java)
Interface: as name suggests, it is an interface between your class and out side world.
                  interfaces can contain only constants, method declarations, and nested types. It can't contain method definitions.
                  Just like an abstract class, you can't create object for an interface.
                  You can imagine interface just like a header file in c program. It tells what all the functionalities supported by your interface.
                   
Use cases of Interfaces:

1. It can be used as APIs for third party libraries or server side libraries when using with client application. This is the main use case.
    Eg: If you are selling some libraries to some clients, then you will not expose the code. Rather you give in terms of .lib format.
          But since lib is unreadable format, you have to create an interface file telling what all the functions available in that library.
    Eg: Similarly if you want to access some server side functionalities in your client application, then also we use interfaces with some libraries.

2. You can use interfaces to implement multiple inheritance. 

3. What are the methods in Async Task?
Async Task: is a way to achieve multi threading in android. It has some advantages over normal java threads.
                       1. You don't need to use any Thread keyword, every thing will be taken care by AsyncTask class internally. 
                            It creates threads internally.
                        2. Since android follows single threaded UI model, where other threads can't touch UI components directly.
                             But from async task you can directly touch UI components from all the functions except from doInBackGround().

AsyncTask class will have 4 functions.
a. onPreExecute() - this is the first function to be called before calling doInBackGround(). This runs in UI thread. You can touch ui from this.
b. doInBackGround() - this runs in background thread created by AsyncTask class. Don't touch ui from this method.
                                         Write background heavy logic in this function, as it runs in background thread.
c. onProgressUpdate() - this function is used to update UI while performing background functionality. to execute this call publishProgress()
                                             this also runs in UI thread.
d. onPostExecute() - once doInBackGround() is finished this function will be called. If you want to update any UI after doInBackGround() use this                                 
                                     function. This also runs in main ui thread.

Async task use case: If you want to upload some images to facebook server and want to update UI (progress bar) while uploading images using progress bar, then you can use AsyncTask.

4. What is a Handler & what is the function of the Handler in Android?
Handler : is used to communicate between two threads.

Use of Handler: If you want to send or pass some message from one thread to other thread, then we can use Handlers.
                             1. A thread can have n number of handlers allowing other threads to communicate with it.
                             2. If we have Thread-A and Thread-B, and if Thread-B wants to send a message to Thread-A, then We have to create a handler
                                  for Thread-A and send message to that handler. Via handler Thread-B can send messages to Thread-A.


5. What is Anchor View in a Relative layout?
Anchor view tells about the relative position of view with respect to a given anchor view.
For eg: android:layout_above property will make sure that the current view's base line will be above the anchor view id given in this property.

More about anchor:
----------------------------
android:layout_above Positions the bottom edge of this view above the given anchor view ID. 
android:layout_alignBaseline Positions the baseline of this view on the baseline of the given anchor view ID. 
android:layout_alignBottom Makes the bottom edge of this view match the bottom edge of the given anchor view ID. 
android:layout_alignEnd Makes the end edge of this view match the end edge of the given anchor view ID. 
android:layout_alignLeft Makes the left edge of this view match the left edge of the given anchor view ID. 

6. How do you make your Application available to others for example you are using browser app if someone wants to use your app how you will make it available to others.
7. How to pass the objects to all activities?
If you want to pass objects between activities, there are multiple options for this.
1. You can implement Serializable for that class, and then pass serializable object in putExtra of intent.
2. Since serializables are heavy compared to parcels, second and better option can be passing parcels in extras.

1st way:
-----------
class ABC implements Serializable{
 ....
}

ABC a = new ABC();
Intent in = new Intent();
in.putExtra("class",a); //this should take serializable objects

2nd way:
------------
Though parcels are fast compared to serializables, but building a parcel is very tough and complicated.
It may affect the readability of the program. Parcels are heavily used only in IPCs (Inter Process Communications) and Binder Services by android
Otherwise to make it simple for reading, better to go with serializables.


8. If an activity is in foreground what all the lifecycle methods to be called?
If an activity is in foreground, then android will call onCreate(), onStart(), and onResume() sequentially before making it as foreground.

9. In life cycle in general it will be on Pause() ->on Stop but tell me example for on Pause()->on Resume()
eg 1. When your activity is in foreground or running state, turn off the LCD (will call onPause on your activity), and again turn on LCD (will call onResume)
eg 2. When your activity is in foreground or running state, display an activity in theme dialog  (will call onPause of your old activity), once dialog themed activity gets destroyed android will call onResume of your old activity.
eg 3. When your activity is in foreground or running state, display an activity which is transparent (will call onPause of your old activity), once transparent activity gets destroyed android will call onResume of your old activity.


10. Random Nos Program code? i.e How will you generate random numbers? (java)
Below code will generate a random number between 0 to 100 and stores it in variable "i".
int i = (int) (Math.random()*100); 

company: mindtree
1. Have u worked on AIDL?
Only if one is working on binder services, then only there is a fair chance of working on AIDL. IPC (Inter Process Communication) in android happens through kernel level Binder driver.
AIDL (Android Interface Definition Language) is a mechanism which internally uses Binders to access or to bind services of other applications.
Binder is an efficient way to do IPC when compared to serialization, thats why AIDL adopts Binder.

When a client application binds a remote service (which is in other application), that service will return an object using which client can call remote methods.
Since both client and service are in different applications, client would not know the type of object which is going to be returned. This is where AIDL
will be useful. 

Steps to implement AIDL in service side (server side):
1. create aidl file, which contains function declarations which you want to expose to the client.
2. implement interface stub method in your service file.
3. create an object for stub and return it as binder object to client

steps to implement AIDL in client side:
1. implement ServiceConnection object, and get the binder object in 
onServiceConnected() method, using aidl file interface name which was exposed by service. 
2. Start calling remote methods by using that object.

2. Why we don’t  give  min sdk version as 1?
There are very negligible number of devices who runs version 1 of android. It is almost deprecated completely. Setting min sdk is to make sure that an application is reaching wide range of users. As of today it will be sufficient to reach major number of users if we set min sdk version as 2.2.

3. What are the basic uses of manifest file?
Every application will contain one manifest file which contains important information about the application which system must know before it can run the application.  1. It contains package name of your application. 2. it contains various components used in the application like how many activities, services, receivers and content providers available in your application. 3. It contains all permissions required to run the application properly. 4. It contains minimum level of api required to run this application. 5. It lists all the libraries required to run the application. etc.

4. What is the use of registering broadcast receiver in manifest file?
Registering a receiver in manifest file makes sure that our receiver will be triggered even if our application is not running currently. For example when a new incoming SMS comes it should be handled by Messaging application even if it is not running currently. In this case programmer has to register the receiver in messaging application's manifest file to respond to incoming sms.

5. Commands to write or create .apk file?
1. use javac to compile your java files
2. use dx tool to convert all .class files to single dex file
3. use aapt tool or apkbuilder tool to generate .apk file, which contains    manifest, .dex, and res.
   .apk is equivalent to .jar in java. 
   aapt tool and dx tools are in android-sdk/platform-tools.
4. sign the apk file by using jarsigner tool of jdk/bin
5. zipalign your signed apk by using zipalign tool of android-sdk/tools 

6. Can we create all ui coding  in activity without using xml?
Ui can be completely created through programming. But that is not recommended. There should be clear separation between design and the logic. That is the reason why android has given res folder to create all the designs like layouts, menus, icons, and styles. If project demands some dynamic changes to the UI, which can't be done in the xml files, then programmer can use any View or ViewGroup classes to design the UI through programming.


lLayout = new LinearLayout(this);
        lLayout.setOrientation(LinearLayout.VERTICAL);
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
        tView = new TextView(this);
        tView.setText("Hello, This is a view created programmatically!");
        tView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
        lLayout.addView(tView);
        setContentView(lLayout);

7. Life cycle of activity and Fragments?what is Fragment?
8. When I run any application where fragments are there which method will be called first?
Just like Activities has life cycle methods, similarly fragments also have their life cycle methods. When we load a fragment first method to be called is onAttach(), followed by onCreate(), which is followed by onCreateView(). Generally programmers will not implement onAttach() method. onCreate() is where we will initialize all the variables which are used in the fragment. onCreateView() is where we will inflate or load the xml file of our fragment and return it to the parent (activity).

9. Can we have fragments without activity?
It is not possible to have fragment with out an activity. Fragments are part of activity. Fragments always lies with in the activity. An activity can exist without a fragment where as fragment with out an activity is not possible. You can assume fragment like a thread and activity is like a process, where threads are always part of a process. Every fragment will contribute its own UI to the parent activity.

10. Tell me different IDEs other than eclipse?
Android can be developed by using below IDEs:

Eclipse
NetBeans
IntelliJ
Re-Sharper
Android Studio which is based on IntelliJ

As of now plugins are up to date for Eclipse.
But soon Android Studio is going to be the official IDE for android development.

11. Asked about memory leakage?How to handle it
To fix memory leaks, first we should know if our application is leaking any memory. For that use Logcat and check for GC messages and observe if free memory is going down. To understand this you can rotate your phone for couple of times and observe gc messages in logcat if free memory is going down. If you see that free memory is going down, that is an indication of memory leak. To fix memory leaks you can use MAT(memory analyzer tool) of eclipse. Before doing that you should create a hprof file which contains the memory status of your application. Open up hprof file in the memory analyzer tool to check for dominator tree and find out what is causing for your memory leak. Note: 70-80% of the memory will leaked by bitmap images, so be careful while using them, and try to avoid un necessery static pointers to them to avoid memory leaks. For more on this, checki https://www.youtube.com/watch?v=_CruQY55HOk



Saturday, January 3, 2015

250 Android Interview Questions - part 2

I am giving set of 250 Android interview questions here, which I have answered in android interview questions and answers - skillgun

Since Java is also a part of android interview, I have included around 60 java interview questions here.

I am giving only questions here as space is a constraint for explaining every answer.
                                            
Android Interview Questions:

101.                        I want to store huge structured data in my app that is private to my application, now should I use preferences [or] files [or] sqlite [or] content provider?
102.                        My application has only a service, and my service performs heavy lift functionality to connect to internet and fetch data, now should I create a thread or not? If so why?
103.                        I want to write a game where snake is moving in all the directions of screen randomly, now  should I use existing android views or should use canvas? Which is better?
104.                        Can I have more than one thread in my service? How to achieve this?
105.                        When lcd goes off, what is the life cycle function gets called in activity?
106.                        When a new activity comes on top of your activity, what is the life cycle function that gets executed.
107.                        When a dialog is displayed on top of your activity, is your activity in foreground state or visible state?
108.                        When your activity is in stopped state, is it still in memory or not?
109.                        When your activity is destroyed, will it be in memory or moved out of it?
110.                        I started messaging app –> composer activity -> gallery  -> camera -> press home button. Now which state camera activity is in?
111.                        Continuation to above question, now If I launch gmail application will it create a new task or is it part of old messaging task?
112.                        Can I have more than one application in a given task?
113.                        Can I have more than one process in a given task?
114.                        Do all the activities and services of my application run in a single process?
115.                        Do all components of my application run in same thread?
116.                        How to pass data from activity to service?
117.                        How to access progress bar from a service?
118.                        What is the difference between intent and intent-filter?
119.                        What is the difference between content-provider and content-resolver?
120.                        What is the difference between cursor & contentvalues ?
121.                        What is Bundle? What does it contain in oncreate() of your activity?
122.                        When an activity is being started with an intent action “MY_ACTION”, how can I see that action in triggered component(activity)?
123.                        How to get contact number from contacts content provider?
124.                        How to take an image from gallery and if no images available in gallery I should be able to take picture from camera and return that picture to my activity?
125.                        What is the difference between linear layout and relative layout?
126.                        How many kinds of linear layouts are there?
127.                        What is “dp” [or] “dip” means ?
128.                        What is importance of gravity attribute in the views?
129.                        What is adapter? What is adapter design pattern?
130.                        What is adapterview? How many adapter views are available in android?
131.                        Can you tell me some list adapters?
132.                        Can I give cursor to an array adapter?
133.                        What is custom adapter, when should I use it. what are the mandatory functions I need to implement in custom adapter?
134.                        What is the class that I need to extend to create my own adapter?
135.                        What is the android compilation and execution process/ cycle?
136.                        What is adb? What is the command to install one application using adb command prompt?
137.                        What is the debugging procedures available in android?
138.                        How will you analyze a crash, how will fix using logcat?
139.                        What is a break point and how to watch variables while debugging?
140.                        What is ddms? What are the various components in ddms?
141.                        What is the difference between started service and binded service?
142.                        How to achieve bind service using IPC?
143.                        How will I know if a client is connected to a service or not?
144.                        I want to access a functionality from one application to other application, then should I use content provider or startservice or bind service?
145.                        I want to access data of another application in my application, now do I need to implement content providers in my application or other application has to implement it?
146.                        What is the difference between local variables, instance variables, and class variables?
147.                        What is anonymous class? Where to use it?
148.                        What is singleton class, where to use it? show with one example how to use it?
149.                        If I want to listen to my phone locations, what all the things I need to use? Is it better to use network providers or gps providers?
150.                        My phone don’t have network signal and satellite signal, now is there any way to fetch my last location where signal was available?
151.                        I have some data available in docs.google server, and I want to display it in tabular fashion, tell me the sequence of steps to achieve this?
152.                        If I want to start some heavy weight functionalities that takes lot of battery power like starting animation or starting camera, should I do it in oncreate() or onstart() or onresume() of my activity? And where should I disable it?
153.                        Why you should not do heavy functionality in onresume and onpause()  of your activity?
154.                        What things I can do in onrestart() of my activity?
155.                        What is the life cycle of a service?
156.                        What is the life cycle of a broadcast receiver?
157.                        What is the life cycle of a content provider?
158.                        What is the life cycle of a thread?
159.                        What is the life cycle of your application process?
160.                        How to kill one activity?
161.                        What is log.d ? where to use log functions?
162.                        Draw the life cycle of an activity in case of configuration change?
163.                        What is the difference between viewgroup and layout?
164.                        Draw the key event flow in android?
165.                        When you fire an intent to start with ACTION_CALL , what is the permission required?
166.                        What are the permissions required to obtain phone locations?
167.                        How many levels of security available in android?
168.                        How to achive security to your service programmatically in such a way that your service should not get triggered from outside applications?
169.                        What are the sequence of tests done to map intent with an intent-filter?
170.                        Describe various folders in android project in eclipse?
171.                        What is raw folder in eclipse project?
172.                        Under what thread broad cast receiver will run?
173.                        If I want to notify something to the user from broadcast receiver, should I use dialogs or notifications? Why?
174.                        Can you create a receiver without registering it in manifest file?
175.                        If I want to broadcast BATTERY_LOW action, should I use sendbroadcast() or sendstickybroadcast? Why?
176.                        If I want to set an alarm to trigger after two days, how should I implement it? assume that I may switch off the phone in between.
177.                        I want to trigger my broadcast receiver as long as my activity is in memory, else it should not get triggered, how should I achieve this?
178.                        What is sleep mode? What will happened to CPU once screen light goes off?
179.                        How many kinds of wake locks are available, which one to use when?
180.                        If I am using full wake lock and user presses screen lights off, what will happen?
181.                        When phone is in sleep mode, what are the two components that will keep running even though phone is in sleep mode?
182.                        Every day night at 12 o clock I need to post some images to facebook, in that case I will set repeating alarm for every day night 12 am. But to upload images I want to start service, how should I do this ?
183.                        When you start an activity from a notification, will it start as new task or old task?
184.                        Why android follows single threaded ui mode? How other threads can manipulate ui views?
185.                        What is the purpose of SQLiteOpenHelper?
186.                        What is the procedure to upgrade database after first release?
187.                        Show with one example where memory leak possibility in Android?
188.                        If I want to write one application for both phones and tablets, what should I use in my UI?
189.                        I have a thousands of items in my array, and I want to display it in listview, what is the most optimized way to achieve this?
190.                        What is r.java file? What does it contain?
191.                        Write one application which will get triggered immediately after booting.
192.                        What does .apk  file contains?
193.                        How will pass information from one activity to other activity, let’s say pass userid, city, and password to next activity and display it.
194.                        Write code for an xml file having a relative layout with employee registration form.
195.                        Get a table information from the database and show it in table UI format.
196.                        I have thousands of columns and thousands of rows to display it in UI tabular format, how should I show it this dynamically growing UI. Should I load all in single shot or any optimization can be done?
197.                        When to use String, StringBuffer, & StringBuilder?
198.                        What is String constant pool? What is the difference between below two statements? 
                                                               i.      Which is preferred way to use?
                                                             ii.      String str1 = “hi”;
                                                            iii.      String str2 = new String(“hi”);
199.                        If I want to share a String between two threads, and none of threads are modifying my String which class I have to use?
200.                        If I want to use my String within only one thread which is modifying my String, then which class I have to use? Similarly if I want to my string to be changed by more than one thread then which class I have to use?
201.                        How does String class look like? What is final class meant for? How will you implement your own String class?
202.                        What is immutable object? How is it different from immutable class?
203.                        Depict one example for immutable class in java framework?
204.                        How will you write a class in such a way that it should generate immutable objects?
205.                        Does String class uses character array internally in its implementation?
206.                        What is the difference between char & Character classes? Which one is value type and which one is ref type?
207.                        What is the meaning of pass by reference? If I have an integer array and if I pass that array name to a function, is it pass by value or pass by reference?
208.                        I want to use array in my program which has to grow dynamically, in that case should I use Array [or] ArrayList [or] Vector? What is the difference between arraylist and vector? Which one of them is not part of collections framework of JAVA?
209.                        I want to use dynamically growing array shared between two threads, should I use arraylist or vector?
210.                        I want to store values of my employees in a data structure using java collections framework in such a way that I should be able to read, write, modify & delete them very fastly. Which datastructure should I use ? arraylist [or] linkedlist [or] hashsets [or] hashmap ?
211.                        Write a program in such a way that Thread1 will print from 1-1000 & Thread2 will print from 1000-1. Thread1 should sleep for 1 second at every 100th location. Thread2 should interrupt thread1 once thread2 reaches 500.
212.                        How will you stop a thread, which is currently running?
213.                        If Thread1 interrputs Thread2, how Thread2 should handle it? (Generally how threads should handle interruptions?) how will thread2 know that other threads are interrupting it?
214.                        What is interrupted exception? Which functions will throw this exception? How to handle it?
215.                        Assume that two threads t1, & t2 are running simultaneously in single core CPU. How does t2 will request OS that it wants to wait till t1 is finished?
216.                        I want to implement threads in my program, should I extend Thread class or implement Runnable interface? Which one is better, justify your answer in terms of design.
217.                        What will happen if you return from run() function of your thread?
218.                        What is the difference between checked  & unchecked exceptions? Which one programmer should handle?
219.                        arrayIndexOutOfBounds, NullPointerException, FileNotFoundException, ArithmeticException, InterruptedException, IOError, IOException. In this list which exceptions programmer has to handler compulsorily? Categorize above exception list into ERROR/ RUNTIME EXCEPTION/ REST categories.
220.                        Assume that I am writing a function which likely to throw checked exception, in that case if I don’t handle it will compiler throw any error?
221.                        How one should handle checked exceptions? Mention 2 ways to handle it.
222.                        I am writing a function where it is likely that checked exception may come, I want to handle it in my function and I want to pass that exception to my parent caller also. How do I achieve it?
223.                        What is difference between throw, throws?
224.                        Can I write a try block without catch statement?
225.                        What is difference between final, finally, & finalize.
226.                        Will java ensure that finalize will be executed all the time immediately after object is destroyed? How to mandate it?
227.                        What is 9 patch image, how is it different from .png images? Why we have to use this in android? How will it help in the scalability of an image for various screens?
228.                        What is the difference between synchronized method and synchronized block? If I have a huge function where only two lines of code is modifying a shared object then should I use synchronized block or method?
229.                        Implement insertion sort, binary search, and heap sort.
230.                        How many ways a server can communicate (Send data) to a mobile application? Which is fastest way json or xml?
231.                        What is JSONArray & JSONObject. Show this with one example by requesting one URL using HTTP, which gives JSON object.
232.                        Name some sites which extensively use JSON in communicating their data with clients.
233.                        What is the permission you need to take for fetching GPS locations, & reading contacts. Where will you have to write permissions in manifest file?
234.                        How will you display data base information in a table kind of architecture in android? Which view will you use?
235.                        How many kinds of adapter-views, and adapters available in android?
236.                        What is notifydatasetchanged() function meant for?
237.                        Take data base cursor of employee (eno, ename, salary) into a cursor, fill into a list view where each item should have a check box also, how will you implement it in android?
238.                        What is the difference between constructor and static block. Can I initialize static variables in constructor?
239.                        I want to use a private variable of Class-A in classB directly without using any function. How to achieve this?
240.                        I want to create a class in such a way that nobody should be able to create object for that class except me. How to do it?
241.                        Can I access instance variables in a static function? Can I access static function /variable from an instance method?
242.                        Why is multiple inheritance of classes not allowed in java? If I want to get functions of Class-A & Class-B into class-C. how do I design this program?
243.                        Does java allow multiple inheritance of interfaces? Can one interface extend other interface ? when should I extend interface from other interface?
244.                        What is the difference between over loading and over riding?
245.                        Can I over ride base class constructor in derived class?
246.                        Can I over load a constructor?
247.                        How does default constructor look like? What super() call does in a constructor?
248.                        Why does base class constructor gets executed before executing derived class constructor? Justify this with appropriate example?
249.                        How will you achieve dynamic polymorphism using over riding? Justify usage by taking some example (note: use client-server example)
250.                        Why overloading is static polymorphism, justify your answer?
251.                        What is the difference between static/compile time linking & dynamic/run time linking? Are static functions dynamically linked?
252.                        Show one Is-A relation with one example.
253.                        Show one Has-A relation with one example.


Happy job hunting
      Best wishes
          Team,
Palle Technologies
enquiry@techpalle.com
Phone : 080 - 4164-5630The training expert in Bangalore.