com.example.droidcodin.popularmdb.MovieDetailFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.example.droidcodin.popularmdb.MovieDetailFragment.java

Source

/*
 * Copyright 2015 Archie David
 *
 * 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.example.droidcodin.popularmdb;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.droidcodin.popularmdb.constant.ProjectionConstant;
import com.example.droidcodin.popularmdb.data.MovieColumns;
import com.example.droidcodin.popularmdb.data.MovieContentProvider;
import com.example.droidcodin.popularmdb.model.Review;
import com.example.droidcodin.popularmdb.model.ReviewList;
import com.example.droidcodin.popularmdb.model.Video;
import com.example.droidcodin.popularmdb.model.VideoList;
import com.example.droidcodin.popularmdb.service.RestClient;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Archie David on 29/12/15.
 */

public class MovieDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final String LOG_TAG = MovieDetailFragment.class.getSimpleName();

    private static final String MOVIESHARE_HASHTAG = " #Popular Movies";
    private String mMovieStr;

    private String apiKey = BuildConfig.PIMDB_API_KEY;
    static final String DETAIL_URI = "URI";

    ImageButton imgViewFavButton;
    Boolean mIsFavourite = false;
    private ShareActionProvider mShareActionProvider;

    List<Review> reviewlist;
    private ArrayAdapter<String> mReviewAdapter;
    private Cursor mDetailCursor;
    private View mRootView;
    private int mPosition;
    private VideoAdapter mVideoAdapter;
    private String youTubeBaseURL = "https://www.youtube.com/watch?v=";

    private Video video;
    private Video mFirstVideo;
    private String mFirstVideoStr;

    private List<Video> listOfVideos;

    private String imageURL;
    private String mMovieID;
    private String mMovieTitle;

    private ImageView mImageview;
    private TextView mRating;
    private TextView mTitleTextView;
    private TextView mReleaseDate;
    private TextView mOverview;

    private TextView mUriText;
    private Uri mUri;
    private static final int DETAIL_LOADER_ID = 50;

    public static MovieDetailFragment newInstance(int position, Uri uri) {
        MovieDetailFragment fragment = new MovieDetailFragment();
        Bundle args = new Bundle();
        fragment.mPosition = position;
        fragment.mUri = uri;
        args.putInt("id", position);
        fragment.setArguments(args);
        return fragment;
    }

    public MovieDetailFragment() {

        setHasOptionsMenu(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate the menu; this adds items to the action bar if it is present.
        inflater.inflate(R.menu.detailfragment, menu);

        // Retrieve the share menu item
        MenuItem menuItem = menu.findItem(R.id.action_share);

        // Get the provider and hold onto it to set/change the share intent.
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);

        // Attach an intent to this ShareActionProvider.  You can update this at any time,
        // like when the user selects a new piece of data they might like to share.
        if (mMovieStr != null) {
            mShareActionProvider.setShareIntent(createMovieShareIntent());
        } else {
            Log.d(LOG_TAG, "Share Action Provider is null?");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        Bundle arguments = getArguments();
        if (arguments != null) {
            mUri = arguments.getParcelable(MovieDetailFragment.DETAIL_URI);
        }

        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.movie_fragment_detail, container, false);

        mImageview = (ImageView) rootView.findViewById(R.id.movie_detail_poster_imageview);
        mTitleTextView = (TextView) rootView.findViewById(R.id.detail_title_textview);
        mRating = (TextView) rootView.findViewById(R.id.movie_rating_textview);
        mReleaseDate = (TextView) rootView.findViewById(R.id.movie_releasedate_textview);
        mOverview = (TextView) rootView.findViewById(R.id.detail_plot_synopsis_textview);

        Bundle args = this.getArguments();

        getLoaderManager().initLoader(DETAIL_LOADER_ID, args, MovieDetailFragment.this);

        imgViewFavButton = (ImageButton) rootView.findViewById(R.id.imgFavBtn);

        imgViewFavButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mIsFavourite) {
                    removeFromFavorites(mMovieID);
                } else {
                    saveToFavorite(mMovieID);
                }

            }
        });
        return rootView;

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        if (null != mUri) {

            // May need to join Movie table with Video table to get movie and video details?

            // Now create and return a CursorLoader that will take care of
            // creating a Cursor for the data being displayed.
            return new CursorLoader(getActivity(), mUri, ProjectionConstant.DETAIL_COLUMNS, null, null, null);
        }
        return null;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    // Set the cursor in our CursorAdapter once the Cursor is loaded
    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // if (data.getCount() > 0 ){
        mDetailCursor = data;
        mDetailCursor.moveToFirst();
        DatabaseUtils.dumpCursor(data);

        mMovieID = mDetailCursor.getString(ProjectionConstant.COL_MOVIE_ID);

        // get the movie title from DB
        mMovieTitle = mDetailCursor.getString(ProjectionConstant.COL_MOVIE_TITLE);

        mTitleTextView.setText(mDetailCursor.getString(ProjectionConstant.COL_MOVIE_TITLE));
        imageURL = mDetailCursor.getString(ProjectionConstant.COL_MOVIE_POSTERPATH);

        Picasso.with(this.getActivity()).load("http://image.tmdb.org/t/p/w185/" + imageURL).into(mImageview);

        mOverview.setText(mDetailCursor.getString(ProjectionConstant.COL_MOVIE_OVERVIEW));
        mReleaseDate.setText(mDetailCursor.getString(ProjectionConstant.COL_MOVIE_RELEASEDATE).substring(0, 4));
        mRating.setText(mDetailCursor.getString(ProjectionConstant.COL_MOVIE_VOTEAVG));

        checkFavourites(mMovieID);

        fetchMovieVideos();

        fetchMovieReviews(mMovieID);

        mMovieStr = mMovieTitle + "\n" + youTubeBaseURL + mFirstVideoStr;

        // If onCreateOptionsMenu has already happened, we need to update the share intent now.
        if (mShareActionProvider != null) {
            mShareActionProvider.setShareIntent(createMovieShareIntent());
        }

    }

    // reset CursorAdapter on Loader Reset
    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mDetailCursor = null;
    }

    private void fetchMovieReviews(String movieID) {
        RestClient restclient = new RestClient();
        restclient.getApiService().getReview(movieID, apiKey, new Callback<ReviewList>() {

            @Override
            public void success(ReviewList reviewList, Response response) {
                reviewlist = reviewList.getReviews();

                //get the name of each movie in the list and add it to movies_names list
                List<String> listOfReviews = new ArrayList<>();
                for (Review review : reviewlist) {
                    listOfReviews.add(review.getContent());
                    listOfReviews.add(review.getAuthor());
                }

                mReviewAdapter = new ArrayAdapter<String>(getActivity(), // The current context (this activity)
                        R.layout.list_item_review, // The name of the layout ID.
                        R.id.list_item_review_textview, // The ID of the textview to populate.
                        listOfReviews);

                ListView listView = (ListView) getView().findViewById(R.id.listview_review);
                listView.setAdapter(mReviewAdapter);

            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(getActivity(), "Connection failed", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void fetchMovieVideos() {
        RestClient restclient = new RestClient();
        restclient.getApiService().getVideo(mMovieID, apiKey, new Callback<VideoList>() {

            @Override
            public void success(VideoList videoList, Response response) {
                listOfVideos = videoList.getResults();
                if (listOfVideos != null) {

                    Utility.storeVideoList(getActivity(), mMovieID, listOfVideos);
                }

                ListView listView = (ListView) getView().findViewById(R.id.listview_video);
                mVideoAdapter = new VideoAdapter(getActivity(), listOfVideos);
                listView.setAdapter(mVideoAdapter);

                mFirstVideoStr = listOfVideos.get(0).getKey();
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                        video = mVideoAdapter.getItem(position);
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(youTubeBaseURL + video.getKey())));
                    }
                });

            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("failure", String.valueOf(error.getCause()));
                Toast.makeText(getActivity(), "Connection failed", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void checkFavourites(String movieID) {
        // check for movies where favorite_flag = 1 and movieid = the movie ID we pass in
        Cursor c = getActivity().getContentResolver().query(MovieContentProvider.Movie.CONTENT_URI, null,
                MovieColumns.COLUMN_FAVFLAG + " = ? AND " + MovieColumns.COLUMN_MOVIEID + " = ?",
                new String[] { "1", movieID }, null);

        if (c != null) {
            c.moveToFirst();
            int index = c.getColumnIndex(MovieColumns.COLUMN_MOVIEID);
            if (c.getCount() > 0) {
                // if (c.getCount() > 0 && c.getString(index).equals(mMovieID)) {
                mIsFavourite = true;
                imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_on);
            } else {
                imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
            }
            c.close();
        }
    }

    private void removeFromFavorites(String movieID) {
        //contentvalue to insert
        ContentValues movieValues = new ContentValues();
        movieValues.put(MovieColumns.COLUMN_FAVFLAG, "0");

        //set fav flag to 0
        getActivity().getContentResolver().update(MovieContentProvider.Movie.CONTENT_URI, movieValues,
                MovieColumns.COLUMN_MOVIEID + " = ?", new String[] { movieID });

        imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
        mIsFavourite = false;
    }

    // insert data into database
    public void saveToFavorite(String movieID) {

        mIsFavourite = true;
        imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_on);
        ContentValues movieValues = new ContentValues();
        movieValues.put(MovieColumns.COLUMN_FAVFLAG, "1");

        getActivity().getContentResolver().update(MovieContentProvider.Movie.CONTENT_URI, movieValues,
                MovieColumns.COLUMN_MOVIEID + " = ?", new String[] { movieID });
    }

    //write a method for share and pass the movie ID as string?
    //when method is clicks grab the strings????
    private Intent createMovieShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, mMovieStr + MOVIESHARE_HASHTAG);
        return shareIntent;
    }
}