How to pass data when using Nested Recycler View - java

I have been trying to figure it out for a few days now and I still can't solve it.
I created a 3-layer nested recycler view and the display is okay.
1st layer is CartStoreAdapter
2nd layer is for it's CartItemAdapter
3rd layer is for the product's CartItemAddonAdapter
My problem is that. I want to display the total price of all the products per store(including the addon prices) considering the qty aswell. But I can't seem to pass the total Price variable (
totalItems += subTotal;
) to the CartStoreAdapter.
I tried creating a public method within the CartItemAdapter. When I use Log.d within the viewholder of CartItemAdapter,
2023-02-02 17:25:36.773 19606-19606/ph.kaminarigo.app D/totalItems: 522.0
2023-02-02 17:25:37.028 19606-19606/ph.kaminarigo.app D/totalItems: 532.0
2023-02-02 17:25:37.120 19606-19606/ph.kaminarigo.app D/totalItems: 660.0
2023-02-02 17:25:37.178 19606-19606/ph.kaminarigo.app D/totalItems: 1485.0
2023-02-02 17:25:37.230 19606-19606/ph.kaminarigo.app D/totalItems: 1785.0
shows up properly. But when I use the variable in the method. It's already zero even before I access that method in the CartStoreAdapter.
public class CartStoreAdapter extends RecyclerView.Adapter<CartStoreAdapter.ItemRowHolder> {
private List<CartStoreModel> storeDataList;
private Context mContext;
private int rowLayout;
private CartItemAdapter cartItemAdapter;
public CartStoreAdapter(List<CartStoreModel> storeDataList, Context mContext, int rowLayout) {
this.storeDataList = storeDataList;
this.mContext = mContext;
this.rowLayout = rowLayout;
}
#NonNull
#Override
public CartStoreAdapter.ItemRowHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ItemRowHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartStoreAdapter.ItemRowHolder holder, int position) {
final CartStoreModel singleItem = storeDataList.get(position);
holder.bind(singleItem);
}
#Override
public int getItemCount() {
return (null != storeDataList ? storeDataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder{
TextView tvStoreName, tvStoreTotal;
RecyclerView rvStoreItems;
public ItemRowHolder(#NonNull View itemView) {
super(itemView);
tvStoreName = itemView.findViewById(R.id.tvStoreName);
rvStoreItems = itemView.findViewById(R.id.rvStoreItems);
tvStoreTotal = itemView.findViewById(R.id.tvStoreTotal);
}
public void bind(CartStoreModel singleItem){
tvStoreName.setText(String.valueOf(singleItem.getNama_merchant()));
CartItemAdapter cartItemAdapter = new CartItemAdapter(singleItem.getCartItem(), mContext, R.layout.cart_item);
rvStoreItems.setAdapter(cartItemAdapter);
rvStoreItems.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
double total = cartItemAdapter.getTotalItems();
Utility.currencyTXT(tvStoreTotal, String.valueOf(total), mContext);
}
}
}
public class CartItemAdapter extends RecyclerView.Adapter<CartItemAdapter.ItemRowHolder> {
private List<CartItemModel> itemDataList;
private Context mContext;
private int rowLayout;
private double totalItems;
public CartItemAdapter(List<CartItemModel> itemDataList, Context mContext, int rowLayout) {
this.itemDataList = itemDataList;
this.mContext = mContext;
this.rowLayout = rowLayout;
}
#NonNull
#Override
public CartItemAdapter.ItemRowHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ItemRowHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartItemAdapter.ItemRowHolder holder, int position) {
final CartItemModel singleItem = itemDataList.get(position);
holder.bind(singleItem);
}
#Override
public int getItemCount() {
return (null != itemDataList ? itemDataList.size() : 0);
}
public double getTotalItems(){
return totalItems;
}
public class ItemRowHolder extends RecyclerView.ViewHolder{
TextView tvProductTitle, tvMainPrice, tvPromoPrice, tvSubTotal, tvQty;
ImageView imgThumbnail;
RecyclerView rvCartItemVar;
Button btnDeduct, btnAdd;
CheckBox cbSelectItem;
public ItemRowHolder(#NonNull View itemView) {
super(itemView);
tvProductTitle = itemView.findViewById(R.id.tvProductTitle);
tvMainPrice = itemView.findViewById(R.id.tvMainPrice);
tvPromoPrice = itemView.findViewById(R.id.tvPromoPrice);
imgThumbnail = itemView.findViewById(R.id.imgThumbnail);
rvCartItemVar = itemView.findViewById(R.id.rvCartItemVar);
tvSubTotal = itemView.findViewById(R.id.tvSubTotal);
btnAdd = itemView.findViewById(R.id.btnAdd);
btnDeduct = itemView.findViewById(R.id.btnDeduct);
tvQty = itemView.findViewById(R.id.tvQty);
cbSelectItem = itemView.findViewById(R.id.cbSelectItem);
}
public void bind(final CartItemModel singleItem){
CartItemAddonAdapter cartItemAddonAdapter = new CartItemAddonAdapter(singleItem.getCartItemVar(), mContext, R.layout.cart_item_variation);
rvCartItemVar.setAdapter(cartItemAddonAdapter);
rvCartItemVar.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
double activePrice, promoPrice, addOnPrice, itemCost, subTotal;
int itemQty = singleItem.getQty();
if(Constants.use_glide) {
Glide.with(mContext)
.load(Constants.IMAGESITEM + singleItem.getFoto_item())
.apply(new RequestOptions().override(250, 250))
.into(imgThumbnail);
} else {
Picasso.with(mContext)
.load(Constants.IMAGESITEM + singleItem.getFoto_item())
.placeholder(R.drawable.image_placeholder)
.resize(250, 250)
.into(imgThumbnail);
}
if(singleItem.getHarga_promo() > 0){
promoPrice = singleItem.getHarga_item();
activePrice = singleItem.getHarga_promo();
tvPromoPrice.setPaintFlags(tvPromoPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
tvPromoPrice.setTextColor(Color.LTGRAY);
} else {
promoPrice = 0;
activePrice = singleItem.getHarga_item();
tvPromoPrice.setVisibility(View.GONE);
}
addOnPrice = cartItemAddonAdapter.getTotalAddonPrice();
itemCost = activePrice + addOnPrice;
subTotal = itemCost * itemQty;
totalItems += subTotal;
tvProductTitle.setText(String.valueOf(singleItem.getNama_item()));
tvQty.setText(String.valueOf(itemQty));
Utility.currencyTXT(tvMainPrice, String.valueOf(activePrice), mContext);
Utility.currencyTXT(tvPromoPrice, String.valueOf(promoPrice), mContext);
Utility.currencyTXT(tvSubTotal, String.valueOf(subTotal), mContext);
Log.d("totalItems", String.valueOf(totalItems));
}
}
}
public class CartItemAddonAdapter extends RecyclerView.Adapter<CartItemAddonAdapter.ItemRowHolder> {
private List<CartItemVarModel> addOnsDataList;
private Context mContext;
private int rowLayout;
public CartItemAddonAdapter(List<CartItemVarModel> addOnsDataList, Context mContext, int rowLayout) {
this.addOnsDataList = addOnsDataList;
this.mContext = mContext;
this.rowLayout = rowLayout;
}
#NonNull
#Override
public CartItemAddonAdapter.ItemRowHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(rowLayout,parent,false);
return new ItemRowHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartItemAddonAdapter.ItemRowHolder holder, int position) {
final CartItemVarModel singleItem = addOnsDataList.get(position);
holder.bind(singleItem);
}
#Override
public int getItemCount() {
return (null != addOnsDataList ? addOnsDataList.size() : 0);
}
public double getTotalAddonPrice() {
double totalAddonPrice = 0;
for(CartItemVarModel addon : addOnsDataList){
totalAddonPrice += addon.getVar_price();
}
return totalAddonPrice;
}
public class ItemRowHolder extends RecyclerView.ViewHolder{
TextView tvVarGroup, tvItemVar, tvPrice;
public ItemRowHolder(#NonNull View itemView) {
super(itemView);
tvVarGroup = itemView.findViewById(R.id.tvVarGroup);
tvItemVar = itemView.findViewById(R.id.tvItemVar);
tvPrice = itemView.findViewById(R.id.tvPrice);
}
public void bind(CartItemVarModel dataList){
tvVarGroup.setText(dataList.getGroup_name());
tvItemVar.setText(dataList.getVar_name());
Utility.currencyTXT(tvPrice, String.valueOf(dataList.getVar_price()), mContext);
}
}
}
I also tried to save the changes in the model but I still can't access it outside of the itemviewholder.

I would try to create the CartStoreModel items with the total prices inside each item and initialize them before I pass them to CartStoreAdapter.
Recommend to use ViewModel to calculate the prices and attach them to CartStoreModel items before you send them to CartStoreAdapter.
public class StoreViewModel extends ViewModel {
public ArrayList<CartStoreModel> getItemsWithPrices(){
for(CartStoreModel item : items) {
int totalItemPrice = item.price;
int totalItemAddonPrices = item.getTotalAddonsPrices()// calculate the prices
item.totalPrices = totalItemPrice + totalItemAddonPrices
}
}
}
Recommend to do it in another Thread (not the Main Thread) in case you have a lot of items in your list...

Related

getResources usage inside adapter class in android

I have adapted class like this
public class InboxAdapter extends RecyclerView.Adapter<InboxAdapter.ViewHolder> {
private static final String LOG_TAG = InboxAdapter.class.getSimpleName();
private List<inbox> mInboxes;
private Context context;
public InboxAdapter(List<inbox> inboxes) {
mInboxes = inboxes;
}
#Override
public InboxAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.recyclerview_mail_item, parent, false);
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(InboxAdapter.ViewHolder holder, int position) {
inbox inbox = mInboxes.get(position);
holder.tvIcon.setText(inbox.getName().substring(0,1).toUpperCase());
holder.tvEmailSender.setText(inbox.getFrom());
holder.tvEmailTitle.setText(inbox.getSubject());
}
#Override
public int getItemCount() {
return mInboxes.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvIcon;
public TextView tvEmailSender;
public TextView tvEmailTitle;
public TextView tvEmailDetails;
public TextView tvEmailTime;
public ViewHolder(View itemView) {
super(itemView);
tvIcon = itemView.findViewById(R.id.tvIcon);
tvEmailSender = itemView.findViewById(R.id.tvEmailSender);
tvEmailTitle = itemView.findViewById(R.id.tvEmailTitle);
tvEmailDetails = itemView.findViewById(R.id.tvEmailDetails);
tvEmailTime = itemView.findViewById(R.id.tvEmailTime);
}
}
private int getRandomMaterialColor(String typeColor) {
int returnColor = Color.GRAY;
int arrayId =getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());
if (arrayId != 0) {
TypedArray colors = getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.GRAY);
colors.recycle();
}
return returnColor;
}
}
Its working fine but I want set different color for my view holder text so I have added function in it called getRandomMaterialColor. But its using getResources inside it and I am not able to use getActivity. Anyone here can please help me for solve puzzle for me? Thanks!
You can use the view(itemView) in ViewHolder Class for get the resources, for example:
private int getRandomMaterialColor(View view,String typeColor) {
int returnColor = Color.GRAY;
int arrayId =view.getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());
if (arrayId != 0) {
TypedArray colors = view.getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.GRAY);
colors.recycle();
}
return returnColor;
}

Android Studio: Deleting Item from ChildRecyclerView

I'm currently building a schedule app where users can input information, and the app will organize the information in a list with each day of the week as the header with each corresponding activity under the day. I'm using a parent child recyclerview to do this (i.e. each day of the week is a part of the parent recyclerview and each activity in the schedule is part of the child recyclerview). Right now I'm trying to add a swipe to delete information in the child recyclerview. Does anyone know how I would go about doing this using the parent child recyclerview configuration, where I have two different adapters for each recyclerview?
Code for Parent RecyclerView:
public class MainRecyclerViewAdapter extends RecyclerView.Adapter<MainRecyclerViewAdapter.ViewHolder> {
ArrayList<DayHeader> weekList;
private Context mContext;
public MainRecyclerViewAdapter(Context mContext, ArrayList<DayHeader> weekList) {
this.mContext = mContext;
this.weekList = weekList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.dayofweekheader,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
DayHeader section = weekList.get(position);
String nameofday = section.getDayName();
ArrayList<medinfo> meditems = section.getmMedItems();
holder.weekdayname.setText(nameofday);
MedicationAdapter childrecyclerAdapter = new MedicationAdapter(mContext,meditems);
holder.childrecyclerview.setAdapter(childrecyclerAdapter);
}
#Override
public int getItemCount() {
return weekList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView weekdayname;
RecyclerView childrecyclerview;
public ViewHolder(#NonNull View itemView) {
super(itemView);
weekdayname = itemView.findViewById(R.id.weekdayheader);
childrecyclerview = itemView.findViewById(R.id.childrecyclerview);
}
}
}
Code for Child RecyclerView:
public class MedicationAdapter extends RecyclerView.Adapter<MedicationAdapter.MedicationViewHolder>{
private ArrayList<medinfo> mMedList;
private Context mContext;
public static class MedicationViewHolder extends RecyclerView.ViewHolder {
public TextView mMedname;
public TextView mTime;
public TextView mNumbPills;
public ImageView popup;
public MedicationViewHolder(#NonNull View itemView) {
super(itemView);
mMedname = itemView.findViewById(R.id.medname);
mTime = itemView.findViewById(R.id.time);
mNumbPills = itemView.findViewById(R.id.numberofpills);
popup = itemView.findViewById(R.id.menumore);
}
}
public MedicationAdapter(Context mContext, ArrayList<medinfo> medList) {
this.mContext = mContext;
this.mMedList = medList;
}
#NonNull
#Override
public MedicationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item,parent,false);
MedicationViewHolder mvh = new MedicationViewHolder(v);
return mvh;
}
#Override
public void onBindViewHolder(#NonNull MedicationViewHolder holder, int position) {
medinfo currentItem = mMedList.get(position);
String medName = "Medication: " + currentItem.getmMedName();
holder.mMedname.setText(medName);
String medTime = "Time: " + currentItem.getmTime();
holder.mTime.setText(medTime);
String numbPills = "# of Pills: " + currentItem.getmNumbPills();
holder.mNumbPills.setText(numbPills);
}
#Override
public int getItemCount() {
return mMedList.size();
}
public void removeItem(int position) {
mMedList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,mMedList.size());
}
}
I also have this SwipeItem class:
public class SwipeItem extends ItemTouchHelper.SimpleCallback {
MedicationAdapter mMedAdapter;
SwipeItem(MedicationAdapter mMedAdapter){
super(0,ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT);
this.mMedAdapter = mMedAdapter;
}
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getBindingAdapterPosition();
this.mMedAdapter.removeItem(position);
}
}
So how can I implement the SwipeItem in my adapter codes to delete each child item?

Show data in Nested Recyclerview in android

As I fetched and show the dates (see image) as the title of the main recyclerview. I want to show the available slots data instead of the 0 1 2 etc elements. The code is attached below
Url for json data
https://run.mocky.io/v3/c9bd7858-0e41-422f-b1d2-cd490c08583b
AppointmentTimeActivity.java
public class AppointmentTimeActivity extends AppCompatActivity {
SharedPrefManager sharedPrefManager;
Button appointmentTimeButton;
private TextView doctorFullName;
ConstraintLayout constraintLayout;
public static List<List<String>> availableSlots;
RecyclerView rvGroup;
public static ArrayList<String> arrayListGroup;
LinearLayoutManager layoutManagerGroup;
GroupAdapter groupAdapter;
private DoctorScheduleResponse timings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_appointment_time);
getSupportActionBar().setTitle("Appointment time");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sharedPrefManager = new SharedPrefManager(this);
constraintLayout = findViewById(R.id.constraintLayout);
appointmentTimeButton = findViewById(R.id.book_video_call_appointment_btn);
doctorFullName = findViewById(R.id.doctor_full_name);
rvGroup = findViewById(R.id.rv_group);
String docName = getIntent().getStringExtra("doctorFullName");
doctorFullName.setText(docName);
arrayListGroup = new ArrayList<>();
fetchAndShowAppointmentsTime();
}
private void fetchAndShowAppointmentsTime() {
String id = String.valueOf(SpecialityActivity.doctorID);
Call<DoctorScheduleResponse> call = RetrofitClient.getInstance().getMyInterface().getAppointmentTime("Bearer " + sharedPrefManager.getAccessToken(), id);
call.enqueue(new Callback<DoctorScheduleResponse>() {
#Override
public void onResponse(#NotNull Call<DoctorScheduleResponse> call, #NotNull Response<DoctorScheduleResponse> response) {
arrayListGroup = new ArrayList<>();
if (response.isSuccessful()) {
assert response.body() != null;
for (List<Slot> slots : response.body().getSlot()) {
for (Slot slot : slots) {
arrayListGroup.add(slot.getScheduleDate());
}
}
groupAdapter = new GroupAdapter(AppointmentTimeActivity.this, response.body().getSlot());
layoutManagerGroup = new LinearLayoutManager(getApplicationContext());
rvGroup.setLayoutManager(layoutManagerGroup);
rvGroup.setAdapter(groupAdapter);
}
}
#Override
public void onFailure(#NotNull Call<DoctorScheduleResponse> call, #NotNull Throwable t) {
Toast.makeText(getBaseContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
DoctorScheduleResponse.java
public class DoctorScheduleResponse {
#SerializedName("slot")
#Expose
private List<List<Slot>> slot = null;
public List<List<Slot>> getSlot() {
return slot;
}
public void setSlot(List<List<Slot>> slot) {
this.slot = slot;
}
}
GroupAdater.java
public class GroupAdapter extends RecyclerView.Adapter<GroupAdapter.ViewHolder> {
private Activity activity;
ArrayList<String> arrayListGroup, arrayListMember;
LinearLayoutManager linearLayoutManager;
SharedPrefManager sharedPrefManager;
List<List<Slot>> slotsList;
public GroupAdapter(Activity activity, ArrayList<String> arrayListGroup) {
this.activity = activity;
this.arrayListGroup = arrayListGroup;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_slot_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.dummyTV.setText(arrayListGroup.get(position));
arrayListMember = new ArrayList<>();
sharedPrefManager = new SharedPrefManager(activity);
for (int i = 0; i < 5; i++) {
arrayListMember.add(String.valueOf(i));
}
CustomAdapter customAdapter = new CustomAdapter(arrayListMember);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
holder.rvMember.setLayoutManager(linearLayoutManager);
holder.rvMember.setAdapter(customAdapter);
}
#Override
public int getItemCount() {
return arrayListGroup.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView dummyTV;
RecyclerView rvMember;
public ViewHolder(#NonNull View itemView) {
super(itemView);
dummyTV = itemView.findViewById(R.id.dummyTextView);
rvMember = itemView.findViewById(R.id.rv_member);
}
}
}
CustomAdapter.java
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.SlotsViewHolder> {
ArrayList<String> slots;
public CustomAdapter(ArrayList<String> slots) {
this.slots = slots;
}
#NonNull
#Override
public SlotsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.available_slots_list, parent, false);
return new CustomAdapter.SlotsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SlotsViewHolder holder, int position) {
holder.tvSlots.setText(slots.get(position));
}
#Override
public int getItemCount() {
return slots.size();
}
public class SlotsViewHolder extends RecyclerView.ViewHolder {
TextView tvSlots;
public SlotsViewHolder(#NonNull View itemView) {
super(itemView);
tvSlots = itemView.findViewById(R.id.tv_slots);
}
}
}
Nested recycler view will be more complex in terms of memory. So you can achieve same UI with different approach.
You should try with single recycler view with dynamic layout binding.
Example: For single item of recycler view, there will be a header(for date) and a viewgroup(may be linear layout) then bind any no. of child views inside that linear layout.
The problem is in GroupAdater.java. Inside onBindViewHolder method you are adding the value of loop variable to your list that you pass to your nested recycler view adaptor.
for (int i = 0; i < 5; i++) {
arrayListMember.add(String.valueOf(i));
}
You have to add the correct date from arrayListGroup object.

attempting to use incompatible return type

Can someone help me with this error that I keep getting? The program that I'm trying to implement admob banner ad between items in recyclerview. every thing is ok but still this one error that blocked me from go on.
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder> {
public static final String TAG = RecipeAdapter.class.getSimpleName();
public static final HashMap<String, Integer> LABEL_COLORS = new HashMap<String, Integer>() {{
put("Low-Carb", R.color.colorLowCarb);
put("Low-Fat", R.color.colorLowFat);
put("Low-Sodium", R.color.colorLowSodium);
put("Medium-Carb", R.color.colorMediumCarb);
put("Vegetarian", R.color.colorVegetarian);
put("Balanced", R.color.colorBalanced);
}};
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Recipe> mDataSource;
private static final int DEFAULT_VIEW_TYPE = 1;
private static final int NATIVE_AD_VIEW_TYPE = 2;
public RecipeAdapter(Context context, ArrayList<Recipe> items) {
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); }
#Override public int getItemViewType(int position) {
// Change the position of the ad displayed here. Current is after 5
if ((position + 1) % 6 == 0) {
return NATIVE_AD_VIEW_TYPE;
}
return DEFAULT_VIEW_TYPE; }
#NonNull
#Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
switch (viewType) {
default:
view = layoutInflater
.inflate(R.layout.list_item_native_ad, parent, false);
return new ViewHolder(view);
case NATIVE_AD_VIEW_TYPE:
view = layoutInflater.inflate(R.layout.list_item_native_ad, parent, false);
return new ViewHolderAdMob(view);
}
}
#Override public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// Get relevant subviews of row view
TextView titleTextView = holder.titleTextView;
TextView subtitleTextView = holder.subtitleTextView;
TextView detailTextView = holder.detailTextView;
ImageView thumbnailImageView = holder.thumbnailImageView;
//Get corresponding recipe for row final Recipe recipe = (Recipe) getItem(position);
// Update row view's textviews to display recipe information
titleTextView.setText(recipe.title);
subtitleTextView.setText(recipe.description);
detailTextView.setText(recipe.label);
// Use Picasso to load the image. Temporarily have a placeholder in case it's slow to load
Picasso.with(mContext).load(recipe.imageUrl).placeholder(R.mipmap
.ic_launcher).into(thumbnailImageView);
holder.parentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent detailIntent = new Intent(mContext, RecipeDetailActivity.class);
detailIntent.putExtra("title", recipe.title);
detailIntent.putExtra("url", recipe.instructionUrl);
mContext.startActivity(detailIntent);
}
});
// Style text views
Typeface titleTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/JosefinSans-Bold.ttf");
titleTextView.setTypeface(titleTypeFace);
Typeface subtitleTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/JosefinSans-SemiBoldItalic.ttf");
subtitleTextView.setTypeface(subtitleTypeFace);
Typeface detailTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/Quicksand-Bold.otf");
detailTextView.setTypeface(detailTypeFace);
detailTextView.setTextColor(android.support.v4.content.ContextCompat.getColor(mContext, LABEL_COLORS
.get(recipe.label)));
}
#Override public int getItemCount() {
return mDataSource.size(); }
#Override public long getItemId(int position) {
return position; }
public Object getItem(int position) {
return mDataSource.get(position); }
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView titleTextView;
private TextView subtitleTextView;
private TextView detailTextView;
private ImageView thumbnailImageView; private View parentView;
public ViewHolder(#NonNull View view){
super(view);
// create a new "Holder" with subviews
this.parentView = view;
this.thumbnailImageView = (ImageView) view.findViewById(R.id.recipe_list_thumbnail);
this.titleTextView = (TextView) view.findViewById(R.id.recipe_list_title);
this.subtitleTextView = (TextView) view.findViewById(R.id.recipe_list_subtitle);
this.detailTextView = (TextView) view.findViewById(R.id.recipe_list_detail);
// hang onto this holder for future recyclage
view.setTag(this);
}
}
public class ViewHolderAdMob extends RecyclerView.ViewHolder {
private final AdView mNativeAd;
public ViewHolderAdMob(View itemView) {
super(itemView);
mNativeAd = itemView.findViewById(R.id.nativeAd);
mNativeAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLoaded");
// }
}
#Override
public void onAdClosed() {
super.onAdClosed();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdClosed");
// }
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdFailedToLoad");
// }
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLeftApplication");
// }
}
#Override
public void onAdOpened() {
super.onAdOpened();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdOpened");
// }
}
});
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("") // Remove this before publishing app
.build();
mNativeAd.loadAd(adRequest);
}
}
}
The return type needs to be whatever ViewHolder type you declared for your adapter class.
For example, from the Android RecyclerView example page:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
// ^^^^^^^^^^^^^^^^^^^^^^
// It should return this type ^
public static class MyViewHolder extends RecyclerView.ViewHolder {
// your adapter
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// Note: returns MyAdapter.MyViewHolder, not RecyclerView.ViewHolder
}
}
In your case, you have
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder>
which means your onCreateViewHolder has to return RecipeAdapter.ViewHolder not RecyclerView.ViewHolder.
There is a separate issue too, which is that you have two ViewHolder types in the same adapter. To do this, you would need to change the ViewHolder type that your RecyclerView is based on to the generic type (RecyclerView.ViewHolder).
Please review this question, it has good answers for how to do this.

Usage time of all (individual) applications in android [Usage]

I tried executing the code below, but this gives the "Last Time Used" of the applications.
public class UsageListAdapter extends RecyclerView.Adapter<UsageListAdapter.ViewHolder> {
private List<CustomUsageStats> mCustomUsageStatsList = new ArrayList<>();
private DateFormat mDateFormat = new SimpleDateFormat();
/**
* Provide a reference to the type of views that you are using (custom ViewHolder)
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView mPackageName;
private final TextView mLastTimeUsed;
private final ImageView mAppIcon;
public ViewHolder(View v) {
super(v);
mPackageName = (TextView) v.findViewById(R.id.textview_package_name);
mLastTimeUsed = (TextView) v.findViewById(R.id.textview_last_time_used);
mAppIcon = (ImageView) v.findViewById(R.id.app_icon);
}
public TextView getLastTimeUsed() {
return mLastTimeUsed;
}
public TextView getPackageName() {
return mPackageName;
}
public ImageView getAppIcon() {
return mAppIcon;
}
}
public UsageListAdapter() {
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.usage_row, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
viewHolder.getPackageName().setText(
mCustomUsageStatsList.get(position).usageStats.getPackageName());
long lastTimeUsed = mCustomUsageStatsList.get(position).usageStats.getLastTimeUsed();
viewHolder.getLastTimeUsed().setText(mDateFormat.format(new Date(lastTimeUsed)));
viewHolder.getAppIcon().setImageDrawable(mCustomUsageStatsList.get(position).appIcon);
}
#Override
public int getItemCount() {
return mCustomUsageStatsList.size();
}
public void setCustomUsageStatsList(List<CustomUsageStats> customUsageStats) {
mCustomUsageStatsList = customUsageStats;
}
}
So can anyone modify this and get the time used of each application (in foreground/background) and display it.

Categories

Resources