Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to work with cursor loader in Android

In this article we will show how we can use cursor loader in Android.

Before we start, it is important for our users to know what a loader is. The idea of loader was commenced in Android 3.0 (API Level 11). To supply asynchronous loading of data for an Activity of Fragment on Non-UI thread, Loaders are basically used. While the application should perform any call to a Loader from the main thread, the Loader must perform their work in a separate thread and delivers its results to the main thread. The code implementation should derive directly from android.content.CursorLoader class inspite of deriving it directly from android.content.Loader class In order to not block the application’s User Interface, Content Resolver Loader, more specifically, CursorLoader queries the Content Resolver in the background thread and returns the loaded Cursor to the Activity or Fragment.Lifecycle of a cursor is handled by CursorLoader.Developer should never call close() on cursor while using CursorLoader.

The distinctiveness of Loaders can be listed as follows:

  • During the loading of data in an Activity, the callbacks of the Loader are called at different stages. In short, an Activity or a Fragment is required to implement Listeners to use Loaders.
  • Loader persist the data fetched to avoid repetitive fetch operations for simple Activity refresh event like orientation change, keyboard open etc
  • When the content changes, Loader will monitor the source of its data and carry the new results. When it is reestablished after a configuration change, it automatically reconnects to the last loader’s cursor in order to avoid the need to re-query their data. In other words, CursorLoader auto updates and hence there is no need to requery the cursor.
  • Loaders 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.
  • CursorLoader, are likely to keep their data after being stopped. This allows applications to maintain their data across the Activity or fragment's onStop() and onStart() methods, so that when users go back to an application, they don't have to wait for the data to reload.

A loader is accessible as an element of the compatibility library. So developers can use it in applications that run on android build previous to Honeycomb. Developers should use CursorLoader instead of Activity.managedQuery orActivity.startManagingCursor starting in android 3.0. There is only one LoaderManager per Activity or Fragment. The LoaderManager control the life of one or more Loader occurrence automatically within an Activity or Fragment.

Any application that uses Loaders must contain the subsequent properties. Application should have an activity or fragment, an instance of the LoaderManager, CursorLoader to load the data packed by a ContentProvider.On the other hand, developers are free to apply their own subclass of Loader or AsyncTaskLoader to load different types of data, an implementation for LoaderManager.LoaderCallbacks. It is a callback interface that lets a client interact with the LoaderManager . A way of displaying the loader's data, such as a SimpleCursorAdapter, A data source, such as a ContentProvider, when using a CursorLoader.Users that use cursor loader in android 3.0 developer needs:

  • The developers need to use the compatibility library: http://developer.android.com/tools/extras/support-library.html
  • Follow these instructions on setting it up: http://developer.android.com/sdk/compatibility- library.html#SettingUp
  • The activity must extend FragmentActivity. You will probably need to import the following classes:

Listing 1: Shows the code for importing FragmentActivity and LoaderManager

import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;

You have to replace the line given below if you are using SimpleCursorAdapter.

Listing 2: Shows the line of code to be replaced

import android.widget.SimpleCursorAdapter;  

Listing 3: Shows the line of code after replacement

import android.support.v4.widget.SimpleCursorAdapter;

Now the steps which are used to write the code are given below:

  1. The activity needs to implement LoaderManager.LoaderCallbacks.
  2. Listing 4: Shows the code to implement LoaderManager.LoaderCallbacks.
    public class MyActivity implements LoaderManager.LoaderCallbacks<Cursor>
  3. Initialize the loader.
  4. Listing 5: Shows the code to initialize the loader

    loadermanager.initLoader(1, null, this);
  5. Implement the loader callback methods.
    • onCreateLoader: Instantiate and return a new Loader for the given ID. This is where the cursor is created.
    • onLoadFinished: Called when a previously created loader has finished its load. Here, you can start using the cursor.
    • onLoaderReset: Called when a previously created loader is being reset, thus making its data unavailable. It is being reset in order to create a new cursor to query different data. 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.

Listing 6: Shows the code how to use a loader

package tpg.main;
 
import tpg.database.DatabaseAccessUtility;
import tpg.database.DatabaseHandler;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.SimpleCursorAdapter;
 
public class MainActivity extends ListActivity implements LoaderCallbacks<Cursor>  {
 
	
    SimpleCursorAdapter mAdapter; 		
    LoaderManager loadermanager;		
    CursorLoader cursorLoader;
    private static String TAG="CursorLoader";
    
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	
        loadermanager=getLoaderManager();
	
	String[] uiBindFrom = {  DatabaseHandler.UserTable.name};		
	int[] uiBindTo = {android.R.id.text1};
	
        /*Empty adapter that is used to display the loaded data*/
	mAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1, null, uiBindFrom, uiBindTo,0);  
        setListAdapter(mAdapter);
       
/**
* This initializes the loader and makes it active. If the loader 
* specified by the ID already exists, the last created loader is reused.
* If the loader specified by the ID does not exist, initLoader() triggers 
* The LoaderManager.LoaderCallbacks method onCreateLoader(). 
* This is where you implement the code to instantiate and return a new loader. 
* Use restartLoader() instead of this, to discard the old data and restart the Loader.
* Hence, here the given LoaderManager.LoaderCallbacks implementations are associated with the loader. 
*/
       loadermanager.initLoader(1, null, this);
   }
	
/**
* This creates and return a new Loader (CursorLoader or custom Loader) for the given ID. 
* This method returns the Loader that is created, but you don't need to capture a reference to it. 
*/
   public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		
	String[] projection = { DatabaseHandler.UserTable.id, DatabaseHandler.UserTable.name };
		
/**
* This requires the URI of the Content Provider
* projection is the list of columns of the database to return. Null will return all the columns
* selection is the filter which declares which rows to return. Null will return all the 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 determines the order of rows. Passing null will use the default sort order, which may be unordered.
* To back a ListView with a Cursor, the cursor must contain a column named _ID.
*/
 
	cursorLoader = new CursorLoader(this, DatabaseAccessUtility.CONTENT_URI, projection, null, null, null);
	return cursorLoader;
		
   }
 
/**
* Called when a previously created loader has finished its load. This assigns the new Cursor but does not close the previous one. 
* This allows the system to keep track of the Cursor and manage it for us, optimizing where appropriate. 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.
* The framework would take of closing of old cursor once we return.
*/
 
   public void onLoadFinished(Loader<Cursor> loader,Cursor cursor) {
	if(mAdapter!=null && cursor!=null)
		mAdapter.swapCursor(cursor); //swap the new cursor in.
	else
		Log.v(TAG,"OnLoadFinished: mAdapter is null");
   }
 
/**
* This method is triggered when the loader is being reset and the loader data is no longer available. 
* 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.
*/
 
   public void onLoaderReset(Loader<Cursor> arg0) {
	if(mAdapter!=null)
		mAdapter.swapCursor(null);
	else
		Log.v(TAG,"OnLoadFinished: mAdapter is null");
   }
	
}

Conclusion

In this article, we talked about the basics of loader and the procedure of using them in Android.



I have done my bachelor in Computer Science and I am well versed with programming languages such as JAVA, C#, html and done courses on Android development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login