Friday 3 June 2016

RecyclerView vs. ListView 



With the advent of Android Lollipop, the RecyclerView made its way officially. The RecyclerView is much more powerful, flexible and a major enhancement over ListView. I will try to give you a detailed insight into it.
1) ViewHolder Pattern
In a ListView, it was recommended to use the ViewHolder pattern but it was never a compulsion. In case of RecyclerView, this is mandatory using the RecyclerView.ViewHolder class. This is one of the major differences between the ListView and the RecyclerView.
It makes things a bit more complex in RecyclerView but a lot of problems that we faced in the ListView are solved efficiently.
2) LayoutManager
This is another massive enhancement brought to the RecyclerView. In a ListView, the only type of view available is the vertical ListView. There is no official way to even implement a horizontal ListView.
Now using a RecyclerView, we can have a
i) LinearLayoutManager - which supports both vertical and horizontal lists,
ii) StaggeredLayoutManager - which supports Pinterest like staggered lists,
iii) GridLayoutManager - which supports displaying grids as seen in Gallery apps.
And the best thing is that we can do all these dynamically as we want.
3) Item Animator
ListViews are lacking in support of good animations, but the RecyclerView brings a whole new dimension to it. Using the RecyclerView.ItemAnimator class, animating the views becomes so much easy and intuitive.
4) Item Decoration
In case of ListViews, dynamically decorating items like adding borders or dividers was never easy. But in case of RecyclerView, the RecyclerView.ItemDecorator class gives huge control to the developers but makes things a bit more time consuming and complex.
5) OnItemTouchListener
Intercepting item clicks on a ListView was simple, thanks to its AdapterView.OnItemClickListenerinterface. But the RecyclerView gives much more power and control to its developers by theRecyclerView.OnItemTouchListener but it complicates things a bit for the developer.
In simple words, the RecyclerView is much more customizable than the ListView and gives a lot of control and power to its developers.

Difference between abstract class and interface ?

1) Abstract class can have abstract and non-abstract methods.
    Interface can have only abstract methods.

2) Abstract class doesn't support multiple inheritance.
    Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non-static variables.
    Interface has only static and final variables.

4) Abstract class can have static methods, main method and constructor.
    Interface can't have static methods, main method or constructor.

5) Abstract class can provide the implementation of interface.
    Interface can't provide the implementation of abstract class.

6) The abstract keyword is used to declare abstract class.
    The interface keyword is used to declare interface.

How to Stop Asynctask Thread in Android ?



if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
{
    loginTask.cancel(true);
}
Where loginTask is object of your AsyncTask

Difference between an IntentService and a Service ?


When to use ?

The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.

The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).
How to trigger ?

The Service is triggered by calling method startService().
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.
Triggered From

The Service and IntentService may be triggered from any thread, activity or other application component.

Runs On

The Service runs in background but it runs on the Main Thread of the application.
The IntentService runs on a separate worker thread.
Limitations / Drawbacks

The Service may block the Main Thread of the application.
The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.
When to stop?

If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method).
The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf()
What is the difference between a regular bitmap and a nine-patch images ?
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

What is the base class for any android application ?


Application
REST vs SOAP

SOAP stands for Simple Object Access Protocol. REST stands for REpresentational State Transfer.

SOAP is a XML based messaging protocol and REST is not a protocol but an architectural style.

SOAP has a standard specification but there is none for REST.

Whole of the web works based on REST style architecture. Consider a shared resource repository and consumers access the resources.

Even SOAP based web services can be implemented in RESTful style. REST is a concept that does not tie with any protocols.

SOAP is distributed computing style and REST is web style (web is also a distributed computing model).

REST messages should be self-contained and should help consumer in controlling the interaction between provider and consumer(example, links in message to decide the next course of action). But SOAP doesn’t has any such requirements.

REST does not enforces message format as XML or JSON or etc. But SOAP is XML based message protocol.

REST follows stateless model. SOAP has specifications for stateful implementation as well.

SOAP is strongly typed, has strict specification for every part of implementation. But REST gives the concept and less restrictive about the implementation.

Therefore REST based implementation is simple compared to SOAP and consumer understanding.

SOAP uses interfaces and named operations to expose business logic. REST uses (generally) URI and methods like (GET, PUT, POST, DELETE) to expose resources.

SOAP has a set of standard specifications. WS-Security is the specification for security in the implementation. It is a detailed standard providing rules for security in application implementation. Like this we have separate specifications for messaging, transactions, etc. Unlike SOAP, REST does not has dedicated concepts for each of these. REST predominantly relies on HTTPS.

Above all both SOAP and REST depends on design and implementation of the application.
Pass ArrayList From OneActivity to AnotherActivity ?


public class DataWrapper implements Serializable 
     {
       private ArrayList<String> arrayList;
       public DataWrapper(ArrayList<String> data) 
        {
         this.arrayList = data;
        }
       public ArrayList<String> getArrayList() 
       {
        return this.arrayList;
       }
      }
 

    Intent intent = new Intent(SubCat1Activity.this,Full1Activity.class);
    intent.putExtra("data",new DataWrapper(MainData));
    startActivity(intent);

    DataWrapper dw = (DataWrapper) getIntent().getSerializableExtra("data");
    ArrayList<String> list = dw.getArrayList();

Friday 13 May 2016

Which Method is called when the user leaves the Activity ?

onPause
What does .apk extension stand for ?

Application Package kit
To log messages from your app to LogCat you should use ?

android.util.Log
The root element of AndroidManifest.xml is ?

manifest
Stores Private Primitive data in key-value pairs ?

Shared Preferences
Difference between Versioncode and Versionname ?

android:versionCode
An internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName attribute. The value must be set as an integer, such as "100". You can define it however you want, as long as each successive version has a higher number. [...]


android:versionName

The version number shown to users. This attribute can be set as a raw string or as a reference to a string resource. The string has no other purpose than to be displayed to users. The versionCode attribute holds the significant version number used internally.
Fragment Life Cycle ?

onAttach()
onCreate()
onCreateView()
onActivityCreated()
onStart()
onResume()
onPaused()
onStop()
onDestroyView()
onDestroy()
onDetach()
What is the difference between Activity and Fragment in Android ?

fragment is a part of an activity, which contributes its own UI to that activity. Fragment can be thought like a sub activity. Where as the complete screen with which user interacts is called as activity. An activity can contain multiple fragments.Fragments are mostly a sub part of an activity.

An activity may contain 0 or multiple number of fragments based on the screen size. A fragment can be reused in multiple activities, so it acts like a reusable component in activities.

A fragment can't exist independently. It should be always part of an activity. Where as activity can exist with out any fragment in it.
What is the difference between local variables, instance variables, and class variables ?

local variables - declared in the function 
class variables - declared in class, static 
instance variables - declared in class which are non static
What is the difference between intent and intent-filter in Android ?

intent is a message passing mechanism between components of android, except for content provider.
intent-filter tells about the capabilities of that component.
What is the difference between getPreferences and getSharedPreferences in Android ?

getPreferences(0) - will open or create a preference file with out giving a name specifically. By default preference file name will be the current Activity name. if some one knows this, any once can access getPreference() file using that activity name.  getSharedPreferences("name",0) - will open or create a preference file with the given name. If you want to create a preference file with a specific name then use this function. If you want multiple preference files for you activity, then also you can use this function.  Note: preferences file will be with .xml extension stored in data/data/preferences folder.

Wednesday 11 May 2016

SQLite Query Returns a set of Rows Along With a Pointer Called  ?

cursor
A Small Message that is Displayed to the User for a few Seconds ?

Toast
is an Mechanism Created to Handle Long Operations that need to report UI Thread ?

AsyncTask


is the Callback Specifies the work to be done on menu key press ?

onCreateOptionsMenu()
Represents a Single User Interface Screen ?

Activity
is used to uniquely identify the framework API revision offered by a version of the Android platform ?

Version Number

What is cursor.moveToNext() ?

It will move the cursor to point to next row if it is available, else it returns false.
What is the Purpose of the ContentProvider class ?

If you want to share the data of one application with the application then use content provider.  
Note: We can start an Activity, a service, and a broadcast receiver by using intents. 
But you can't start or communicate with a content provider by using intents. 
If you want to communicate with content provider then you have to use content resolver.  
1.content provider, and resolver will handle IPC(Inter process communication) mechanism when sharing data between 
2 applications. 2.content provider has the capability to handle multiple threads, when queries are coming from multiple resolvers.
Is it Possible to Have Multiple Actions in an intent-filter ?

intent-filters can have 0 - n number of actions, but if that component has only one intent-filter with 0 actions, then that component can be triggered using only explicit intents. a given intent-filter can have more than one action because, a given component can do more than one action. EG: notepad can perform two actions ACTION_VIEW & ACTION_EDIT on an existing note pad file.
What is the Permission Required to Make a Call in Android, by using  ACTION_CALL ?

android.permission.CALL_PHONE

Monday 9 May 2016

How Many Types of Menus are There in Android ?

Options Menu - triggered when user presses menu hard key. This is deprecated starting from android 3.0. In place of options menu migrate to action bars.
Sub Menu - Menu with in a menu (only one level of sub menu is allowed).
Context Menu - Triggered when user press and hold on some view which was registered to show context menu.
What is the Difference Between Menus and Dialog, in Android ?

Menus are designed using xml, because menus will not change so frequently. You can build menus using code also when ever required. But it is not recommended to completely build menus using code.
Dialog are built using code because dialog content will frequently change.
What is the life cycle of a Started Service ? 

onCreate 
onStartCommand() 
onDestroy()
What is the Difference Between Service and Intentservice in Android  ? 

i  Intentservice by default will create one separate thread to handle the service functionality.
   All the startservice requests for intentservice will be routed to that thread. 
ii. Where as service by default runs in main thread. All the startservice requests will be routed to main thread by default. 
iii. While implementing a service, programmer has to implement onCreate(), onStartCommand(), and onDestroy() methods. 
iv. Where as while implementing IntentService programmer has to implement only onHandleIntent(). 
v. After starting IntentService, it will be automatically closed if there are no pending startService requests. 
vi. Where as for normal service programmer has to stop the service explicitly either by using stopSelf() or stopService() methods. 
vii. Don't try to touch UI from IntentService's onHandleIntent() method directly, as that function runs in a separate thread. (Not in main thread).
What is MODE_PRIVATE When Creating SharedPreference File ?

only the process or application which has created that preference file can access it. other applications can't access it.
What is the Difference Between permission and uses-permission in Android ?  

i. permission tag is used to enforce a user defined permission on a component of your application. 
ii. uses-permission tag is used to take a permission from the user for your application. 
iii. permission tag is used when you want other applications to seek permission from the user to use some of your applications components.

Sunday 8 May 2016

What is the root tag of a Manifest File in Android? (which will be immediately after xml tag).

manifest


What is the Maximum Memory limit Given for Each Process or Application in Android ?

16 MB


What is APK in Android, and What does .apk  file Contains ?

APK - Application Package file. It is a file format used to distribute and install android applications. .apk will contain single .dex file, zipped resources, other non java library files (c/c++). .dex file will internally contains converted .class files. other wise .apk will not contains .class files.


What is R.java in Android? What does it Contain ?

It is automatic generated file, which have pointers to all resources used in the application.
What type of Kernel is used in Android ?

Linux modified kernel (Monolithic) is used in Android
Which Programming Language Should be used to Create Applications in Android ?

At the initial stages android application development was limited to use only Java. But later with NDK (Native Development Kit) programmers can use C & C++ to write applications. Recently there has been lot of support for lot of scripting languages as well.
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



Which Component is not Started by an Intent ?

Content Providers
What are the Permissions Required to Access Phone's Location using NETWORK_PROVIDER ?

ACCESS_FINELOCATION
ACCESS_COARSE_LOCATION

NETWORK_PROVIDER will fetch locations either by using WiFi point or cell tower information. for cell tower we have to use COARSE_LOCATION permission and for WiFi we have to use FINELOCATION permission.
How to create a SensorManager object to access and view list of Sensors available in the phone ?

SensorManager s = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
How To Send SMS Message In Android  ?

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
 

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("sms_body", "Hii.....  i m Naveen Tamrakar an Android Developer from 
        Indore"); 
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);


<uses-permission android:name="android.permission.SEND_SMS" />
How to Send Mail in Android  ?

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"er.naveen.tamrakar@gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "message");
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent, "Choose an Email client :"));

How to use Hindi Fonts in Android ?


TextView t = new TextView(this);
Typeface Hindi = Typeface.createFromAsset(getAssets(), "fonts/mangle.ttf");
t.setTypeface(Hindi);
t.setText("Naveen Tamrakar");
What are Adapters and When and How are they used ?

It is tough to develop an Android app without using an adapter somewhere because they are so important.
Where do adapters fit in? They bridge the Model and View (e.g. AdapterViews such as ListViews, GridViews, Spinners and ViewPagers) with underlying data. They provide access to data items and are responsible for Creating a view for each item in the data set.
Android doesn’t adopt the MVC pattern per se. You define the Model that works for you. Android helps you layout and render views, and you customize Android’s Activities and Fragments that typically act as Controllers.

Novice developers might try to get away with using simple helper adapters like ArrayAdapter, SimpleAdapter and SimpleCursorAdapter when possible, but these are usually too limiting for some of the more complex views typically required by todays apps. Master developers will write adapters that extend BaseAdapter directly, because it is more powerful and flexible than the subclass helpers mentioned above.
What is an URI ?

Android uses URI strings both for requesting data (e.g., a list of contacts) and for requesting actions (e.g., opening a Web page in a browser). Both are valid URI strings, but have different values. All requests for data must start with the string “content://”. Action strings are valid URIs that can be handled appropriately by applications on the device; for example, a URI starting with “http://” will be handled by the browser.
What is AsyncTask ?

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
What are the different Storage Methods in Android ?

Android provides many options for storage of persistent data. It provides the solution according to your need. The storages which have been provided in Android are as follows:

 Shared Preferences: Store private primitive data in key value pairs
 Internal Storage: Store private data on the device memory.
 External Storage: Store public data on the shared external storage.
 SQLite Databases: Store structured data in a private database.
 Network Connection: Store data on the web with your own network server.
What is a Sticky Intent ?

Intent is basically an abstract description of an operation that has to be performed for communication. Sticky Intent is also a type of intent which allows the communication between a function and a service.

sendStickyBroadcast() performs a sendBroadcast (Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver (BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent). 
What is a Broadcast Receivers ?

A broadcast receiver is a component that does nothing but receive and react to broadcast announcements.
For example, announcements that the timezone has changed, that the battery is low or that the user changed a language preference.
All receivers extend the BroadcastReceiver base class.

Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive, or they may use the NotificationManager to alert the user like(flashing the backlight, vibrating the device, playing a sound)
What is an Intent Filter ?

Activities and intent receivers include one or more filters in their manifest to describe what kinds of intents or messages they can handle or want to receive. An intent filter lists a set of requirements, such as data type, action requested, and URI format, that the Intent or message must fulfill. For Activities, Android searches for the Activity with the most closely matching valid match between the Intent and the activity filter. For messages, Android will forward a message to all receivers with matching intent filters.
What is the Difference Between Service and Thread ?

Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you wolud not create a blank activity for it, for this you will use a Service. It is also known as Background Service because it performs tasks in background. 

A Thread is a concurrent unit of execution. You need to know that you cannot update UI from a Thread. You need to use a Handler for this.
What is a Toast Notification ? 

A toast notification is a message that pops up on the surface of the window. It only fills the amount of space required for the message and the users current activity remains visible and interactive. The notification automatically fades in and out, and does not accept interaction events.
What is Android Runtime ?

Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included dx tool.
What is Dalvik Virtual Machine ?

The name of Android virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included dx tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.