Home  >  Android

Android AsyncTaskLoader Example with ListView and BaseAdapter

By Arvind Rai, July 09, 2015
This page will walk through the Android AsyncTaskLoader example with ListView and BaseAdapter. AsyncTaskLoader uses AsyncTask to perform work. ListView is a view which shows items in vertically scrolling list. BaseAdapter is a common implementation for other adapters. While using AsyncTaskLoader we need to extend it and override at least a method i.e loadInBackground which perform the user task. After loading data we will set data to adapter and finally call notifyDataSetChanged() to reflect list view on UI. Here we will show a demo of AsyncTaskLoader which will populate data in list view using adapter.

AsyncTaskLoader

android.content.AsyncTaskLoader<D> is a loader that uses AsyncTask to perform the task. It is an abstract class and to use it we need to extend and override its methods. In our example we will iterate a list using ListView. Find some methods that need to be overridden.
loadInBackground() : Performs actual task in background and returns the result.
onCanceled(D data) : This method is called if task is cancelled before completion. It is used to clean up data post cancellation.
cancelLoadInBackground() : We override this method to cancel the background process. If there is no process in background, it is not going to be called.


ListView

android.widget.ListView is a view which shows items in a vertically scrolling list. To achieve it we need to add ListView in layout.
<ListView
     android:id="@+id/employees"
     android:layout_height="match_parent"
     android:layout_width="match_parent"/> 
which will be accessed as
ListView employeeListView = (ListView) findViewById(R.id.employees);
employeeListView.setAdapter(empAdapter);  

BaseAdapter

android.widget.BaseAdapter is common implementation of adapters like ArrayAdapter<T>, CursorAdapter and SimpleAdapter. BaseAdapter can be used with ListView. To use BaseAdapter , we need to extend it in our class and override required methods. Some of them are given below.
View getView(int position, View view, ViewGroup parent) : Returns a view that displays data at specified position.
Object getItem(int position): Returns the data item for a given position.
long getItemId(int position): Returns the row id associated with the given position.
int getCount() : Count of data items represented by adapter.

Finally to display data, we need to call notifyDataSetChanged().

Complete Example


Employee.java
package com.concretepage;
public class Employee {
    public String empid;
    public String name;
    public Employee(String id, String name) {
        this.empid = id;
        this.name = name;
    }
} 

EmployeeLoader.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
public class EmployeeLoader extends AsyncTaskLoader<List<Employee>> {
    public EmployeeLoader(Context context) {
		super(context);
    }
    @Override 
    public List<Employee> loadInBackground() {
    	List<Employee> list = new ArrayList<Employee>();
    	list.add(new Employee("emp1", "Brahma"));
    	list.add(new Employee("emp2", "Vishnu"));
    	list.add(new Employee("emp3", "Mahesh"));
        return list;
    }
} 

EmployeeAdapter.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class EmployeeAdapter extends BaseAdapter {
    private LayoutInflater inflater;
    private List<Employee> employees = new ArrayList<Employee>();
    public EmployeeAdapter(Context context, List<Employee> employees) {
        this.employees = employees;
        inflater = LayoutInflater.from(context);
    }
    @Override
    public View getView(int position, View view, ViewGroup parent) {
        Employee emp = (Employee) getItem(position);
        if (view == null) {
            view = inflater.inflate(R.layout.employeedata, null);
        }
        TextView empid = (TextView) view.findViewById(R.id.empid);
        empid.setText(emp.empid);
        TextView empname = (TextView) view.findViewById(R.id.empname);
        empname.setText(emp.name);
        return view;
    }
    @Override
    public Object getItem(int position) {
        return employees.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public int getCount() {
        return employees.size();
    }
    public void setEmployees(List<Employee> data) {
        employees.addAll(data);
        notifyDataSetChanged();
    }
} 

MainActivity.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.widget.ListView;
public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<List<Employee>> {
    EmployeeAdapter empAdapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      empAdapter = new EmployeeAdapter(this, new ArrayList<Employee>());
      ListView employeeListView = (ListView) findViewById(R.id.employees);
      employeeListView.setAdapter(empAdapter);
      getSupportLoaderManager().initLoader(1, null, this).forceLoad();
    }
    @Override 
    public Loader<List<Employee>> onCreateLoader(int id, Bundle args) {
      return new EmployeeLoader(MainActivity.this);
    }
    @Override 
    public void onLoadFinished(Loader<List<Employee>> loader, List<Employee> data) {
      empAdapter.setEmployees(data);
    }
    @Override 
    public void onLoaderReset(Loader<List<Employee>> loader) {
      empAdapter.setEmployees(new ArrayList<Employee>());
    }
} 

employeedata.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:orientation="horizontal" 
       android:background="#D1C4E9">
       <TextView
         android:id="@+id/empid"
         android:textSize="25sp"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:textColor="#FF8A80"
         android:layout_weight="2"/>
       <TextView
         android:id="@+id/empname"
         android:textSize="25sp"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:textColor="#FF8A80"
         android:layout_weight="2"/>
</LinearLayout> 

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#C98C00">
    <ListView
        android:id="@+id/employees"
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>
</LinearLayout> 

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11"/>
    <application
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity  android:name=".MainActivity" android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Output

Android AsyncTaskLoader Example with ListView and BaseAdapter

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us