Android CursorLoader

When you build an application that retrieves data from ContentProvider or database, using CursorLoader is a good choice. The CursorLoader executes a query against ContentProvider and returns the results to Activity or FragmentActivity. The Activity or FragmentActivity still continues to interact with the user while the query is executing. The Activity or FragmentActivity that uses the CursorLoader must implement the LoaderCallbacks<Cursor> interface. You write code to execute the query in the onCreateLoader() and get the results in the onLoadFinished() method. Before the query can be executed, you need to initialize the background framework (e.g. data table, query, column names, and so on) using the initLoader() method of the LoaderManager. This method is placed in the onCreate() method of the Activity.
In the onLoadFinished(), you get the results in the Cursor object. This Cursor object can be passed the CursorAdapter so that the results can be displayed in ListView, Spinner, and so on.

Now to have example application on using CursorLoader, create a new Android project. In the activity_main.xml file you need to add a ListView. It will be used to display the call logs from an Android device.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.example.a ndexample.MainActivity"

>
<ListView
   android:id="@+id/calllist"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   >
  
  
</ListView>


</LinearLayout>

The call logs' information to display in the ListView contains calling number, calling date, and calling type. So, you need to have another layout called list_item.xml that is used as a single item template for the ListView.

<?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:orientation="horizontal" >
  
   <TextView
   android:id="@+id/callnum"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:padding="10sp"
   android:textStyle="bold" >
</TextView>
<TextView
   android:id="@+id/calldate"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:padding="10sp"
   android:textStyle="bold"
     >
</TextView>
<TextView
   android:id="@+id/calltype"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:padding="10sp"
   android:textStyle="bold" >
</TextView>
</LinearLayout>

In the src folder, you create a java file called CAdapter.java containing the CAdapter class. The CAdapter class extends the CursorAdapter class.

package com.example.andexample;
import java.util.Date;
import android.content.Context;
import android.database.Cursor;
import android.provider.CallLog;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class CAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
String[] callTypes={"Incoming Call","Outgoing Call","Missed Call"};
public CAdapter(Context context, Cursor cursor) {
     super(context, cursor, false);
     mInflater = LayoutInflater.from(context);
   }

   @Override
   public View newView(Context context, Cursor cursor, ViewGroup parent) {
      return mInflater.inflate(R.layout.list_item, parent, false);
   }
   @Override
   public void bindView(View view, Context context, Cursor cursor) {
   // set call number to callnum TextView
   String number=cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
     ((TextView) view.findViewById(R.id.callnum)).setText(number);
     // set call type to calltype TextView
     int type=cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
     ((TextView) view.findViewById(R.id.calltype)).setText(callTypes[type-1]);
   //format date field
   long time = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
     Date cdate=new Date(time);
     String format = "yyyy-MM-dd hh:mm";
     DateFormat.format(format, cdate);
     // set formatted to calldate TextView
     ((TextView) view.findViewById(R.id.calldate)).setText(DateFormat.format(format, cdate).toString());
   }
}

In the MainActivity class, you write code to initialize the background framework, execute the query, pass the result Cursor object to the CAdapter, and display the results in the ListView.

package com.example.andexample;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.app.NotificationManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity implements LoaderCallbacks<Cursor>{


SimpleCursorAdapter adapter;
private static final int LOADER_ID = 0;
String[] projection={CallLog.Calls._ID,CallLog.Calls.NUMBER,CallLog.Calls.DATE, CallLog.Calls.TYPE};
String[] ccolumns={CallLog.Calls.NUMBER,CallLog.Calls.DATE, CallLog.Calls.TYPE};
int lfields[]={R.id.callnum,R.id.calldate, R.id.calltype};
CAdapter adapt;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listview=(ListView)findViewById(R.id.calllist);
// Initialize CursorLoader
getLoaderManager().initLoader(LOADER_ID, null,this);
// Set the adapter for the view
adapt=new CAdapter(this,null);
listview.setAdapter(adapt);

}

public void onLoaderReset(Loader<Cursor> loader)
{

}

public void onLoadFinished(Loader<Cursor> loader, Cursor cursor){
// Change cursor of adapter
adapt.changeCursor(cursor);
}

public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle){

/*
* Takes action based on the ID of the Loader that's being created   */
switch (loaderID) {
case LOADER_ID:
// Returns a new CursorLoader
        return new CursorLoader(
                this,  // Parent activity context
                CallLog.Calls.CONTENT_URI, // Table to query
                projection,   // Projection to return
                null,        // No selection clause
                null,        // No selection arguments
                null         // Default sort order
     );
default:
// An invalid id was passed in
return null;
}
}

}

Android-CursorLoader

Posted by: Dara | post date: 10-13-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.