Tuesday 12 November 2013

Data Storage Options in Android

Hello Guys!!! Hopes things are well at your end.
Today I am going to discuss Data storage Option in android. Particularly about sqlite in android. How to use its efficiently and effectively in your application without any error.
There are five ways to store data in Android:
  1. shared preferences
  2. internal files
  3. external files
  4. SQLite and 
  5. network storage in the cloud
Let’s review each. 
1. Shared preferences are internal to the application and device. This data is not available to other applications. The user cannot directly manipulate this data by mounting onto a USB port. The data is
removed automatically when the application is removed. Shared preferences are structured key/value
pair data and follow a few other semantics imposed by Android for using the stored data as preferences. Shared preferences are maintained as XML files.
2. Internal files are unstructured private files that an application can create and store data in. Like shared preferences,  internal files follow the life cycle of the application. When the application is uninstalled, the internal files created by the application are also removed.
3. External files are stored on the SD card. These become public files that other apps including the user could see outside the context of your application. External files are typically used for data that is primarily created by the user and is meaningful outside of the app that creates it—for example, audio files,  video files, word documents,  etc. External files are also suitable when the amount of data is large, say 10MB or more.
4. SQLite is a relational database. For structured data, like the data that you are planning to use JSON for, SQLite is preferred. However, it is lot of work to go between Java objects and a relational database. Even in the simplest case of using wonderfully crafted o/r mapping tools or libraries, it is still lot of work. However, SQLite is an excellent option for tuning and refactoring your application for subsequent releases. This refactoring will make your application respond much faster and use much less power. The database also is private to the application and not available to outside apps unless you wrap the database in a content-provider framework.
5. Network storage allows your application to choose to save persistent data in the cloud. Network
storage cannot be a complete option for lot of apps, however, as you likely will need the app to work when disconnected from the Internet. There may be supplemental opportunities to use parse.com or a similar BaaS (backend as a service) platform to do a hybrid approach, whereby some data is stored in the cloud and is synced when needed with the device.

 Now after reviewing each you can understand which one is better suited your need. I am going to put some more light on sqlite database use in Android Application. 

SQLite is at the heart of Android’s database support. This database was developed with embedded environments in mind – and is used not only by Android but also by Apple’s iOS and Blackberry’s system as well as lots of other systems with low memory footprint and comparatively little CPU horsepower.
 SQLite is so dominant in the embedded and also the mobile world. The main reasons are
  1. Low memory consumption
  2. Ease of use
  3. Free availability
  4. SQLite is serverless
  5. SQLite stores data in one database file
  6. SQLite offers only a few data types
  7. SQLite uses manifest typing instead of static types
  8. SQLite has no fixed column length
  9. SQLite uses cross-platform database files
SQLite datatypes

TypeMeaning
NULLThe null value
INTEGERAny number which is no floating point number
REALFloating-point numbers (8-Byte IEEE 754 – i.e. double precision)
TEXTAny String and also single characters (UTF-8, UTF-16BE or UTF-16LE)
BLOBA binary blob of data
SQLite is written in the C programming language while  Android applications are primarily developed using Java. To bridge this “language gap”, the Android SDK includes a set of classes that provide a Java layer on top of the SQLite database management system. Here I am providing  a basic overview of each of the major classes within this category. More details on each class, You  can  find in the online Android documentation.
Cursor
A class provided specifically to provide access to the results of a database query. For example, a SQL SELECT operation performed on a database will potentially return multiple matching rows from the database. A Cursor instance can be used to step through these results, which may then be accessed from within the application code using a variety of methods. Some key methods of this class are as follows:
  • close() – Releases all resources used by the cursor and closes it.
  • getCount() – Returns the number of rows contained within the result set.
  • moveToFirst() – Moves to the first row within the result set.
  • moveToLast() – Moves to the last row in the result set.
  • moveToNext() – Moves to the next row in the result set.
  • move() – Moves by a specified offset from the current position in the result set.
  • get<type>() – Returns the value of the specified <type> contained at the specified column index of the row at the current cursor position (variations consist of getString(), getInt(), getShort(), getFloat() and getDouble()).
SQLiteDatabase
This class provides the primary interface between the application code and underlying SQLite databases including the ability to create, delete and perform SQL based operations on databases. Some key methods of this class are as follows:
  • insert() – Inserts a new row into a database table.
  • delete() – Deletes rows from a database table.
  • query() – Performs a specified database query and returns matching results via a Cursor object.
  • execSQL() – Executes a single SQL statement that does not return result data.
  • rawQuery() – Executes an SQL query statement and returns matching results in the form of a Cursor object.
SQLiteOpenHelper
A helper class designed to make it easier to create and update databases. This class must be subclassed within the code of the application seeking database access and the following callback methods implemented within that subclass:
  • onCreate() – Called when the database is created for the first time. This method is passed as an argument the SQLiteDatabase object for the newly created database. This is the ideal location to initialize the database in terms of creating a table and inserting any initial data rows.
  • onUpgrade() – Called in the event that the application code contains a more recent database version number reference. This is typically used when an application is updated on the device and requires that the database schema also be updated to handle storage of additional data.
In addition to the above mandatory callback methods, the onOpen() method, called when the database is opened, may also be implemented within the subclass.
The constructor for the subclass must also be implemented to call the super class, passing through the application context, the name of the database and the database version. Notable methods of the SQLiteOpenHelper class include:
  • getWritableDatabase() – Opens or creates a database for reading and writing. Returns a reference to the database in the form of a SQLiteDatabase object.
  • getReadableDatabase() – Creates or opens a database for reading only. Returns a reference to the database in the form of a SQLiteDatabase object.
  • close() – Closes the database.









Tuesday 5 November 2013

Android loader versus AsyncTask

Hello Guys!!! Hope things are well at your side.
Today the point of discussion is Android loader versus AsyncTask.
The concept of Loaders was introduced in Android 3.0 (API Level 11). It is a mechanism of loading data asynchronously for an activity or fragment. Since loaders are specifically designed to solve the issue of Async loading, one does not have to spend too much time designing Async tasks to handle all different scenarios efficiently.

Before we proceed for  Android loader we have to put some light on AsyncTask it uses drawback.
AsyncTask
Before getting into the Loader concept, it’s important to have a good idea of what the AsyncTask is and what it’s used for within Android. AsyncTask was added to Android in API level 3 (Android 1.5 Cupcake) and was said to help developers manage their threads.
     Right now, AsyncTask is probably the most commonly used technique on Android for background execution. It's really easy to work with and that's what developers love about it. It gives the developer an easy way to do processing on a thread that isn’t the UI thread. This keeps the UI thread focused on the UI instead of other time-intensive tasks, such as disk or server calls
 But this class has a couple of downsides and we are not always aware of them.
1.  Lifecycle
(a) There is quite a misunderstanding about our AsyncTask. Developers might think that when the Activity that created the AsyncTask has been destroyed, the AsyncTask will be destroyed as well. This is not the case. The AsyncTask keeps on running, doing his doInBackground() method until it is done. Once this is done it will either go to the onCancelled(Result result) method if cancel(boolean) is invoked or the onPostExecute(Result result) method if the task has not been cancelled.
Suppose our AsyncTask was not cancelled before our Activity was destroyed. This could make our AsyncTask crash, because the view it wants to do something with, does not exist anymore. So we always have to make sure we cancel our task before our Activity is destroyed.
(b) Pausing an activity doesn’t pause the AsyncTask
2.  Memory leaks
An AsyncTask has methods that run on the worker thread (doInBackground()) as well as methods that run on the UI ( onPostExecute()), it has took keep a reference to it's Activity as long as it's running. But if the Activity has already been destroyed, it will still keep this reference in memory. This is completely useless because the task has been cancelled anyway. So it gives memory leaks.
3. Configuration changes
Another problem is that we lose our results of the AsyncTask if our Activity has been recreated. For example when an orientation change occurs. The Activity will be destroyed and recreated, but our AsyncTask will now have an invalid reference to its Activity, so onPostExecute() will have no effect.
There is a solution for this. You can hold onto a reference to AsyncTask that lasts between configuration changes (for example using a global holder in the Application object).  Activity.onRetainNonConfigurationInstance() and Fragment.setRetainedInstance(true) may also help you in this case.
Do we need AsyncTasks?
Not really. Now there is  an easy way to implement background features in our app without having to write a lot of code(For Async Task). we can do it  by using Loaders. They were introduced in Android 3.0 (Honeycomb) and are also available in the support library.
   Now before going to use Android Loader for background process we have to look on its characteristics. Loaders have these characteristics:
  1. Loaders are basically used to provide asynchronous loading of data for an Activity or  Fragment on Non-UI thread. While the application should perform any call to a Loader from the main thread, the Loader (or subclasses of Loader) performs their work in a separate thread and delivers its results to the main thread.  
  2. The code implementation should not derive directly from android.content.Loader class but specifically from android.content.CursorLoader class. 
  3. The callbacks of the Loader are invoked at different stages during loading of data in an Activity or Fragment. In short, an Activity or a Fragment are required to implement Listeners to use Loaders.   
  4. Loaders internally use AsyncTask to perform the data load. There is no performance gain when Loaders are compared to AsyncTask, provided that the AsyncTask are designed and developed properly.   
  5. Loader, more specifically, CursorLoader queries the Content Resolver in the background thread so that the application's User Interface is not blocked and returns the loaded Cursor to the Activity or Fragment. 
  6. CursorLoader handles the life cycle of the cursor. When using CursorLoader, the developer should never call close() on the cursor.     
  7. Loader persist the data fetched to avoid repetitive fetch operations for simple Activity refresh event like orientation change, keyboard open etc.  
  8. Loader monitor the source of its data and deliver new results when the content changes. It automatically  reconnects to the last loader’s cursor when being recreated after a configuration change avoiding the  need to re-query their data. In other words, CursorLoader auto updates and hence there is no need to  requery the cursor.   
  9. Loaders, in particular CursorLoader, are expected to retain their data after being stopped. This allows applications to keep their data across the Activity or fragment's onStop() and onStart() methods, so that when users return to an application, they don't have to wait for the data to reload.   
  10. Loaders are available as a part of the compatibility library. So developers can use it in applications that run on android build previous to HoneyComb. 
  11. Developers should use CursorLoader instead of Activity.managedQuery or Activity.startManagingCursor starting in android 3.0.  
  12. There is only one LoaderManager per Activity or Fragment. The LoaderManager manages the life of one or more Loader instances automatically within an Activity or Fragment. 
Point No 7, 8, and 9 are important. It gives Android Loader an edge over AsyncTask. Over all properties of  Android Loader shows that it is useful to use Loaders in place of AsyncTask generally. In some case we can use Async task based upon our need but I will suggest you that before using Async task or Android Loader analyse your application needs. If there is no to much data to fetch from Server or DB which going to change frequently then use AsyncTask otherwise use Android Loader.
In my next post I shall discuss Android Loaders it type and uses with examples.
Thanks
Happy Coding !!! 

Monday 4 November 2013

Speed up your Android's emulator

Hello Guys !!! Hope  you are doing well.
Today I am going to discuss about emulator. As you know that Android Emulator is  a virtual test device for your App development. An Android app running in the emulator should behave nearly identically on a target device; you should also be able to run some level of performance tests on the Android emulator.
     But practically  an Android emulator tends to be so slow on most development machines -- any sort of performance testing is almost impossible. The latency of Android's emulator has continued to increase with each iteration of the new android versions and starting at about 4.0 (Ice Cream Sandwich), The out-of-the-box Android emulator experience has become somewhat painful in the last 18 months.
Luckily, the open nature of Android has made it easy for third parties to step in, pick up the ball, and run with it. This leads into my discussion of Genymotion, a commercial offshoot of the open source project AndroVM. Genymotion is a very fast, Android emulator that works for Windows, Mac, and Linux.  Best of all (at least for now), it's free.
Genymotion integrates directly into Eclipse, has a slew of pre-configured popular phone images to choose from, and supports the majority of critical sensor emulation. The only area where I find Genymotion lacking is that I haven't figured out a way to throttle the network connection to emulate 3G, even after reading the documentation.
  Here I am putting some screen shot of Genymotion  VM device. Look on that images. I am also going to help you out how to install and use this Genymotion  VM device for your app development testing.




Now I am going for setup this fast Android VM with some basic question.
1. What is Genymotion ?
Genymotion is the fastest Android emulator for app testing and presentation. Genymotion is the evolution of AndroVM open source project, already trusted by 300 000 developers.

2. Features of Genymotion:

  1. Fastest Android emulator right now.
  2. Do your simultanous automatic tests on unlimited virtual appliances .
  3. Directly launch Genymotion from your Eclipse and Android Studio platforms.
  4. It has Open GL acceleration ,multiscreen and full screen display.

3. Steps to Setup Genymotion Android Emulator in Windows OS:

  1. Go to http://www.genymotion.com/ and sign up.
  2. After logging in download genymotion for Windows 32/64 bits from the following link.
  3. https://cloud.genymotion.com/page/launchpad/download/
  4. Download and install virtualbox for linux from the following link.
  5. https://www.virtualbox.org/wiki/Downloads
  6. Now run the the downloaded genymotion-1.1.0.exe and install the Genymotion on your PC.
  7. Then launch Genymotion and login with your Username and Password.
  8. Select Add to create a new virtual device, then select a device from the list and click Add. See the 2nd Image for more detail. 
  9. Then select next and the Virtual image starts downloading.
  10. When the download is completed select next from the window.
  11. Then you will be asked to enter a name for the downloaded Genymotion virtual device. Enter a name and select create and the click finish.
  12. Now the virtual device will be listed in “Your virtual devices” in the home screen.
  13.  Then select play to start your virtual device.For the first time it asks to configure sdk path for using ADB , select the sdk path and you will be booted to Android home screen.

4. Configure Genymotion with Eclipse IDE:
  1. Open Eclipse and select Help->Install New Software.
  2. Enter the URL http://plugins.genymotion.com/eclipse and hit Enter
  3. Genymobile will be shown, select it and click next.
  4. Genymotion Eclipse Plugin will be downloaded and installed.
  5. Now restart Eclipse IDE the plugin will be active.
  6. Now you can run your apps developed in eclipse in Genymotion Android Emulator.
     Happy Codings !!!
Any questions and Suggestion please comment here.
Thanks

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...