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

Saturday 5 October 2013

Fragment lifecycle

Hello Guys!!! Hope You all doing well. Today I am going to discuss fragment and its lifecycle methods. In my previous post Fragment and It uses I had discussed the basic of fragments and Its implementation. Today we are moving further  to discuss the fragment lifeCycle and its Type.
As we know that  fragment lives only inside an Activity that acts as a container.Each fragment has its own view hierarchy that can be inflated as we do usually.  A fragment lifecycle is more complex than the activity lifecycle because it has more states. These lifecycle states are shown above.
 Now I am going to shade some light on this lifeCycle states.
1. onAttach()
This method is called as soon as the fragment is “attached” to the “father” activity and we can use this method to store the reference about the activity.
2. onCreate()
 After  calling onAttach() method  we have  to call onCreate() method. It is one of the most important step, our fragment is in the creation process. This method can be used to start some thread to retrieve data information, maybe from a remote server.
3. onCreateView()
The onCreateView is the method called when the fragment has to create its view hierarchy. During this method we will inflate our layout inside the fragment as we do for example in the ListView widget(Fragment and It uses). During this phase we can’t be sure that our activity is still created so we can’t count on it for some operation.
4. onActivityCreated()
 onActivityCreated()  called  to give a  notification to fragment that  “father” activity is created and it is  ready  for use.  From now on, our activity is active and created and we can use it when we need.
5. onStart()
The next step is onStart() method. Here we do the common things as in the activity onStart(), during this phase our fragment is visible but it isn’t still interacting with the user.
6. onResume()
When the fragment is ready to interact with user onResume() is called. At the end of this phase our fragment is up and running.
7. onPause()
Then it can happen that the activity is paused and so the activity’s onPause is called. Well onPause fragment method is called too.
8. onDestroyView()
After it it can happen that the OS decides to destroy our fragment view and so onDestroyView is called.
9. onDestroy()
After it, if the system decides to dismiss our fragment it calls onDestroy() method. Here we should release all the connection active and so on because our fragment is close to die.
10. onDetach()
 Even if it is during the destroy phase it is still attached to the father activity. The last step is detach the fragment from the activity and it happens when onDetach() is called.
This is all about fragment lifeCycle. Now I am  putting all above this as summary.

Phase I: When a fragment gets created, it goes through the following states:
  • onAttach()
  • onCreate()
  • onCreateView()
  • onActivityCreated()

Phase II: When the fragment becomes visible, it goes through these states:
  • onStart()
  • onResume()

Phase III: When the fragment goes into the background mode, it goes through these states:
  • onPaused()
  • onStop()

Phase IV: When the fragment is destroyed, it goes through the following states:
  • onPaused()
  • onStop()
  • onDestroyView()
  • onDestroy()
  • onDetach()


Sunday 25 August 2013

Fragment and It uses In Android

Hello Guys, Hopes You are Doing Well.
Today  I am going to discuss Fragment and it use in Android. Fragment introduced in Android Version 3.0 (HoneyComb). To use the larger screen size device(Tablet). But now it is  used actively in  responsive design and reuse-ability of code. Before proceeding in depth the first basic question?
What is Fragment? and what is  the benefit to use it?
 A fragment is simply a block of UI, with its own life cycle, that can be reused within different activities. Fragments allow developers to create highly modular user interface components that can change dramatically based on screen sizes, orientation, and other aspects of the display that might be relevant to the design.
What is the inter-dependency between Activity and Fragment ?
A fragment must always be embedded in an activity and the fragment's life cycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. However, while an activity is running, you can manipulate each fragment independently, such as add or remove them.
When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.
How  We can add fragment and what is the process?
When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout. You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup.
However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.
     
To define a new fragment you extend either the android.app.Fragment class or one of its subclasses, for example ListFragment, DialogFragment, PreferenceFragment or WebViewFragment. The following code shows an example implementation.

In that code I am showing two pan layout for tablet and single pan layout for device(Just like above given Images).  There are 4 java class file and two xml file under layout folder and one xml file under layout-large.
Here is following java and xml file name:-
/src folder
1. HomeActivity .java
2. HeaderFragment.java
3. ArticleFragment.java
4. DataCenter.java
/layout folder
1. activity_home.xml
2. article_view.xml
/layout-large folder
1. news_articles.xml
I have putted the detailed description of individual function in comment. So please going through this code have a look on that comments. It help you to understand this code thoroughly.
package com.sks.fragment;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
public class HomeActivity extends FragmentActivity
implements HeadlineFragment.OnHeadlineSelectedListener {
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_home);

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }
            // Create an instance of ExampleFragment
            HeadlineFragment firstFragment = new HeadlineFragment();

            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
             
       }
    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment

        // Capture the article fragment from the activity layout
        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);

        } else {
            // If the frag is not available, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }
       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.home, menu);
              return true;
       }

}

 2. HeadlineFragment
package com.sks.fragment;
import android.app.Activity;
import android.support.v4.app.ListFragment;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class HeadlineFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface OnHeadlineSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onArticleSelected(int position);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // We need to use a different list item layout for devices older than Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

        // Create an array adapter for the list view, using the Ipsum headlines array
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, DataContainer.Headlines));
    }

    @Override
    public void onStart() {
        super.onStart();

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        mCallback.onArticleSelected(position);
       
        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);
    }
}
3. public class ArticleFragment extends Fragment {
    final static String ARG_POSITION = "position";
    int mCurrentPosition = -1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        // If activity recreated (such as from screen rotate), restore
        // the previous article selection set by onSaveInstanceState().
        // This is primarily necessary when in the two-pane layout.
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.article_view, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();

        // During startup, check if there are arguments passed to the fragment.
        // onStart is a good place to do this because the layout has already been
        // applied to the fragment at this point so we can safely call the method
        // below that sets the article text.
        Bundle args = getArguments();
        if (args != null) {
            // Set article based on argument passed in
            updateArticleView(args.getInt(ARG_POSITION));
        } else if (mCurrentPosition != -1) {
            // Set article based on saved instance state defined during onCreateView
            updateArticleView(mCurrentPosition);
        }
    }

    public void updateArticleView(int position) {
        TextView article = (TextView) getActivity().findViewById(R.id.article);
        article.setText(DataContainer.Articles[position]);
        mCurrentPosition = position;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // Save the current article selection in case we need to recreate the fragment
        outState.putInt(ARG_POSITION, mCurrentPosition);
    }
}
 4. package com.sks.fragment;

public class DataContainer {

    static String[] Headlines = {
        "Android",
        "java",
        "Database"
    };

    static String[] Articles = {
        "Android\n\nExcepteur pour-over occaecat squid biodiesel umami gastropub, nulla laborum salvia dreamcatcher fanny pack. Ullamco culpa retro ea, trust fund excepteur eiusmod direct trade banksy nisi lo-fi cray messenger bag. Nesciunt esse carles selvage put a bird on it gluten-free, wes anderson ut trust fund twee occupy viral. Laboris small batch scenester pork belly, leggings ut farm-to-table aliquip yr nostrud iphone viral next level. Craft beer dreamcatcher pinterest truffaut ethnic, authentic brunch. Esse single-origin coffee banksy do next level tempor. Velit synth dreamcatcher, magna shoreditch in american apparel messenger bag narwhal PBR ennui farm-to-table.",
        "javao\n\nVinyl williamsburg non velit, master cleanse four loko banh mi. Enim kogi keytar trust fund pop-up portland gentrify. Non ea typewriter dolore deserunt Austin. Ad magna ethical kogi mixtape next level. Aliqua pork belly thundercats, ut pop-up tattooed dreamcatcher kogi accusamus photo booth irony portland. Semiotics brunch ut locavore irure, enim etsy laborum stumptown carles gentrify post-ironic cray. Butcher 3 wolf moon blog synth, vegan carles odd future.",
        "DataBase\n\nsgshuishuihsuish89 ugishuhs huisuihs8uh , huihsuihj. gfuyghuygh HGUygh bhuih8ihun dHJAGDSYUGS7GBV . ftF6TYF76TGF78YGH78 YUG7GUKBHUIH H78UH78H87UH.YUG78Y87YU9KHNUIY,HIHU "
    };
}
 Now xml file, at first under layout folder
1. activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
 2. article_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/article"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:textSize="18sp" />

lastly
3.  news_articles.xml 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="horizontal" >
    <fragment
        android:id="@+id/headlines_fragment"
        android:name="com.example.android.fragments.HeadlinesFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
    <fragment
        android:id="@+id/article_fragment"
        android:name="com.example.android.fragments.ArticleFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" />
</LinearLayout>
this is the starting code for Fragment. In next blog  I will put more light on Fragment LifeCycle and different type of fragment and Its uses. 
              Happy Coding !!!

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...