Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replace click adapter listener with binding click handler for more clean code #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@


public final class RatingAdapter extends DataListAdapter<Rating, ItemRatingBinding> {
public RatingAdapter() {
super(item -> {
});
}

@Override
protected ItemRatingBinding createBinding(LayoutInflater inflater, ViewGroup parent) {
Expand All @@ -25,4 +21,5 @@ protected ItemRatingBinding createBinding(LayoutInflater inflater, ViewGroup par
protected void bind(ItemRatingBinding binding, Rating item) {
binding.setRate(item);
}

}
Original file line number Diff line number Diff line change
@@ -1,35 +1,33 @@
package com.google.firebase.example.fireeats.adapter;

import android.app.Activity;
import android.databinding.DataBindingUtil;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.google.firebase.example.fireeats.R;
import com.google.firebase.example.fireeats.common.DataListAdapter;
import com.google.firebase.example.fireeats.common.OnItemClickedListener;
import com.google.firebase.example.fireeats.databinding.ItemRestaurantBinding;
import com.google.firebase.example.fireeats.model.Restaurant;


public final class RestaurantAdapter extends DataListAdapter<Restaurant, ItemRestaurantBinding> {
public RestaurantAdapter(OnItemClickedListener<Restaurant> listener) {
super(listener);

private RestaurantClickHandler restaurantClickHandler;

public RestaurantAdapter(Activity activity) {
this.restaurantClickHandler = new RestaurantClickHandler(activity);
}

@Override
protected ItemRestaurantBinding createBinding(LayoutInflater inflater, ViewGroup parent) {
final ItemRestaurantBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_restaurant, parent, false);
binding.getRoot().setOnClickListener(v -> {
final Restaurant chosen = binding.getRestaurant();
if (chosen != null) {
listener.onClicked(chosen);
}
});
return binding;
return DataBindingUtil.inflate(inflater, R.layout.item_restaurant, parent, false);
}

@Override
protected void bind(ItemRestaurantBinding binding, Restaurant item) {
binding.setRestaurant(item);
binding.setRestaurantClickHandler(restaurantClickHandler);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.google.firebase.example.fireeats.adapter;

import android.app.Activity;
import android.content.Intent;

import com.google.firebase.example.fireeats.R;
import com.google.firebase.example.fireeats.model.Restaurant;
import com.google.firebase.example.fireeats.ui.detail.RestaurantDetailActivity;

/**
* Created by Ahmed Abd-Elmeged on 2/6/2018.
*/

/**
* Click handler for the restaurant click in {@link RestaurantAdapter}
*/
public class RestaurantClickHandler {

private Activity activity;

RestaurantClickHandler(Activity activity) {
this.activity = activity;
}

public void onRestaurantClicked(Restaurant restaurant) {
// Go to the details page for the selected restaurant
Intent intent = new Intent(activity, RestaurantDetailActivity.class);
intent.putExtra(RestaurantDetailActivity.KEY_RESTAURANT_ID, restaurant.id);

activity.startActivity(intent);
activity.overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.google.firebase.example.fireeats.common;

import android.annotation.SuppressLint;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProvider;
import android.arch.lifecycle.ViewModelProviders;
Expand All @@ -13,8 +12,7 @@
* This Activity is to be inherited by any activity to initiate the injection.
*/

@SuppressLint("Registered")
public class BaseActivity extends DaggerAppCompatActivity {
public abstract class BaseActivity extends DaggerAppCompatActivity {

@Inject
public ViewModelProvider.Factory viewModelFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,12 @@
public abstract class DataListAdapter<T, V extends ViewDataBinding>
extends RecyclerView.Adapter<DataViewHolder<V>> {

protected final OnItemClickedListener<T> listener;
@Nullable
private List<T> items;
// each time data is set, we update this variable so that if DiffUtil calculation returns
// after repetitive updates, we can ignore the old calculation
private int dataVersion = 0;

public DataListAdapter(final OnItemClickedListener<T> listener) {
this.listener = Objects.requireNonNull(listener, "listener cannot be null");
}

@Override
public final DataViewHolder<V> onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
Expand Down Expand Up @@ -120,7 +115,6 @@ protected boolean areContentsTheSame(T oldItem, T newItem) {
return Objects.equals(oldItem, newItem);
}


@Override
public int getItemCount() {
return items == null ? 0 : items.size();
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public final class MainRepository {
private final FirebaseFirestore firestore;

@Inject
public MainRepository(FirebaseFirestore store) {
MainRepository(FirebaseFirestore store) {
this.firestore = store;
}

Expand Down Expand Up @@ -90,12 +90,13 @@ public void addRestaurants(final Context context) {
if (task.isSuccessful()) {
Timber.d("Write batch succeeded.");
} else {
Timber.w("write batch failed.", task.getException());
Timber.w(task.getException(), "write batch failed.");
}
});
}

public void deleteAll() {
RestaurantUtil.deleteAll(firestore.collection("restaurants"));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public final class RestaurantRepository {
private final CollectionReference restaurants;

@Inject
public RestaurantRepository(@Named("restaurants") CollectionReference restaurants) {
RestaurantRepository(@Named("restaurants") CollectionReference restaurants) {
this.restaurants = restaurants;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
Expand Down Expand Up @@ -34,7 +35,7 @@ public interface RatingDialogHandler {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.dialog_rating, container, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
Expand Down Expand Up @@ -36,7 +37,7 @@ public interface FiltersDialogHandler {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.dialog_filters, container, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
import com.google.firebase.example.fireeats.adapter.RestaurantAdapter;
import com.google.firebase.example.fireeats.common.BaseActivity;
import com.google.firebase.example.fireeats.databinding.ActivityMainBinding;
import com.google.firebase.example.fireeats.model.Restaurant;
import com.google.firebase.example.fireeats.repo.MainRepository;
import com.google.firebase.example.fireeats.ui.detail.RestaurantDetailActivity;

import java.util.Collections;

Expand Down Expand Up @@ -52,7 +50,7 @@ protected void onCreate(Bundle savedInstanceState) {
viewModel.isSignedIn().observe(this, isSigned -> {
// Start sign in if necessary
//noinspection ConstantConditions
if (! isSigned) startSignIn();
if (!isSigned) startSignIn();
});

viewModel.restaurants().observe(this, listResource -> {
Expand All @@ -66,7 +64,7 @@ protected void onCreate(Bundle savedInstanceState) {
}

private void initRecycler() {
adapter = new RestaurantAdapter(this::onRestaurantSelected);
adapter = new RestaurantAdapter(this);
binding.recycler.setLayoutManager(new LinearLayoutManager(this));
binding.recycler.setAdapter(adapter);

Expand Down Expand Up @@ -108,15 +106,6 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
}

public void onRestaurantSelected(Restaurant restaurant) {
// Go to the details page for the selected restaurant
Intent intent = new Intent(this, RestaurantDetailActivity.class);
intent.putExtra(RestaurantDetailActivity.KEY_RESTAURANT_ID, restaurant.id);

startActivity(intent);
overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
}

@Override
public void onFilter(Filters filters) {
// Set header
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ LiveData<Resource<List<Restaurant>>> restaurants() {
return restaurants;
}

public MainRepository getRepository() {
MainRepository getRepository() {
return repository;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
*/
public class RestaurantUtil {

private static final String TAG = "RestaurantUtil";

private static final ThreadPoolExecutor EXECUTOR =
new ThreadPoolExecutor(2, 4, 60,
TimeUnit.SECONDS, new LinkedBlockingQueue<>());
Expand Down
23 changes: 19 additions & 4 deletions app/src/main/res/layout/item_restaurant.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,23 @@
name="restaurant"
type="com.google.firebase.example.fireeats.model.Restaurant" />

<variable
name="restaurantClickHandler"
type="com.google.firebase.example.fireeats.adapter.RestaurantClickHandler" />

</data>

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:onClick="@{(view)-> restaurantClickHandler.onRestaurantClicked(restaurant)}"
android:orientation="vertical"
android:padding="8dp">

<ImageView
imageUrl="@{restaurant.photo}"
android:id="@+id/restaurant_item_image"
imageUrl="@{restaurant.photo}"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#757575"
Expand All @@ -36,21 +41,25 @@
android:layout_alignTop="@+id/restaurant_item_image"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="-2dp"
android:layout_toEndOf="@+id/restaurant_item_image"
android:layout_toLeftOf="@+id/restaurant_item_price"
android:layout_toRightOf="@+id/restaurant_item_image"
android:layout_toStartOf="@+id/restaurant_item_price"
android:ellipsize="end"
android:maxLines="1"
android:text="@{restaurant.name}"

tools:text="Foo's Bar" />

<me.zhanghai.android.materialratingbar.MaterialRatingBar
android:id="@+id/restaurant_item_rating"
style="@style/Widget.MaterialRatingBar.RatingBar.Indicator.Small"
setRating="@{restaurant.avgRating}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
setRating="@{restaurant.avgRating}"
android:layout_alignLeft="@+id/restaurant_item_name"
android:layout_alignStart="@+id/restaurant_item_name"
android:layout_below="@+id/restaurant_item_name"
android:layout_marginBottom="4dp" />

Expand All @@ -62,6 +71,8 @@
android:layout_alignBottom="@+id/restaurant_item_rating"
android:layout_alignTop="@+id/restaurant_item_rating"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:layout_toEndOf="@+id/restaurant_item_rating"
android:layout_toRightOf="@+id/restaurant_item_rating"
android:gravity="center_vertical"
android:text="@{@string/fmt_num_ratings(restaurant.numRatings)}"
Expand All @@ -74,6 +85,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/restaurant_item_name"
android:layout_alignStart="@+id/restaurant_item_name"
android:layout_below="@+id/restaurant_item_rating"
android:text="@{restaurant.category}"
android:textColor="@color/greySecondary"
Expand All @@ -83,17 +95,19 @@
android:id="@+id/restaurant_item_city_divider"
style="@style/AppTheme.TextDivider"
android:layout_alignTop="@+id/restaurant_item_category"
android:layout_toEndOf="@+id/restaurant_item_category"
android:layout_toRightOf="@+id/restaurant_item_category"
android:text="@string/divider_bullet" />

<TextView
android:id="@+id/restaurant_item_city"
style="@style/AppTheme.Body1"
android:layout_width="wrap_content"
android:text="@{restaurant.city}"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/restaurant_item_category"
android:layout_toEndOf="@+id/restaurant_item_city_divider"
android:layout_toRightOf="@+id/restaurant_item_city_divider"
android:text="@{restaurant.city}"
android:textColor="@color/greySecondary"
tools:text="San Francisco" />

Expand All @@ -102,6 +116,7 @@
style="@style/AppTheme.Caption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="@{RestaurantUtil.getPriceString(restaurant)}"
android:textColor="@color/greySecondary"
Expand Down