Skip to content

Instantly share code, notes, and snippets.

@sheerazam
Created April 11, 2016 09:21
Show Gist options
  • Save sheerazam/7a86c74e38f23f58d00ad522ee584dc5 to your computer and use it in GitHub Desktop.
Save sheerazam/7a86c74e38f23f58d00ad522ee584dc5 to your computer and use it in GitHub Desktop.
Custom Loader with Gson Network Request
public class ForSaleListLoader extends AsyncTaskLoader<List<ForSale>> {
private static final String TAG = "AppointmentListLoader";
private static final boolean DEBUG = false;
// We hold a reference to the Loaders data here.
private List<ForSale> mSales;
String select;
Uri uri;
String[] projection;
String SortOrder;
Context context;
String url;
public ForSaleListLoader(Context ctx, String url) {
super(ctx);
this.url = url;
context = ctx;
}
/****************************************************/
/** (1) A task that performs the asynchronous load **/
/****************************************************/
/**
* This method is called on a background thread and generates a List of
* {@link ForSaleListLoader} objects. Each entry corresponds to a single installed
* application on the device.
*/
@Override
public List<ForSale> loadInBackground() {
if (DEBUG) Log.i(TAG, "+++ loadInBackground() called! +++");
// List<Appointment> list = ( (SrxProvider) getContext().getContentResolver() ).getAppoinments();
List<ForSale> sales = null;
if(isNetworkAvailable()){
//TODO: do the network related work here....
// insert english
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
sales = gson.fromJson(reader, new TypeToken<List<ForSale>>(){}.getType());
}
// Sort the list.
//Collections.sort(appointments, ALPHA_COMPARATOR);
return sales;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
/*******************************************/
/** (2) Deliver the results to the client **/
/*******************************************/
/**
* Called when there is new data to deliver to the client. The superclass will
* deliver it to the registered listener (i.e. the LoaderManager), which will
* forward the results to the client through a call to onLoadFinished.
*/
@Override
public void deliverResult(List<ForSale> sales) {
if (isReset()) {
if (DEBUG) Log.w(TAG, "+++ Warning! An async query came in while the Loader was reset! +++");
// The Loader has been reset; ignore the result and invalidate the data.
// This can happen when the Loader is reset while an asynchronous query
// is working in the background. That is, when the background thread
// finishes its work and attempts to deliver the results to the client,
// it will see here that the Loader has been reset and discard any
// resources associated with the new data as necessary.
if (sales != null) {
releaseResources(sales);
return;
}
}
// Hold a reference to the old data so it doesn't get garbage collected.
// We must protect it until the new data has been delivered.
List<ForSale> oldApps = mSales;
mSales = sales;
if (isStarted()) {
if (DEBUG) Log.i(TAG, "+++ Delivering results to the LoaderManager for" +
" the ListFragment to display! +++");
// If the Loader is in a started state, have the superclass deliver the
// results to the client.
super.deliverResult(sales);
}
// Invalidate the old data as we don't need it any more.
if (oldApps != null && oldApps != sales) {
if (DEBUG) Log.i(TAG, "+++ Releasing any old data associated with this Loader. +++");
releaseResources(oldApps);
}
}
/*********************************************************/
/** (3) Implement the Loader's state-dependent behavior **/
/*********************************************************/
@Override
protected void onStartLoading() {
if (DEBUG) Log.i(TAG, "+++ onStartLoading() called! +++");
if (mSales != null) {
// Deliver any previously loaded data immediately.
if (DEBUG) Log.i(TAG, "+++ Delivering previously loaded data to the client...");
deliverResult(mSales);
}
// Register the observers that will notify the Loader when changes are made.
/* if (mAppsObserver == null) {
mAppsObserver = new InstalledAppsObserver(this);
}
if (mLocaleObserver == null) {
mLocaleObserver = new SystemLocaleObserver(this);
}*/
if (takeContentChanged()) {
// When the observer detects a new installed application, it will call
// onContentChanged() on the Loader, which will cause the next call to
// takeContentChanged() to return true. If this is ever the case (or if
// the current data is null), we force a new load.
if (DEBUG) Log.i(TAG, "+++ A content change has been detected... so force load! +++");
forceLoad();
} else if (mSales == null) {
// If the current data is null... then we should make it non-null! :)
if (DEBUG) Log.i(TAG, "+++ The current data is data is null... so force load! +++");
forceLoad();
}
}
@Override
protected void onStopLoading() {
if (DEBUG) Log.i(TAG, "+++ onStopLoading() called! +++");
// The Loader has been put in a stopped state, so we should attempt to
// cancel the current load (if there is one).
cancelLoad();
// Note that we leave the observer as is; Loaders in a stopped state
// should still monitor the data source for changes so that the Loader
// will know to force a new load if it is ever started again.
}
@Override
protected void onReset() {
if (DEBUG) Log.i(TAG, "+++ onReset() called! +++");
// Ensure the loader is stopped.
onStopLoading();
// At this point we can release the resources associated with 'apps'.
if (mSales != null) {
releaseResources(mSales);
mSales = null;
}
// The Loader is being reset, so we should stop monitoring for changes.
/* if (mAppsObserver != null) {
getContext().unregisterReceiver(mAppsObserver);
mAppsObserver = null;
}
if (mLocaleObserver != null) {
getContext().unregisterReceiver(mLocaleObserver);
mLocaleObserver = null;
}*/
}
@Override
public void onCanceled(List<ForSale> apps) {
if (DEBUG) Log.i(TAG, "+++ onCanceled() called! +++");
// Attempt to cancel the current asynchronous load.
super.onCanceled(apps);
// The load has been canceled, so we should release the resources
// associated with 'mApps'.
releaseResources(apps);
}
@Override
public void forceLoad() {
if (DEBUG) Log.i(TAG, "+++ forceLoad() called! +++");
super.forceLoad();
}
/**
* Helper method to take care of releasing resources associated with an
* actively loaded data set.
*/
private void releaseResources(List<ForSale> sales) {
// For a simple List, there is nothing to do. For something like a Cursor,
// we would close it in this method. All resources associated with the
// Loader should be released here.
}
/*********************************************************************/
/** (4) Observer which receives notifications when the data changes **/
/*********************************************************************/
/* // An observer to notify the Loader when new apps are installed/updated.
private InstalledAppsObserver mAppsObserver;
// The observer to notify the Loader when the system Locale has been changed.
private SystemLocaleObserver mLocaleObserver;
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment