com.nonobay.fana.udacityandroidproject1popularmovies.FetchMovieTask.java Source code

Java tutorial

Introduction

Here is the source code for com.nonobay.fana.udacityandroidproject1popularmovies.FetchMovieTask.java

Source

/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * 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.nonobay.fana.udacityandroidproject1popularmovies;

import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import com.nonobay.fana.udacityandroidproject1popularmovies.data.MovieContract;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;

public class FetchMovieTask extends AsyncTask<String, Void, Void> {

    private final String LOG_TAG = FetchMovieTask.class.getSimpleName();

    private final Context mContext;

    public FetchMovieTask(Context context) {
        mContext = context;
    }

    /**
     * Take the String representing the complete movies in JSON Format and
     * pull out the data we need to construct the Strings needed for the wireframes.
     * <p/>
     * Fortunately parsing is easy:  constructor takes the JSON string and converts it
     * into an Object hierarchy for us.
     */
    private void getMovieDataFromJson(String moviesJsonStr) throws JSONException {

        // Now we have a String representing the complete movie list in JSON Format.
        // Fortunately parsing is easy:  constructor takes the JSON string and converts it
        // into an Object hierarchy for us.

        /* example
        {
        "page": 1,
        "results": [
            {
                "adult": false,
                    "backdrop_path": "/razvUuLkF7CX4XsLyj02ksC0ayy.jpg",
                    "genre_ids": [
                80,
                        28,
                        53
                ],
                "id": 260346,
                    "original_language": "en",
                    "original_title": "Taken 3",
                    "overview": "Ex-government operative Bryan Mills finds his life is shattered when he's falsely accused of a murder that hits close to home. As he's pursued by a savvy police inspector, Mills employs his particular set of skills to track the real killer and exact his unique brand of justice.",
                    "release_date": "2015-01-09",
                    "poster_path": "/c2SSjUVYawDUnQ92bmTqsZsPEiB.jpg",
                    "popularity": 11.737899,
                    "title": "Taken 3",
                    "video": false,
                    "vote_average": 6.2,
                    "vote_count": 698
            }
        ],
        "total_pages": 11543,
        "total_results": 230847
        }*/

        // These are the names of the JSON objects that need to be extracted.
        final String JSON_PAGE = "page";
        final String JSON_PAGE_TOTAL = "total_pages";
        final String JSON_MOVIE_LIST = "results";
        final String JSON_MOVIE_TOTAL = "total_results";

        final String JSON_MOVIE_ID = "id";
        final String JSON_MOVIE_TITLE = "original_title";
        final String JSON_MOVIE_DATE = "release_date";
        final String JSON_MOVIE_POSTER = "poster_path";
        final String JSON_MOVIE_OVERVIEW = "overview";
        final String JSON_MOVIE_VOTE_AVERAGE = "vote_average";

        try {

            JSONObject moviesJson = new JSONObject(moviesJsonStr);

            JSONArray movieArray = moviesJson.getJSONArray(JSON_MOVIE_LIST);

            // Insert the new movie information into the database
            Vector<ContentValues> cVVector = new Vector<>(movieArray.length());

            // These are the values that will be collected.
            String releaseTime;
            long movieId;
            double vote_average;
            String overview;
            String original_title;
            String poster_path;

            for (int i = 0; i < movieArray.length(); i++) {

                // Get the JSON object representing the movie
                JSONObject eachMovie = movieArray.getJSONObject(i);

                movieId = eachMovie.getLong(JSON_MOVIE_ID);
                original_title = eachMovie.getString(JSON_MOVIE_TITLE);
                overview = eachMovie.getString(JSON_MOVIE_OVERVIEW);
                poster_path = eachMovie.getString(JSON_MOVIE_POSTER);
                vote_average = eachMovie.getDouble(JSON_MOVIE_VOTE_AVERAGE);
                releaseTime = eachMovie.getString(JSON_MOVIE_DATE);

                ContentValues movieValues = new ContentValues();
                movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_ID, movieId);
                movieValues.put(MovieContract.MovieEntry.COLUMN_ORIGINAL_TITLE, original_title);
                movieValues.put(MovieContract.MovieEntry.COLUMN_POSTER_THUMBNAIL, poster_path);
                movieValues.put(MovieContract.MovieEntry.COLUMN_SYNOPSIS, overview);
                movieValues.put(MovieContract.MovieEntry.COLUMN_RELEASE_DATE, releaseTime);
                movieValues.put(MovieContract.MovieEntry.COLUMN_USER_RATING, vote_average);

                cVVector.add(movieValues);
            }

            // add to database
            if (cVVector.size() > 0) {
                // Student: call bulkInsert to add the weatherEntries to the database here
                mContext.getContentResolver().delete(MovieContract.MovieEntry.CONTENT_URI, null, null);
                mContext.getContentResolver().bulkInsert(MovieContract.MovieEntry.CONTENT_URI,
                        cVVector.toArray(new ContentValues[cVVector.size()]));
            }

        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }

    @Override
    protected Void doInBackground(String... params) {

        // Verify size of params.
        if (params.length == 0) {
            return null;
        }

        // These two need to be declared outside the try/catch
        // so that they can be closed in the finally block.
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        try {
            // Construct the URL for the discover movie query
            // http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=[YOUR API KEY]
            final String FORECAST_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
            final String QUERY_PARAM_SORT = "sort_by";
            final String QUERY_PARAM_API_KEY = "api_key";

            Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                    .appendQueryParameter(QUERY_PARAM_SORT, params[0])
                    .appendQueryParameter(QUERY_PARAM_API_KEY, params[1]).build();

            URL url = new URL(builtUri.toString());

            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            //urlConnection.setConnectTimeout(5000);
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            String movieJsonStr = buffer.toString();
            getMovieDataFromJson(movieJsonStr);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            return null;
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, "Error closing stream", e);
                }
            }
        }
        return null;

    }

}