Saturday, April 28, 2012

Android 3D Gallery


Quick Action Like In Android 3D Gallery

- You have to Create ActionItem class object For add new item logo and text.
//dashboard action item
        ActionItem dashboard = new ActionItem();
dashboard.setTitle("Dashboard");
        dashboard.setIcon(getResources().getDrawable(R.drawable.dashboard));
- Now you have to create object of QuickAction class for adding this action item.
//create quickaction
        final QuickAction quickAction = new QuickAction(this);
quickAction.addActionItem(dashboard);
- This method is use for showing popup with action item.
quickAction.show(v);
Ex:
Button btn1 = (Button) this.findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                quickAction.show(v);
            }
        });

Inflate Fragments Layouts in Android



Fragment

You can see the previous post "Working with Fragments in Android" to know about Fragment. Let's directly move on example.

Example

- The example illustrates to inflate layout(.xml) file in Fragment area.
Step - 1:
- Create arrays.xml in /res/values and create string array as <string-array name="android_platforms">.
- Add below items in string array and it will look like as below
    <string-array name="android_platforms">
        <item>Android 3.2</item>
        <item>Android 3.1</item>
        <item>Android 3.0</item>
        <item>Android 2.3.4</item>
        <item>Android 2.3.3</item>
        <item>Android 2.2</item>
        <item>Android 2.1</item>
        <item>Android 2.3</item>
        <item>Android 2.0.1</item>
        <item>Android 2.0</item>
        <item>Android 1.6</item>
        <item>Android 1.5</item>
        <item>Android 1.1</item>
    </string-array>
- Create .xml files in /res/layout as per your requirement.
Step - 2:
- Get the position of selected list item.
    int position = getArguments().getInt("position", 0);
- Here, we are inflating layouts in onCreateView(...). The layout will change based on the position of list item.
    View view = null;
    if(position == 0) {
        view = inflater.inflate(R.layout.fr_layout_1, null);
    } else if(position == 1) {
        view = inflater.inflate(R.layout.fr_layout_2, null);
    } else if(position == 2) {
        view = inflater.inflate(R.layout.fr_layout_3, null);
    } else if(position == 3) {
        view = inflater.inflate(R.layout.fr_layout_4, null);
    } else if(position == 4) {
        view = inflater.inflate(R.layout.fr_layout_5, null);
    } else if(position == 5) {
        view = inflater.inflate(R.layout.fr_layout_6, null);
    } else if(position == 6) {
        view = inflater.inflate(R.layout.fr_layout_7, null);
    } else if(position == 7) {
        view = inflater.inflate(R.layout.fr_layout_8, null);
    } else if(position == 8) {
        view = inflater.inflate(R.layout.fr_layout_9, null);
    } else if(position == 9) {
        view = inflater.inflate(R.layout.fr_layout_10, null);
    } else if(position == 10) {
        view = inflater.inflate(R.layout.fr_layout_11, null);
    } else if(position == 11) {
        view = inflater.inflate(R.layout.fr_layout_12, null);
    } else if(position == 12) {
        view = inflater.inflate(R.layout.fr_layout_13, null);
    }
Step - 3:
- Follow this step from the older article "Working with Fragments in Android".
Step - 4:
- Create main_fragment.xml in /res/layout.
- Register FragmentListTitles in <fragment /> tag.
    <fragment
        android:id = "@+id/fragment1"
        android:name = "com.indianic.fragmentview.FragmentListTitles"
        android:layout_width = "0dp"
        android:layout_height = "match_parent"
        android:layout_weight = "1"
        android:layout_marginRight = "4dp">
    </fragment>
The android:name attribute has below format <package name>.<class name>
android:name = "com.indianic.fragmentdemo.FragmentListTitles"
- Set a FrameLayout to display content.
    <FrameLayout
         android:id = "@+id/fragment2"
         android:layout_weight = "1"
         android:layout_width = "0px"
         android:layout_height = "match_parent"
         android:background = "?android:attr/detailsElementBackground">
    </FrameLayout>
Step - 5:
- Run application.
Find the attached zip file for complete source code.
I would be glad to receive your suggestions regarding it.
Thanks.

OAuth For Google API in Android


Auth is the preferred method for getting authorized access to a user's Google data. OAuth is an open standard for authorizing the use of data on the web. we can use OAuth for authorization with the Calendar service, other Google services, or with services from other companies that have adopted the standard.
To use OAuth, application must obtain an access token by following this sequence of token requests:
Client Login Method :
Client Login is one of the best method for obtaining Authentication token.With ClientLogin,application prompts the user for username and password on first run. After that, application uses a token for authorized access to the user's data.
To authenticate the user, send a POST request to the following URL: * https://www.google.com/accounts/ClientLogin*
Include the relevant parameters in the body of the POST request
Parameter For Client Login :
·      accountType:Type of account to request authorization for. Possible values are:
1      GOOGLE (get authorization for a Google account only)
2      HOSTED (get authorization for a hosted account only)
3      HOSTED_OR_GOOGLE (get authorization first for a hosted account; if attempt fails, get authorization for a Google account)
·      Email : User's full email address. It must include the domain (i.e.ramesh.turi@indianic.com).
·      Passwd :User's password.
·      service :Name of the Google service you're requesting authorization for.eg. The service name for Calendar is cl.
·      source = Short string identifying your application, for logging purposes. This string should take the form:
"companyName-applicationName-versionID". eg "indianic.projectname-1.0"
The POST request should be structured as a form post with the default encoding "application/x-www-form-urlencoded" because gogle api does not support any plaintext
so please in post request header set "Content-type" to "application/x-www-form-urlencoded".
If the request succeeds, then the response contains an alphanumeric string labeled Auth.
After a successful authentication request, use the Auth value to create an Authorization header for each request: * Authorization: GoogleLogin auth=yourAuthValue*
Function for getting Auth value :
public String getAuthentication(String email, String password) {
        String AUTH = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "https://www.google.com/accounts/ClientLogin");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("Email", email)); 
            nameValuePairs.add(new BasicNameValuePair("Passwd", password)); 
            nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
            nameValuePairs.add(new BasicNameValuePair("source",
                    "Google-cURL-Example"));
            /**
             * for calendar service value is "cl"
             */
            nameValuePairs.add(new BasicNameValuePair("service", "cl")); 
            /***
             * // content-type must be "application/x-www-form-urlencoded"
             */
            post.setHeader("Content-type", "application/x-www-form-urlencoded");
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = client.execute(post);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                Log.e("rd", line);
                if (line.startsWith("Auth=")) {
                    String s = line.substring(5);
                    AUTH = s;
                }
            }
            System.out.println(AUTH + "<-----------------");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AUTH;
    }

this function returns the Auth value from the given user.
After getting Auth value, we can access google api which is mentioned in service parameter of client login request. eg "cl" for calendar so we can access any calendar api using this auth value.
to access any service use following code :
/// URL  = "https://www.google.com/calendar/feeds/default/owncalendars/full";
/// this url is used to getting the calendar list for user
 /// Authvalue = Authentication value   

public String getData(String URL, String Authvalue) {
        final DefaultHttpClient httpClient = createHttpClient();
        final HttpGet httpget = new HttpGet(URL);
        HttpResponse response = null;
        try {
            Log.i("Util", "posted Url:" + URL);
            httpget.setHeader("Authorization", "GoogleLogin auth=" + Authvalue);
            httpget.setHeader(HTTP.CONTENT_TYPE, "application/json");
            response = httpClient.execute(httpget);
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            return "";
        }
    }
to get all response in json please append "alt=jsonc" to each service url.
Please refer to this given link for more information.
Reference : http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html

Handling User Interaction with Android App Widgets in Android



In order to handle user interaction with an App Widget, the following tasks must be performed:
1.Set a unique click handler for each App Widget control
2.Have the click handler send a command to a registered receiver
3.Process the command received and perform any action necessary
4.Update the App Widget to reflect the changes
We include a button bar with three controls. Each of the buttons on the button bar will perform a specific action and clicking anywhere else in the App Widget will hide the button bar. The left-hand button (tool set) will launch the configuration Activity so users can change the time interval between image transitions in the slideshow. The middle button will pause or resume, the slideshow. The right-hand button allows the user to skip to the next image immediately.
Working with RemoteViews
In order to enable user interaction with a RemoteViews control, you must register for a PendingIntent to be triggered when a specific View within the RemoteViews object is clicked. This is done with a call to the setOnClickPendingIntent() method of the RemoteViews object. For instance, to add the PendingIntent for launching the Activity to configure the slideshow time interval.
PendingIntent pendingIntent = PendingIntent.getActivity
     (context, 0, configIntent,
     PendingIntent.FLAG_UPDATE_CURRENT);
  remoteView.
     setOnClickPendingIntent(R.id.config, pendingIntent);
Working with PendingIntents
the Intent had to be unique in order for the application to differentiate between specific instances of the App Widget, since more than one might exist. This was achieved by including the App Widget identifier in the Uri field, allowing each App Widget to have its own time interval.
Intent configIntent =
     new Intent(context, ImagesWidgetConfiguration.class);
  configIntent.putExtra(
     AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
  configIntent.setData(Uri.withAppendedPath(Uri.Parse
     (ImagesWidgetProvider.URI_SCHEME + "://widget/id/"),
     String.valueOf(appWidgetId)));
At first, it might seem like the state information could be encoded as part of the Intent being sent by the button handler. Remember, however, that the App Widget will also be updating on a regular schedule with the Intent sent by the Alarm. That Intent won't be changing and won't know the new state. In order to solve this problem, we create a new action type for the App Widget called ACTION_WIDGET_CONTROL and append the command to the Uri of the Intent. We then store the state of the App Widget in the SharedPreferences.
private PendingIntent makeControlPendingIntent
     (Context context, String command, int appWidgetId) {
     Intent active = new Intent();
     active.setAction(ACTION_WIDGET_CONTROL);
     active.putExtra(
        AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
     Uri data = Uri.withAppendedPath(
        Uri.parse(URI_SCHEME + "://widget/id/#"+command),
        String.valueOf(appWidgetId));
     active.setData(data);
     return(PendingIntent.getBroadcast(context,
        0, active, PendingIntent.FLAG_UPDATE_CURRENT));
  }

The block of code above creates a new Intent with an action of ACTION_WIDGET_CONTROL, which is simply a string.
The App Widget will be able to receive these broadcasts in its onReceive() handler method
else if (ACTION_WIDGET_CONTROL.equals(action)) {
     final int appWidgetId = intent.getIntExtra(
        AppWidgetManager.EXTRA_APPWIDGET_ID,
        AppWidgetManager.INVALID_APPWIDGET_ID);
     if (appWidgetId !=
        AppWidgetManager.INVALID_APPWIDGET_ID) {
        this.onHandleAction(
           context, appWidgetId, intent.getData());
  }
I have create ImageWidgetDemo , attached with this article.

How to create App Widget in Android?


An App Widget is basically just a BroadcastReceiver that handles specific actions.
Creating a simple App Widget involves several steps:
Create a RemoteView, which provides the user interface for the App Widget.
Tie the RemoteView to an Activity that implements the AppWidgetProvider interface.
Provide key App Widget configuration information in the Android manifest file.
Available views and layouts
A widget is restricted in the elements it can use. For layouts you can use "FrameLayout", "LinearLayout" and "RelativeLayout". As views you can use "AnalogClock", "Button", "Chromometer", "ImageButton", "ImageView", "ProgressBar" and "TextView".
The only interaction with is possible on the views of a widget is via on OnClickListener.
Widget size
A widget will take a certain amount of cells on the homescreen. A cell is usually used to display the icon of one application. As a calculation rule you should define the size of the widget with the formula: ((Number of columns / rows)* 74) - 2. These are device independent pixels and the -2 is used to avoid rounding issues.
Lifecycle method
The AppWidgetProvider interface simplifies handling these actions by providing a framework for developers to implement the following methods:
onEnabled(): Called when the first App Widget is created. Global initialization should take place here, if applicable.
onDisabled(): The inverse of the onEnabled() method, called when the last App Widget handled by this definition is deleted. Global cleanup should take place here, if applicable.
onUpdate(): Called when the App Widget needs to update its View, which could be when the user first creates the widget.
onDeleted(): Called when a particular instance of this App Widget is deleted. Cleanup for the specific instance in question should take place here.
onReceive(): The default implementation of this method handles the BroadcastReceiver actions and makes the appropriate calls to the methods shown above.
For the Android system to know about the App Widget, place a standard <receiver> tag in the Android manifest file.
<receiver android:name="MyWidgetProvider" android:label="Example Widget">
     <intent-filter>
          <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
     </intent-filter>
    <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/widget_info" />
</receiver>

In <receiver> definition, a <meta-data> section references an XML file resource. This file defines addition data for App Widget, corresponding to the AppWidgetProviderInfo class. This attribute specifies that the AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast. This is the only broadcast that you must explicitly declare.
AppWidgetProviderInfo
The following code shows the complete widget_info.xml file:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:updatePeriodMillis="180000"
    android:initialLayout="@layout/widget_layout"
    android:minHeight="72dp" android:minWidth="146dp" >
</appwidget-provider>

The <appwidget-provider> tag defines the size of the App Widget, the default layout to use, and the configuration Activity to launch whenever an instance of the App Widget is created. To display nicely on the Home screen, widgets must adhere to certain size guidelines.The smallest update interval is 180000 milliseconds (30 minutes). A more flexible update can be archived with the AlarmManager which we will demonstrate later in this tutorial.
Implementing onUpdate()
Update via a service
An App Widget that doesn't display anything isn't very useful. Luckily, the implementation for the RemoteView object of this App Widget is straightforward.
Here we can start service for long running operations or we can set update the App Widget at intervals defined by the updatePeriodMillis attribute.
 RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.widget_layout);
        Intent intent = new Intent(context.getApplicationContext(),
                UpdateWidgetService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

        // To react to a click we have to use a pending intent as the
        // onClickListener is
        // excecuted by the homescreen application
        PendingIntent pendingIntent = PendingIntent.getService(
                context.getApplicationContext(), 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.layout, pendingIntent);

        // Finally update all widgets with the information about the click
        // listener
        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);

        // Update the widgets via the service
        context.startService(intent);
Working with RemoteViews
An App Widget uses a special display control called RemoteViews. Unlike a regular View, a RemoteViews control is designed to display a collection of View controls in another process. Consequently, you can't simply add a button handler because that code would run in your application process, not in the process displaying the RemoteViews object (in this case, the Home Screen process).In order to enable user interaction with a RemoteViews control, you must register for a PendingIntent to be triggered when a specific View within the RemoteViews object is clicked. This is done with a call to the setOnClickPendingIntent() method of the RemoteViews object.
Working with PendingIntents
A PendingIntent is basically a wrapper object combining an Intent with its target action, such as startActivity() or broadcastIntent().
Android services are loosely defined as background processes or executables that can be accessed from other applications. They can be started, to run in the background, or they can be directly connected to by means of a remote interface. On the Service-side of the startService() call is our onStart() handler.In this method we can update widget.
Random random = new Random();

        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this
                .getApplicationContext());

        int[] appWidgetIds = intent
                .getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
        if (appWidgetIds.length > 0) {
            for (int widgetId : appWidgetIds) {
                int nextInt = random.nextInt(100);
                fakeUpdate = "Random: " + String.valueOf(nextInt);
                RemoteViews remoteViews = new RemoteViews(getPackageName(),
                        R.layout.widget_layout);
                remoteViews.setTextViewText(R.id.TextView01, fakeUpdate);
                appWidgetManager.updateAppWidget(widgetId, remoteViews);
            }
            stopSelf();
        }

Please refer to this given link for more information :[[http://www.vogella.de/articles/AndroidWidgets/article.html]]

Action Bar with Tabs and Options Menu in Android


Action Bar

You can see the previous article Action Bar with Tabs to know about Action Bar. Here, we directly move on Options Menu.

Add Options Menu with Example

Step - 1: Create a xml file named main_menu.xml in /res/menu. If /menu directory is not available in /res, create it as /res/menu.
Step - 2: Display options for Date-Time and Share in Action Bar. Add below code in /res/menu/main_menu.xml.
    <item
        android:id = "@+id/time"
        android:title = "Time"
        android:icon = "@drawable/clock"
        android:showAsAction="ifRoom|withText">
    </item>
    <item
        android:id = "@+id/share"
        android:title = "Share"
        android:icon = "@drawable/share"
        android:showAsAction="ifRoom|withText">
    </item>
- Add below code to display menu.
    <item
        android:id = "@+id/defaultDialog"
        android:title = "Default Dialog"
        android:showAsAction = "never">
    </item>
    <item
        android:id = "@+id/customDialog"
        android:title = "Custom Dialog"
        android:showAsAction = "never">
    </item>
Step - 3 Create following classes to set tabs.
- TabModel.java: Write a method to get tab name.
    public String getTabName() {
        return tabName;
    }
- TabTitles.java: Write a method to get tab name, tab models and number of tabs respectively.
    public String getTabName() {
        return tabName;
    }

    public TabModel getTabModels(int index) {
        return tabModels[index];
    }

    public int getTabCount() {
        return tabModels.length;
    }
- Tabs.java: Wirte a method to add tab and their values.
    private static TabTitles[] tabTitles;

    public static void initTabTitles() {

        tabTitles = new TabTitles[] {

            new TabTitles("Android Platforms", new TabModel[] {
                    new TabModel("3.2"),
                    new TabModel("3.1"),
                    new TabModel("3.0"),
                    new TabModel("2.3.4"),
                    new TabModel("2.3.3"),
                    new TabModel("2.2"),
                    new TabModel("2.1"),
                    new TabModel("2.3"),
                    new TabModel("2.0"),
                    new TabModel("1.6"),
                    new TabModel("1.1")
            }),
            new TabTitles("Android Mobiles", new TabModel[] {
                    new TabModel("Samsung"),
                    new TabModel("HTC"),
                    new TabModel("LG"),
                    new TabModel("Motorola"),
                    new TabModel("Sony Ericsson"),
                    new TabModel("Acer"),
                    new TabModel("Micromax"),
            }),
        };
    }
Step - 4: Create custom_dialog.xml for displaying custom dialog and add below layout in it.
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is an example of custom dialog."
        android:textStyle="bold"
        android:background="#343434"
        android:gravity="center"
        android:padding="50dp"
        android:textSize = "20sp">
    </TextView>
Step - 5: Apply the code to set tabs in Action Bar in ActionBarDemoActivity.java
- Initialize the tabs.
    Tabs.initTabTitles();
- Add tabs in Action Bar
    ActionBar actionBar = getActionBar();                         
    for (int i = 0; i < Tabs.getCount(); i++) {                   
        actionBar.addTab(actionBar.newTab().setText(              
                Tabs.getTab(i).getTabName()).setTabListener(this));
    }                                                             
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);   // Do not forget to add this line, otherwise tabs won't displayed.
    actionBar.setDisplayShowHomeEnabled(true);                    
- Add Options Menu in Action Bar
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
- Derive below @Override method
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int action = item.getItemId();
- Open dialog for menu option Share
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("text/html");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html
            .fromHtml(""));
    startActivity(Intent.createChooser(sharingIntent, "Share using"));
- Open Default Dialog from menu
- Open Custom Dialog from menu
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.custom_dialog, null);
    builder.setCustomTitle(view);
    builder.show();

Action Bar with Tabs in Android



The Action Bar is a widget for activities that replaces the traditional title bar at the top of the screen. By default, the Action Bar includes the application logo on the left side, followed by the activity title, and any available items from the Options Menu on the right side.

Features

·      Display items from the Options Menu directly in the Action Bar, as "action items"—providing instant access to key user actions.
·      Menu items that do not appear as action items are placed in the overflow menu, revealed by a drop-down list in the Action Bar.
·      Provide tabs for navigating between fragments.
·      Provide a drop-down list for navigation.
·      Provide interactive "action views" in place of action items (such as a search box).

Example

Step - 1: Get access of Action Bar
final ActionBar actionBar = getActionBar();
Step - 2 Create a class MyActionBarListener which implements ActionBar.TabListener to set action on tab.
private class MyActionBarListener implements ActionBar.TabListener {
Step - 3: Add tab to Action Bar. (You can add multiple tab)
actionBar.addTab(actionBar.newTab().setText("Tab 1").setTabListener(new MyActionBarListener()));
Step - 4: After adding all tabs, set setNavigationMode(...) to Action Bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Step - 5: Run Application

Loader API in Android


Before starting Loader I will recommend you all to get a brief about Fragments which are introduced in Android API level 11 (i.e. HoneyComb).
Loader is introduced in Android 3.0, loaders make it easy to asynchronously load data in an activity or fragment. Loaders have these characteristics:
·      They are available to every Activity and Fragment.
·      They provide asynchronous loading of data.
·      They monitor the source of their data and deliver new results when the content changes.
·      They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.
Dealing with Loader you may came across to the classes/interfaces LoaderManager, LoaderManager.LoaderCallbacks, Loader, AsyncTaskLoader, CursorLoader.
The LoaderManager manages one or more Loader instances within an Activity or Fragment. There is only one LoaderManager per activity or fragment.

Starting a Loader

Loader should be initialized within the activity's onCreate() method, or within the fragment's onActivityCreated() method using initLoader() method.
The initLoader() method takes the following parameters:
·      A unique ID that identifies the loader. In this example, the ID is 0.
·      Optional arguments to supply to the loader at construction (null in this example).
·      A LoaderManager.LoaderCallbacks implementation, which the LoaderManager calls to report loader events. In this example, the local class implements the LoaderManager.LoaderCallbacks interface, so it passes a reference to itself, this.
// Prepare the loader.  Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);

Restarting a Loader

When you use initLoader(), as shown above, it uses an existing loader with the specified ID if there is one. If there isn't, it creates one. But sometimes you want to discard your old data and start over.
To discard your old data, you use restartLoader().
 getLoaderManager().restartLoader(0, null, this);

Using the LoaderManager Callbacks

LoaderManager.LoaderCallbacks is a callback interface that lets a client interact with the LoaderManager.
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. You use the LoaderManager.LoaderCallbacks methods when to know when to create a new loader, and to tell the application when it is time to stop using a loader's data.
LoaderManager.LoaderCallbacks includes these methods:
·      onCreateLoader() — Instantiate and return a new Loader for the given ID.
·      onLoadFinished() — Called when a previously created loader has finished its load.
·      onLoaderReset() — Called when a previously created loader is being reset, thus making its data unavailable.
These methods are described in more detail in the following sections.
onCreateLoader
When you attempt to access a loader (for example, through initLoader()), it checks to see whether the loader specified by the ID exists. If it doesn't, it triggers the LoaderManager.LoaderCallbacks method onCreateLoader(). This is where you create a new loader. Typically this will be a CursorLoader, but you can implement your own Loader subclass.
onLoadFinished
This method is called when a previously created loader has finished its load. This method is guaranteed to be called prior to the release of the last data that was supplied for this loader. At this point you should remove all use of the old data (since it will be released soon), but should not do your own release of the data since its loader owns it and will take care of that.
onLoaderReset
This method is called when a previously created loader is being reset, thus making its data unavailable. This callback lets you find out when the data is about to be released so you can remove your reference to it.
I will explain you how to use Loader in your app.And as I have mentioned you should have a little idea about the Fragments.

Step 1 : Create an android project and Activity

Create an Activity name FragmentListCursorLoader
Write following code in your onCreate() method
FragmentManager fm = getFragmentManager();

        // Create the list fragment and add it as our sole content.
        if (fm.findFragmentById(android.R.id.content) == null) {
            CursorLoaderListFragment list = new CursorLoaderListFragment();
            fm.beginTransaction().add(android.R.id.content, list).commit();
        }
Where getFargmentManager is the method defined in Activity Class.

Step 2 : Create CursorLoaderListFragment class

CursorLoaderListFragment is the class which will retrieve Contacts from Android Device and will display on the screen using Loader.
CursorLoaderListFragment has extended ListFragment and two interfaces named CursorLoaderListFragment and LoaderManager.LoaderCallbacks<Cursor>

Step 3 : Write onActivityCreateMethod :

        // Give some text to display if there is no data.  In a real
        // application this would come from a resource.
        setEmptyText("No phone numbers");

        // We have a menu item to show in action bar.
        setHasOptionsMenu(true);
        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(0, null, this);

Now in this method there are three lines which I need to explain you.
1) setEmptyText will display the content which is passed in argument only when there is no data to diplay.
2) setHasOptionMenu will indicate whether to show the optionMenu content in the Activity or not.
3) getLoaderManager().initLoader(0, null, this); will init the loader. We need to give the unique Id to the initLoader, for our example it is 0.

Step 4 : What Loader will do.

public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            // This is called when a new Loader needs to be created.  This
            // sample only has one Loader, so we don't care about the ID.
            // First, pick the base URI to use depending on whether we are
            // currently filtering.
            Uri baseUri;
            if (mCurFilter != null) {
                baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
                        Uri.encode(mCurFilter));
            } else {
                baseUri = Contacts.CONTENT_URI;
            }

            // Now create and return a CursorLoader that will take care of
            // creating a Cursor for the data being displayed.
            String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
                    + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
                    + Contacts.DISPLAY_NAME + " != '' ))";
            return new CursorLoader(getActivity(), baseUri,
                    CONTACTS_SUMMARY_PROJECTION, select, null,
                    Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
        }
As you can see the task which a Loader should perform is written in onCreateLoader method.
It needs...
·      uri — The URI for the content to retrieve.
·      projection — A list of which columns to return. Passing null will return all columns, which is inefficient.
·      selection — A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.
·      selectionArgs — You may include ?s in the selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings.
·      sortOrder — How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
Step 5 : Time to close the Loader
The loader will release the data once it knows the application is no longer using it. For example, if the data is a cursor from a CursorLoader, you should not call close() on it yourself. If the cursor is being placed in a CursorAdapter, you should use the swapCursor() method so that the old Cursor is not closed. For example:
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // Swap the new cursor in.  (The framework will take care of closing the
    // old cursor once we return.)
    mAdapter.swapCursor(data);
}

Step 6 : Reset the Loader

This callback lets you find out when the data is about to be released so you can remove your reference to it.
public void onLoaderReset(Loader<Cursor> loader) {
    // This is called when the last Cursor provided to onLoadFinished()
    // above is about to be closed.  We need to make sure we are no
    // longer using it.
    mAdapter.swapCursor(null);
}
You will also find method to create Menu and request search query also..
 @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Place an action bar item for searching.
        MenuItem item = menu.add("Search");
        item.setIcon(android.R.drawable.ic_menu_search);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        SearchView sv = new SearchView(getActivity());
        sv.setOnQueryTextListener(this);
        item.setActionView(sv);
    }

public boolean onQueryTextChange(String newText) {
        // Called when the action bar search text has changed.  Update
        // the search filter, and restart the loader to do a new query
        // with this filter.
        mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
        getLoaderManager().restartLoader(0, null, this);
        return true;
    }

I have attached demo project which has two different Activities. You can see it one by one for better understanding of the Loader.

Fragment in Android


A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
See more about Fragment at below link.
http://developer.android.com/guide/topics/fundamentals/fragments.html
For example, a news application can use one fragment to show a list of articles on the left and another fragment to display an article on the right—both fragments appear in one activity. A fragment should be a modular and reusable component in your application. The same concept is applied here.
There are few steps to create an example using Fragment. They are as follows.
Step - 1:
Define string arrays in /res/values/arrays.xml file.
- android_platforms : Contains all the Android Platforms (Left pane as List)
- platform_revisions : Contains all the contents for Android Platforms (Right pane as Content)
Step - 2:
- Create a class FragmentListContent.java which extends to Fragment. The FragmentListContent.java is used to fill out the content(name="platform_revisions") from arrays.xml of selected item from the list in fragment area.
- Add onCreateView(...) @Override method in FragmentListContent.java.
- Here, we are not inflating any other layout, so it would be return null.
        if (container == null) {
            return null;
        }
- Allow scroll for displaying content.
        ScrollView scroller = new ScrollView(getActivity());
        TextView text = new TextView(getActivity());
        int padding = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 4, getActivity().getResources()
                        .getDisplayMetrics());
        text.setPadding(padding, padding, padding, padding);
        scroller.addView(text);
- Get the content of the selected position from /res/values/arrays.xml.
        String[] REVISION = getResources().getStringArray(R.array.platform_revisions);
        text.setText(REVISION[getArguments().getInt("position", 0)]);
Step - 3:
- Create a class FragmentListTitles.java which extends to ListFragment. http://developer.android.com/reference/android/app/ListFragment.html.
- The FragmentListTitles.java is used to fill out Android Platforms(name="android_platforms") from arrays.xml into list. Already filled area would be replaced to existing content.
- Populate list
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getActivity(), android.R.layout.simple_list_item_activated_1);
        adapter.addAll(getResources().getStringArray(R.array.android_platforms));
        setListAdapter(adapter);
- Store state of current position
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        /*** STORE STATE OF CURRENT POSITION ***/
        outState.putInt("current_position", mCurrentCheckedPosition);
        outState.putInt("shown_position", mCheckedPosition);
    }
- Create a method showDetails(int index) and add below code to update the existing content by replacing new content for selected item
        /*** UPDATE THE CONTENT FOR SELECTED ITEM FROM THE LIST ***/
        getListView().setItemChecked(index, true);

        if (mCheckedPosition != mCurrentCheckedPosition) {
            FragmentListContent listContent = FragmentListContent
                    .newInstance(index);

            /*** REPLACE THE TRANSACTION WITH EXISTING AND UPDATE CONTENT ***/
            FragmentTransaction transaction = getFragmentManager()
                    .beginTransaction();
            transaction.replace(R.id.fragment2, listContent);
            transaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.commit();
            mCurrentCheckedPosition = index;
        }
Step - 4:
- Create main_fragment.xml in /res/layout.
- Register FragmentListTitles in <fragment /> tag.
    <fragment
        android:id = "@+id/fragment1"
        android:name = "com.indianic.fragmentdemo.FragmentListTitles"
        android:layout_width = "0dp"
        android:layout_height = "match_parent"
        android:layout_weight = "1"
        android:layout_marginRight = "4dp">
    </fragment>
The android:name attribute has below format <package name>.<class name>
android:name = "com.indianic.fragmentdemo.FragmentListTitles"
- Set a FrameLayout to display content.
    <FrameLayout
         android:id = "@+id/fragment2"
         android:layout_weight = "1"
         android:layout_width = "0px"
         android:layout_height = "match_parent"
         android:background = "?android:attr/detailsElementBackground">
    </FrameLayout>
Step - 5:
- Run application.
Find the attached zip file for complete source code.
I would be glad to receive your suggestions regarding it.
Thanks.