Skip to content

Instantly share code, notes, and snippets.

@enginebai
Last active December 12, 2015 22:42
Show Gist options
  • Save enginebai/9f602d2d1c1fc4f4491c to your computer and use it in GitHub Desktop.
Save enginebai/9f602d2d1c1fc4f4491c to your computer and use it in GitHub Desktop.
public class MovieListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<MovieListItem> mMovieList = new ArrayList<>();
private Context mContext;
private boolean mShowBomberCount;
public MovieListAdapter(Context context, List<MovieListItem> mMovieList, boolean showBomberCount) {
this.mContext = context;
this.mMovieList = mMovieList;
this.mShowBomberCount = showBomberCount;
}
public List<MovieListItem> getMovieList() {
return mMovieList;
}
public void setMovieList(List<MovieListItem> mMovieList) {
this.mMovieList = mMovieList;
}
@Override
public int getItemViewType(int position) {
return R.layout.card_movie_list;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MovieListItemHolder(LayoutInflater.from(parent.getContext())
.inflate(viewType, parent, false), this.mShowBomberCount);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
MovieListItemHolder holder = (MovieListItemHolder)viewHolder;
final MovieListItem movieItem = this.mMovieList.get(p);
holder.mTextMovieName.setText(movieItem.getTitleChinese());
String thumbnailPath = movieItem.getThumbnailPath();
holder.mImageMovieCover.setImageResource(R.drawable.img_empty);
if (!thumbnailPath.isEmpty())
Picasso.with(holder.mImagePoster.getContext())
.load(MainActivity.getResizePhoto(this.mContext, thumbnailPath))
.error(R.drawable.img_empty)
.into(holder.mImagePoster);
if (movieItem.getPhotoLists().size() > 0) {
String coverUrl = movieItem.getPhotoLists().get(
(int) (Math.random() * movieItem.getPhotoLists().size())).getPath();
Picasso.with(holder.mImageMovieCover.getContext())
.load(MainActivity.getResizePhoto(this.mContext, coverUrl))
.error(R.drawable.img_empty)
.into(holder.mImageMovieCover);
}
holder.mTextDuration.setText(this.mContext.getResources().getString(R.string.text_duration)
+ ": " + movieItem.getDuration());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN);
holder.mTextReleaseDate.setText(this.mContext.getResources().getString(R.string.text_release_date)
+ ": " + dateFormat.format(movieItem.getReleaseDate()));
holder.mRipple.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMovieDetail(movieItem.getId(), movieItem.getTitleChinese());
}
});
holder.mButtonOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMovieDetail(movieItem.getId(), movieItem.getTitleChinese());
}
});
holder.mTextGoodBomber.setText(String.valueOf(movieItem.getGoodBomber()));
holder.mTextNormalBomber.setText(String.valueOf(movieItem.getNormalBomber()));
holder.mTextBadBomber.setText(String.valueOf(movieItem.getBadBomber()));
holder.mProgressGoodBomber.setProgress((int) (movieItem.getGoodRate() * 100));
holder.mProgressNormalBomber.setProgress((int) (movieItem.getNormalRate() * 100));
holder.mProgressBadBomber.setProgress((int) (movieItem.getBadRate() * 100));
}
private void showMovieDetail(int id, String name) {
GAApplication.getTracker(mContext).send(new HitBuilders.AppViewBuilder()
.build());
Intent movieDetail = new Intent(mContext, MovieDetailActivity.class);
movieDetail.putExtra(MovieDetailActivity.EXTRA_MOVIE_ID, id);
movieDetail.putExtra(MovieDetailActivity.EXTRA_MOVIE_NAME, name);
Activity activity = (Activity) mContext;
activity.startActivity(movieDetail);
activity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
@Override
public int getItemCount() {
return this.mMovieList.size();
}
class MovieListItemHolder extends RecyclerView.ViewHolder {
@InjectView(R.id.card_movie_list_item)
CardView mCardMovie;
@InjectView(R.id.ripple)
MaterialRippleLayout mRipple;
@InjectView(R.id.layout_bomber_count)
View mLayoutBomberCount;
@InjectView(R.id.image_movie_cover)
ImageView mImageMovieCover;
@InjectView(R.id.image_movie_poster)
ImageView mImagePoster;
@InjectView(R.id.text_movie_name)
TextView mTextMovieName;
@InjectView(R.id.text_release_date)
TextView mTextReleaseDate;
@InjectView(R.id.text_duration)
TextView mTextDuration;
@InjectView(R.id.text_good_bomber)
TextView mTextGoodBomber;
@InjectView(R.id.progress_good_bomber)
ArcProgress mProgressGoodBomber;
@InjectView(R.id.text_normal_bomber)
TextView mTextNormalBomber;
@InjectView(R.id.progress_normal_bomber)
ArcProgress mProgressNormalBomber;
@InjectView(R.id.text_bad_bomber)
TextView mTextBadBomber;
@InjectView(R.id.progress_bad_bomber)
ArcProgress mProgressBadBomber;
@InjectView(R.id.button_order)
Button mButtonOrder;
MovieListItemHolder(View itemView, boolean showBomberCount) {
super(itemView);
ButterKnife.inject(this, itemView);
if (showBomberCount)
this.mLayoutBomberCount.setVisibility(View.VISIBLE);
else
this.mLayoutBomberCount.setVisibility(View.GONE);
}
}
}
public class MovieListFragment extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_TAB_POSITION = "TAB_POSITION";
@InjectView(R.id.list_movie)
SuperRecyclerView mListMovie;
private MovieListAdapter mAdapter;
private int mCurrentTab = 0;
private int mCurrentPage = 1;
private boolean mLoadingMore = false;
private boolean mShouldLoadMore = false;
public static MovieListFragment newInstance(int currentTabPosition) {
MovieListFragment fragment = new MovieListFragment();
Bundle args = new Bundle();
args.putInt(ARG_TAB_POSITION, currentTabPosition);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.mCurrentTab = getArguments().getInt(ARG_TAB_POSITION);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movie_list, container, false);
this.initView(rootView);
this.loadMovieList();
return rootView;
}
private void initView(View rootView) {
ButterKnife.inject(this, rootView);
this.mListMovie.getSwipeToRefresh().setColorSchemeResources(
R.color.primary,
R.color.accent,
android.R.color.holo_orange_dark);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
this.mListMovie.setLayoutManager(layoutManager);
this.mListMovie.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (mAdapter != null)
mAdapter.getMovieList().clear();
mCurrentPage = 1;
loadMovieList();
}
});
this.mListMovie.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (mShouldLoadMore && newState == RecyclerView.SCROLL_STATE_IDLE && !mLoadingMore) {
mListMovie.showMoreProgress();
loadMovieList();
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
mShouldLoadMore = (firstVisibleItem + visibleItemCount == totalItemCount);
}
});
}
private void loadMovieList() {
AsyncHttpClient httpClient = new AsyncHttpClient();
String url = formatMovieListRequest();
Logger.d(ApiTask.API_LOG_TAG, url);
httpClient.get(url, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Logger.json(ApiTask.API_LOG_TAG, response.toString());
List<MovieListItem> movieList = new ArrayList<>();
Gson gson = new Gson();
if (mAdapter == null) {
mAdapter = new MovieListAdapter(new ArrayList<MovieListItem>());
mListMovie.setAdapter(mAdapter);
}
mListMovie.getSwipeToRefresh().setRefreshing(false);
mListMovie.hideMoreProgress();
try {
JSONArray objects = response.getJSONArray(ApiTask.RESPONSE_OBJECTS);
if (objects.length() > 0) {
for (int i = 0; i < objects.length(); i++)
movieList.add(gson.fromJson(objects.getJSONObject(i).toString(), MovieListItem.class));
mAdapter.getMovieList().addAll(movieList);
} else {
if (mAdapter.getMovieList().size() <= 0)
Toast.makeText(getActivity(), getResources().getString(R.string.warn_no_movies),
Toast.LENGTH_SHORT).show();
else
Toast.makeText(getActivity(), getResources().getString(R.string.warn_no_more_movies),
Toast.LENGTH_SHORT).show();
return;
}
}
catch (JSONException e) {
this.onFailure(statusCode, headers, e, response);
}
mAdapter.notifyDataSetChanged();
mCurrentPage++;
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Logger.e((Exception)throwable);
mListMovie.getSwipeToRefresh().setRefreshing(false);
mListMovie.hideMoreProgress();
}
});
}
private String formatMovieListRequest() {
JSONObject q = new JSONObject();
try {
JSONArray filters = new JSONArray();
JSONObject filter = new JSONObject();
filter.put(Query.PARAM_NAME, Query.FIELD_RELEASE_STATUS);
filter.put(Query.PARAM_OP, Query.OPERATOR_EQUAL);
filter.put(Query.PARAM_VAL, MovieListTab.values()[this.mCurrentTab]);
filters.put(filter);
JSONArray orderBy = new JSONArray();
JSONObject dateSort = new JSONObject();
dateSort.put(Query.PARAM_FIELD, Query.FIELD_RELEASE_DATE);
dateSort.put(Query.PARAM_DIRECTION, Query.OPERATOR_DESC);
orderBy.put(dateSort);
q.put(Query.PARAM_FILTERS, filters);
q.put(Query.PARAM_ORDER_BY, orderBy);
}
catch (JSONException e) {
e.printStackTrace();
}
Resources res = this.getActivity().getResources();
try {
return String.format("%s%s%s?q=%s&%s=%d", res.getString(R.string.host),
res.getString(R.string.api_root), res.getString(R.string.api_movie_list),
URLEncoder.encode(q.toString(), "UTF8"),
Query.PARAM_PAGE, this.mCurrentPage);
}
catch (UnsupportedEncodingException e) {
return "";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment