Last active
November 12, 2016 23:16
-
-
Save devriesm/5534122 to your computer and use it in GitHub Desktop.
Base Android AsyncTaskLoader for list data with common functionality like paging.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.markdevries.loader; | |
import java.util.ArrayList; | |
import java.util.List; | |
import android.content.Context; | |
import android.support.v4.content.AsyncTaskLoader; | |
public class ListAsyncTaskLoader<D> extends AsyncTaskLoader<List<D>> | |
{ | |
protected List<D> mData; | |
private boolean mIsLoading = false; | |
private int mCurrentPage; | |
private int mItemsPerPage; | |
private int mTotalPages; | |
public ListAsyncTaskLoader( Context context ) | |
{ | |
super( context ); | |
init( ); | |
} | |
private void init( ) | |
{ | |
mCurrentPage = 0; | |
} | |
public int getCurrentPage( ) | |
{ | |
return mCurrentPage; | |
} | |
public void setCurrentPage( int currentPage ) | |
{ | |
mCurrentPage = currentPage; | |
} | |
public int getItemsPerPage( ) | |
{ | |
return mItemsPerPage; | |
} | |
public void setItemsPerPage( int itemsPerPage ) | |
{ | |
mItemsPerPage = itemsPerPage; | |
} | |
public int getTotalPages( ) | |
{ | |
return mTotalPages; | |
} | |
public void setTotalPage( int totalPages ) | |
{ | |
mTotalPages = totalPages; | |
} | |
@Override | |
public List<D> loadInBackground( ) | |
{ | |
mIsLoading = true; | |
return null; | |
} | |
public void deliverResult( List<D> data ) | |
{ | |
mIsLoading = false; | |
if( data != null ) | |
{ | |
if( mData == null ) | |
mData = data; | |
else | |
mData.addAll( data ); | |
} | |
super.deliverResult( ( ( mData == null ) ? null : new ArrayList<D>( mData ) ) ); | |
}; | |
@Override | |
protected void onStartLoading( ) | |
{ | |
if( mData != null ) | |
deliverResult( null ); | |
else | |
forceLoad( ); | |
} | |
@Override | |
protected void onStopLoading( ) | |
{ | |
mIsLoading = false; | |
cancelLoad( ); | |
} | |
@Override | |
protected void onReset( ) | |
{ | |
super.onReset( ); | |
onStopLoading( ); | |
mData = null; | |
} | |
public boolean getIsLoading( ) | |
{ | |
return mIsLoading; | |
} | |
public boolean getHasMoreResults( ) | |
{ | |
return( mCurrentPage <= mTotalPages ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment