This commit is contained in:
danijoo
2015-10-28 23:44:03 +01:00
commit c1580748d0
38 changed files with 922 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
package net.headlezz.udacityproject1;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.headlezz.udacityproject1" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,25 @@
package net.headlezz.udacityproject1;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle(getString(R.string.app_name));
if(savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentHolder, new MovieListFragment())
.commit();
}
}
}

View File

@@ -0,0 +1,67 @@
package net.headlezz.udacityproject1;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import net.headlezz.udacityproject1.tmdbapi.Movie;
import net.headlezz.udacityproject1.tmdbapi.TMDBApi;
import java.util.List;
public class MovieListAdapter extends RecyclerView.Adapter<MovieListAdapter.MovieViewHolder>{
Context context;
List<Movie> mMovies;
public MovieListAdapter(Context context, List<Movie> movies) {
this.context = context;
mMovies = movies;
}
@Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View movieView = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
return new MovieViewHolder(movieView);
}
@Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
holder.setMovie(mMovies.get(position));
}
@Override
public int getItemCount() {
return mMovies.size();
}
/**
* Viewholder for the movie items
*/
class MovieViewHolder extends RecyclerView.ViewHolder {
ImageView ivPoster;
Movie movie;
public MovieViewHolder(View itemView) {
super(itemView);
ivPoster = (ImageView) itemView;
ivPoster.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), movie.getTitle() + " clicked.", Toast.LENGTH_SHORT).show();
}
});
}
public void setMovie(Movie movie) {
this.movie = movie;
TMDBApi.loadPoster(ivPoster, movie);
}
}
}

View File

@@ -0,0 +1,141 @@
package net.headlezz.udacityproject1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
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.Toast;
import net.headlezz.udacityproject1.tmdbapi.Movie;
import net.headlezz.udacityproject1.tmdbapi.MovieList;
import net.headlezz.udacityproject1.tmdbapi.MovieListCallback;
import net.headlezz.udacityproject1.tmdbapi.TMDBApi;
import java.util.List;
import retrofit.Call;
/**
* A fragment showing a list of movies
*/
public class MovieListFragment extends Fragment {
// TODO fix restore
public static final String TAG = MovieListFragment.class.getSimpleName();
/**
* The number of columns our movie grid shows
*/
private static final int NUM_COLUMNS = 2;
/**
* The currently selected sorting order of the list
* @see TMDBApi
*/
private int mSortingOrder = TMDBApi.SORT_ORDER_MOST_POPULAR;
RecyclerView mMovieGridView;
/**
* Holding a reference to running api calls. This makes it possible to cancel them if
* the user leaves the app, resorts the list or opens the detail view.
*/
Call<MovieList> mMovieListCall;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_movie_list, container, false);
mMovieGridView = (RecyclerView) view.findViewById(R.id.movie_list_grid);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mMovieGridView.setLayoutManager(new GridLayoutManager(getActivity(), NUM_COLUMNS));
}
@Override
public void onStart() {
super.onStart();
loadMovieList();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.movie_list_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sort_popularity:
mSortingOrder = TMDBApi.SORT_ORDER_MOST_POPULAR;
loadMovieList();
return true;
case R.id.action_sort_rating:
mSortingOrder = TMDBApi.SORT_ORDER_HIGHEST_RATED;
loadMovieList();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Loads a list of movies into the movie grid.
* mSortingOrder will be used to determine the sorting
*/
private void loadMovieList() {
stopLoadingMovies(); // stop any running query before starting a new one
MovieListCallback cb = new MovieListCallback() {
@Override
protected void onResponse(MovieList movies) {
setListToGrid(movies.getList());
}
@Override
public void onFailure(Throwable t) {
Log.d(TAG, t.getMessage());
Toast.makeText(getActivity(), "Somethig went wrong", Toast.LENGTH_SHORT).show();
}
};
mMovieListCall = TMDBApi.discoverMovies(mSortingOrder, getString(R.string.api_key));
mMovieListCall.enqueue(cb);
}
private void setListToGrid(List<Movie> movies) {
mMovieGridView.setAdapter(new MovieListAdapter(getActivity(), movies));
}
/**
* Stops the current api query
*/
private void stopLoadingMovies() {
if(mMovieListCall != null) {
mMovieListCall.cancel();
mMovieListCall = null;
}
}
@Override
public void onStop() {
super.onStop();
stopLoadingMovies();
}
}

View File

@@ -0,0 +1,29 @@
package net.headlezz.udacityproject1.tmdbapi;
/**
* Data object to represent a single movie
* Only required data from the api is stored to save memory
*/
public class Movie {
String title;
String posterPath;
String overview;
double avRating;
public String getTitle() {
return title;
}
public String getPosterPath() {
return posterPath;
}
public String getOverview() {
return overview;
}
public double getAvRating() {
return avRating;
}
}

View File

@@ -0,0 +1,15 @@
package net.headlezz.udacityproject1.tmdbapi;
import java.util.List;
public class MovieList {
public MovieList(List<Movie> movieList) {
this.movies = movieList;
}
List<Movie> movies;
public List<Movie> getList() { return movies; }
}

View File

@@ -0,0 +1,24 @@
package net.headlezz.udacityproject1.tmdbapi;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public abstract class MovieListCallback implements Callback<MovieList> {
@Override
public void onResponse(Response<MovieList> response, Retrofit retrofit) {
if(response.isSuccess())
onResponse(response.body());
else
onFailure(new MovieDownloadException("Something went wrong" + response.code())); // TODO make this better
}
protected abstract void onResponse(MovieList movies);
public static class MovieDownloadException extends Exception {
public MovieDownloadException(String detailMessage) {
super(detailMessage);
}
}
}

View File

@@ -0,0 +1,36 @@
package net.headlezz.udacityproject1.tmdbapi;
import android.util.Log;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class MovieListDeserializer implements JsonDeserializer<MovieList> {
@Override
public MovieList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<Movie> movieList = new ArrayList<>();
for(JsonElement elem : json.getAsJsonObject().getAsJsonArray("results")) {
try { // TODO fix this and remove try/catch
JsonObject jsonObj = elem.getAsJsonObject();
Movie m = new Movie();
m.title = jsonObj.get("title").getAsString();
m.overview = jsonObj.get("overview").getAsString();
m.avRating = jsonObj.get("vote_average").getAsDouble();
JsonElement posterPath = jsonObj.get("poster_path");
m.posterPath = posterPath.getAsString();
movieList.add(m);
} catch (Exception e) {
Log.e(MovieListDeserializer.class.getSimpleName(), e.toString());
}
}
return new MovieList(movieList);
}
}

View File

@@ -0,0 +1,73 @@
package net.headlezz.udacityproject1.tmdbapi;
import android.widget.ImageView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.picasso.Picasso;
import retrofit.Call;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.http.GET;
import retrofit.http.Headers;
import retrofit.http.Query;
/**
* This class provides all the methods to interact with the tmdb api
* Methods are all static and the underlying retrofit service will be reused.
*/
public class TMDBApi {
private static final String BASE_URL = "http://api.themoviedb.org/3/";
private static final String IMAGE_BASE_URL = "http://image.tmdb.org/t/p/w342"; // TODO select size depending on device screen ratios
/**
* These are the possible sorting orders
*/
public static final int SORT_ORDER_MOST_POPULAR = 1;
public static final int SORT_ORDER_HIGHEST_RATED = 2;
private static TMDBApi.TMDBApiService apiService = buildApiService();
/**
* The initialization steps for the retrofit api
* @return TMDBApiService service to make api calls
*/
private static TMDBApiService buildApiService() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(MovieList.class, new MovieListDeserializer())
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
return retrofit.create(TMDBApiService.class);
}
public static void loadPoster(ImageView imageView, Movie movie) {
Picasso.with(imageView.getContext()).load(IMAGE_BASE_URL + movie.getPosterPath()).into(imageView);
}
public static Call<MovieList> discoverMovies(int sortOrder, String apiKey) {
String sort;
switch (sortOrder) {
case SORT_ORDER_MOST_POPULAR:
sort = "popularity.desc";
break;
default:
sort = "vote_average.desc";
}
return apiService.discoverMovies(sort, apiKey);
}
/**
* Api interface for retrofit
*/
public interface TMDBApiService {
@Headers("Accept: application/json")
@GET("discover/movie")
Call<MovieList> discoverMovies(@Query("sort_by") String sortOrder, @Query("api_key") String apiKey);
}
}

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<android.support.v7.widget.Toolbar android:id="@+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />
<FrameLayout
android:id="@+id/fragmentHolder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

View File

@@ -0,0 +1,13 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="@layout/activity_main"
tools:context=".MainActivityFragment">
<android.support.v7.widget.RecyclerView
android:id="@+id/movie_list_grid"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"/>

View File

@@ -0,0 +1,6 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item android:id="@+id/action_sort_popularity" android:title="Sort by popularity" app:showAsAction="never" />
<item android:id="@+id/action_sort_rating" android:title="Sort by av. rating" app:showAsAction="never" />
</menu>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -0,0 +1,7 @@
<resources>>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
</style>
</resources>

View File

@@ -0,0 +1,6 @@
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="api_key"></string>
</resources>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>

View File

@@ -0,0 +1,6 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="fab_margin">16dp</dimen>
</resources>

View File

@@ -0,0 +1,4 @@
<resources>
<string name="app_name">UdacityProject1</string>
<string name="action_settings">Settings</string>
</resources>

View File

@@ -0,0 +1,17 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>

View File

@@ -0,0 +1,15 @@
package net.headlezz.udacityproject1;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}