Java tutorial
/** * Copyright 2012 Scott Weeden-Moody * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lillicoder.newsblurry.feeds; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.util.Log; import com.lillicoder.newsblurry.R; import com.lillicoder.newsblurry.exception.ApiRequestException; import com.lillicoder.newsblurry.net.BaseTask; import com.lillicoder.newsblurry.net.OnTaskCompletedListener; /** * Task that downloads the current user's feed subscriptions. * @author lillicoder */ public class DownloadFeedsTask extends BaseTask<Void, Void, List<IFeed>> { private static final String TAG = DownloadFeedsTask.class.getSimpleName(); protected DownloadFeedsTask(Context context, OnTaskCompletedListener<List<IFeed>> listener) { super(context, listener); } @Override protected List<IFeed> doInBackground(Void... params) { try { Context context = this.getContext(); String feedsUrl = context.getString(R.string.api_feedsUrl); HttpGet feedsGet = new HttpGet(feedsUrl); // Pull entity and parse JSON response. HttpResponse httpResponse = this.executeWebRequest(feedsGet); JSONObject responseJson = this.getJsonFromResponse(httpResponse); // Save the newly fetched feeds in cache and persistent storage. FeedParser parser = new FeedParser(context); Map<Integer, Feed> feedsById = parser.parseFeedsById(responseJson); FeedCache cache = new FeedCache(); cache.updateFeeds(feedsById); FeedRepository repository = new FeedRepository(this.getContext()); repository.saveFeeds(feedsById); // Sort feeds before returning. List<IFeed> feeds = parser.parseFeeds(responseJson); Collections.sort(feeds); return feeds; } catch (ApiRequestException e) { Log.e(TAG, EXCEPTION_API_REQUEST_FAILED, e); this.setException(e); } catch (IOException e) { Log.e(TAG, EXCEPTION_FAILED_TO_PARSE_RESPONSE, e); this.setException(e); } catch (JSONException e) { Log.e(TAG, EXCEPTION_UNABLE_TO_CREATE_JSON_FROM_RESPONSE, e); this.setException(e); } return null; } }