Skip to content

Instantly share code, notes, and snippets.

@inan-mahmud
Last active October 13, 2019 09:33
Show Gist options
  • Save inan-mahmud/09bbf4fd7f8ddf551372441361afbe7d to your computer and use it in GitHub Desktop.
Save inan-mahmud/09bbf4fd7f8ddf551372441361afbe7d to your computer and use it in GitHub Desktop.
package com.unitor.foodhub.paging.daily;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.paging.PageKeyedDataSource;
import com.unitor.foodhub.data.Resource;
import com.unitor.foodhub.data.rest.ApiClient;
import com.unitor.foodhub.data.rest.ApiInterface;
import com.unitor.foodhub.pojos.event.EventResult;
import com.unitor.foodhub.pojos.event.EventsItem;
import java.io.IOException;
import java.util.List;
import retrofit2.Response;
/**
* Created by Inan Mahmud on 02/10/2019.
*/
public class EventDataSource extends PageKeyedDataSource<Integer, EventsItem> {
private String date;
private int sourceIndex = 0;
private Context context;
private ApiInterface apiInterface;
private MutableLiveData<Resource> liveData = new MutableLiveData<>();
private MutableLiveData<List<EventsItem>> itemMutableLiveData = new MutableLiveData<>();
public EventDataSource(Context context, String date) {
this.date = date;
this.context = context;
apiInterface = ApiClient.getClient(context).create(ApiInterface.class);
}
@Override
public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, EventsItem> callback) {
try {
Response<EventResult> response = apiInterface.getEventsData(date, sourceIndex).execute();
if (response.body().getEvents() != null) {
liveData.postValue(Resource.success(response));
itemMutableLiveData.postValue(response.body().getEvents());
callback.onResult(response.body().getEvents(), null, sourceIndex + 1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, EventsItem> callback) {
try {
Response<EventResult> response = apiInterface.getEventsData(date, params.key).execute();
if (response.body().getEvents() != null) {
liveData.postValue(Resource.success(response));
itemMutableLiveData.postValue(response.body().getEvents());
callback.onResult(response.body().getEvents(), params.key - 1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void loadAfter(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, EventsItem> callback) {
try {
Response<EventResult> response = apiInterface.getEventsData(date, params.key).execute();
if (response.body().getEvents() != null) {
liveData.postValue(Resource.success(response));
itemMutableLiveData.postValue(response.body().getEvents());
callback.onResult(response.body().getEvents(), params.key + 1);
}
} catch (Exception e) {
Log.d("EventDataSource", e.getMessage());
}
}
public MutableLiveData<Resource> getResourceLiveData() {
return liveData;
}
public void updateDate(String date) {
this.date = date;
}
}
package com.unitor.foodhub.paging.daily;
import android.content.Context;
import androidx.lifecycle.MutableLiveData;
import androidx.paging.DataSource;
import androidx.paging.PageKeyedDataSource;
import com.unitor.foodhub.data.Resource;
import com.unitor.foodhub.pojos.event.EventsItem;
/**
* Created by Inan Mahmud on 02/10/2019.
*/
public class EventDataSourceFactory extends DataSource.Factory {
private MutableLiveData<PageKeyedDataSource<Integer, EventsItem>> itemLiveDataSource = new MutableLiveData<>();
private Context context;
private EventDataSource eventDataSource;
private String date;
public EventDataSourceFactory(Context context, String date) {
this.context = context;
this.date = date;
}
@Override
public DataSource create() {
eventDataSource = new EventDataSource(context, date);
itemLiveDataSource.postValue(eventDataSource);
return eventDataSource;
}
public MutableLiveData<PageKeyedDataSource<Integer, EventsItem>> getItemLiveDataSource() {
return itemLiveDataSource;
}
public MutableLiveData<Resource> getLiveData() {
return eventDataSource.getResourceLiveData();
}
public void updateDate(String date) {
eventDataSource.updateDate(date);
}
}
package com.unitor.foodhub.viewmodel;
import android.content.Context;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PageKeyedDataSource;
import androidx.paging.PagedList;
import com.unitor.foodhub.base.BaseViewModel;
import com.unitor.foodhub.paging.daily.EventDataSourceFactory;
import com.unitor.foodhub.paging.monthly.MonthlyEventDataSourceFactory;
import com.unitor.foodhub.pojos.event.EventsItem;
/**
* Created by Inan Mahmud on 02/10/2019.
*/
public class EventViewModel extends BaseViewModel {
public LiveData<PageKeyedDataSource<Integer, EventsItem>> liveDataSource;
public LiveData<PagedList<EventsItem>> itemPagedList;
public LiveData<PageKeyedDataSource<Integer, EventsItem>> monthlyLiveDataSource;
public LiveData<PagedList<EventsItem>> monthlyItemPagedList;
public MutableLiveData<String> dateLiveData = new MutableLiveData<>();
public EventDataSourceFactory dataSourceFactory;
public EventViewModel(Context context, String date) {
dataSourceFactory = new EventDataSourceFactory(context, date);
liveDataSource = dataSourceFactory.getItemLiveDataSource();
MonthlyEventDataSourceFactory monthlyEventDataSourceFactory = new MonthlyEventDataSourceFactory(context, date);
monthlyLiveDataSource = monthlyEventDataSourceFactory.getItemLiveDataSource();
PagedList.Config config = new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(10)
.build();
itemPagedList = new LivePagedListBuilder(dataSourceFactory, config).build();
monthlyItemPagedList = new LivePagedListBuilder(monthlyEventDataSourceFactory, config).build();
}
public void updateDate(String date){
dataSourceFactory.updateDate(date);
}
public LiveData<PagedList<EventsItem>> getItemPagedList() {
return itemPagedList;
}
public void triggerPrefsChenged(String date) {
dateLiveData.setValue(date);
}
}
package com.unitor.foodhub.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.unitor.foodhub.R;
import com.unitor.foodhub.adapters.EventListAdapter;
import com.unitor.foodhub.adapters.MonthlyAdapter;
import com.unitor.foodhub.application.FoodHubApplication;
import com.unitor.foodhub.base.BaseFragment;
import com.unitor.foodhub.databinding.FragmentHomeBinding;
import com.unitor.foodhub.pojos.Event;
import com.unitor.foodhub.pojos.event.EventsItem;
import com.unitor.foodhub.viewmodel.EventViewModel;
import com.unitor.foodhub.viewmodel.EventViewModelFactory;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends BaseFragment {
private FragmentHomeBinding binding;
private Calendar mCalender;
private SimpleDateFormat mDateFormat;
private SimpleDateFormat dateFormatForMonth = new SimpleDateFormat("MMMM yyyy", Locale.getDefault());
private List<Event> events = new ArrayList<>();
private EventListAdapter adapter;
private EventViewModel viewModel;
private MonthlyAdapter monthlyAdapter;
public HomeFragment() {
}
public static HomeFragment newInstance() {
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = provideMyFragment(inflater, container, savedInstanceState);
return view;
}
@Override
public View provideMyFragment(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, parent, false);
mDateFormat = new SimpleDateFormat("dd MMMM yyyy");
Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c);
viewModel = ViewModelProviders.of(this, new EventViewModelFactory(formattedDate, FoodHubApplication.getInstance())).get(EventViewModel.class);
mCalender = Calendar.getInstance();
binding.monthName.setText(dateFormatForMonth.format(binding.compactcalendarView.getFirstDayOfCurrentMonth()));
binding.nextBtn.setOnClickListener(view -> binding.compactcalendarView.scrollRight());
binding.backBtn.setOnClickListener(view -> binding.compactcalendarView.scrollLeft());
binding.compactcalendarView.setFirstDayOfWeek(Calendar.SUNDAY);
binding.compactcalendarView.setLocale(TimeZone.getTimeZone("EST"), Locale.US);
binding.compactcalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener() {
@Override
public void onDayClick(Date dateClicked) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(dateClicked);
viewModel.updateDate(formattedDate);
observeViewModel();
}
@Override
public void onMonthScroll(Date firstDayOfNewMonth) {
binding.monthName.setText(dateFormatForMonth.format(firstDayOfNewMonth));
}
});
iniViews();
return binding.getRoot();
}
private void iniViews() {
binding.todayEventBtn.setOnClickListener(view -> {
binding.group.setVisibility(View.VISIBLE);
binding.monthlyEventCard.setVisibility(View.GONE);
toggleBackground(binding.todayEventBtn, binding.monthlyeEventBtn);
});
binding.monthlyeEventBtn.setOnClickListener(view -> {
binding.group.setVisibility(View.GONE);
binding.monthlyEventCard.setVisibility(View.VISIBLE);
toggleBackground(binding.monthlyeEventBtn, binding.todayEventBtn);
});
binding.upcomingEventListView.setFocusable(false);
binding.monthlyEventListView.setFocusable(false);
binding.upcomingEventListView.setLayoutManager(new LinearLayoutManager(getContext()));
binding.monthlyEventListView.setLayoutManager(new LinearLayoutManager(getContext()));
init();
}
private void toggleBackground(Button btn1, Button btn2) {
btn1.setBackgroundColor(ContextCompat.getColor(FoodHubApplication.getInstance(), R.color.food_hub_color));
btn1.setTextColor(ContextCompat.getColor(FoodHubApplication.getInstance(), R.color.white));
btn2.setTextColor(ContextCompat.getColor(FoodHubApplication.getInstance(), R.color.black));
btn2.setBackgroundColor(ContextCompat.getColor(FoodHubApplication.getInstance(), R.color.white));
}
private void init() {
try {
adapter = new EventListAdapter(getContext());
monthlyAdapter = new MonthlyAdapter(getContext());
showProgressDialog("Loading!!!", false);
observeViewModel();
binding.upcomingEventListView.setAdapter(adapter);
binding.monthlyEventListView.setAdapter(monthlyAdapter);
} catch (Exception e) {
}
}
private void observeViewModel() {
viewModel.itemPagedList.observe(this, eventsItems -> {
if (eventsItems != null && eventsItems.size() > 0) {
updateViews(eventsItems);
adapter.submitList(eventsItems);
dissmissDialog();
}
});
viewModel.monthlyItemPagedList.observe(this, eventsItems -> {
monthlyAdapter.submitList(eventsItems);
dissmissDialog();
});
}
private void updateViews(PagedList<EventsItem> eventsItems) {
binding.eventCard.setVisibility(View.VISIBLE);
binding.upcomingEventCard.setVisibility(View.VISIBLE);
binding.emptyImage.setVisibility(View.GONE);
binding.eventName.setText(eventsItems.get(0).getTitle());
binding.eventTime.setText(eventsItems.get(0).getStartTime());
binding.duration.setText(String.format("%s - %s", eventsItems.get(0).getStartTime(), eventsItems.get(0).getEndTime()));
binding.dateNumber.setText(eventsItems.get(0).getDate());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment