Items in RecyclerView not retaining the changed stated when backed - java

I'm basically working on incrementing, decrementing and removing items from cart in the Recyclerview. I have a general class called CategoryItem.java whose objects I'm passing through to the Main Recyclerview in the mainactivity which show my items (without the quantity) which starts the Cart Activity on a button click and I have passed the same list of CategoryItem objects to the cart on button click. Everything else is working fine except the Cart.java and CartItemRecyclerAdapter, I'm utilizing the quantity attribute of CategoryItem objects here only, now the issue is the item quantity does get incremented/decremented/removed when I click my imageviews but does not retain the values in the textviews (Quantity goes back to 1 and the price gets to original of each item in the cart) and if I had removed the item it appears back when I return from the MainActivity. Also, help me with the carttotal, it does not update when I try to from the CartItemRecyclerAdapter.
public class MainActivity extends AppCompatActivity {
RecyclerView mainrecyclerview;
MainRecyclerAdapter mainRecyclerAdapter;
RecyclerView categoryrecyclerview;
CategoryItemRecyclerAdapter categoryItemRecyclerAdapter;
TextView menu ;
DrawerLayout drawerLayout;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = findViewById(R.id.textView);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.drawer);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawerToggle.setDrawerIndicatorEnabled(false);
drawerToggle.setHomeAsUpIndicator(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_baseline_account_circle_24,getTheme()));
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
});
drawerToggle.syncState();
ImageView cartViewButton = toolbar.findViewById(R.id.viewCartButton);
cartViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),Cart.class);
startActivity(intent);
}
});
List<CategoryItem> soupItemList = new ArrayList<>();
soupItemList.add(new CategoryItem("Chicken Corn",30,R.drawable.soup1));
soupItemList.add(new CategoryItem("Hot & Sour",100,R.drawable.hotnsour));
soupItemList.add(new CategoryItem("Chinese Rice",500,R.drawable.soup3));
soupItemList.add(new CategoryItem("Chicken Noodle",800,R.drawable.soup4));
List<CategoryItem> seafoodItemList = new ArrayList<>();
seafoodItemList.add(new CategoryItem("Chilli Prawns",750,R.drawable.chilliprawn));
seafoodItemList.add(new CategoryItem("Dragon Prawns",750,R.drawable.dragonprawn));
seafoodItemList.add(new CategoryItem("Red Roast Prawns",750,R.drawable.redroastprawn));
seafoodItemList.add(new CategoryItem("Hot & Spicy Fish",750,R.drawable.hotnspicyfish));
List<CategoryItem> poultryItemList = new ArrayList<>();
List<AllCategory> allCategoryList = new ArrayList<>();
allCategoryList.add(new AllCategory("SOUPS",soupItemList));
allCategoryList.add(new AllCategory("SEAFOOD",seafoodItemList));
//allCategoryList.add(new AllCategory("Sizzlers"));
setMainrecyclerview(allCategoryList);
}
private void closeDrawer(){
drawerLayout.closeDrawer(GravityCompat.START);}
private void openDrawer(){
drawerLayout.openDrawer(GravityCompat.START);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
closeDrawer();
}
super.onBackPressed();
}
private void setMainrecyclerview(List<AllCategory> allCategoryList){
mainrecyclerview = findViewById(R.id.mainCatRecycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
mainrecyclerview.setLayoutManager(layoutManager);
mainRecyclerAdapter = new MainRecyclerAdapter(MainActivity.this,allCategoryList);
mainrecyclerview.setAdapter(mainRecyclerAdapter);
}
}
public class Cart extends AppCompatActivity {
Toolbar toolbar;
RecyclerView cartRecyclerview;
CartItemRecyclerAdapter cartItemRecyclerAdapter;
static TextView bill;
int billtotal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
toolbar = findViewById(R.id.carttoolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Cart");
bill = findViewById(R.id.bill);
setCartRecyclerview(getArrayList("key"));
cartItemRecyclerAdapter.updatecarttotal();
bill.setText(""+cartItemRecyclerAdapter.cartTotal);
}
public List<CategoryItem> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<List<CategoryItem>>() {}.getType();
return gson.fromJson(json, type);
}
public void setCartRecyclerview(List<CategoryItem> cartitem){
cartRecyclerview = findViewById(R.id.recyclerView);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(Cart.this);
cartRecyclerview.setLayoutManager(layoutManager);
cartItemRecyclerAdapter = new CartItemRecyclerAdapter(Cart.this,cartitem);
cartRecyclerview.setAdapter(cartItemRecyclerAdapter);
}
}
public class CartItemRecyclerAdapter extends RecyclerView.Adapter<CartItemRecyclerAdapter.CartItemViewHolder> {
Context context;
List<CategoryItem> cartitems;
CartItem quantity;
int cartTotal=0;
public CartItemRecyclerAdapter(Context context, List<CategoryItem> cartitems) {
this.context = context;
this.cartitems = cartitems;
this.quantity = new CartItem(1);
}
#NonNull
#Override
public CartItemRecyclerAdapter.CartItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new CartItemRecyclerAdapter.CartItemViewHolder(LayoutInflater.from(context).inflate(R.layout.cartitem, parent, false));
}
#Override
public void onBindViewHolder(#NonNull CartItemViewHolder holder, int position) {
holder.cartitem.setActivated(true);
holder.cartItemname.setText(cartitems.get(position).getName());
holder.cartItemimage.setImageResource(cartitems.get(position).getImageURI());
holder.cartItemprice.setText("Rs. " + cartitems.get(position).getPrice() * cartitems.get(position).getQuantity());
holder.cartItemquantity.setText("" + cartitems.get(position).getQuantity());
updatecarttotal();
holder.plusimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartitems.get(position).quantity++;
holder.cartItemquantity.setText(""+cartitems.get(position).getQuantity());
holder.cartItemprice.setText("Rs. " + cartitems.get(position).getPrice()*cartitems.get(position).getQuantity());
updatecarttotal();
}
});
holder.minusimagem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartitems.get(position).quantity--;
holder.cartItemquantity.setText(""+cartitems.get(position).getQuantity());
holder.cartItemprice.setText("Rs. " + cartitems.get(position).getPrice()*cartitems.get(position).quantity);
updatecarttotal();
if (cartitems.get(position).getQuantity() == 0) {
cartitems.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, cartitems.size());
updatecarttotal();
} else {
updatecarttotal();
}
}
});
holder.crossimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartitems.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, cartitems.size());
updatecarttotal();
}
});
}
public void updatecarttotal() {
for (int i = 0; i < cartitems.size(); i++) {
cartTotal += cartitems.get(i).getPrice()*quantity.quantity;
}}
#Override
public int getItemCount() {
return cartitems.size();
}
public static final class CartItemViewHolder extends RecyclerView.ViewHolder{
ImageView cartItemimage , plusimage, minusimagem, crossimage;
TextView cartItemname, cartItemprice,cartItemquantity, billtotal;
CardView cartitem;
public CartItemViewHolder(#NonNull View itemView) {
super(itemView);
cartitem = itemView.findViewById(R.id.cartitemcardview);
cartItemimage = itemView.findViewById(R.id.cart_itemimage);
plusimage = itemView.findViewById(R.id.plus);
minusimagem =itemView.findViewById(R.id.minus);
crossimage = itemView.findViewById(R.id.remove);
cartItemname = itemView.findViewById(R.id.cartitemname);
cartItemprice = itemView.findViewById(R.id.cartitemprice);
cartItemquantity = itemView.findViewById(R.id.quantity);
}
}
}'''
public class CategoryItem {
String name;
int imageURI,price;
int quantity;
public CategoryItem(String name, int price, int imageURI) {
this.name = name;
this.price = price;
this.imageURI = imageURI;
this.quantity = 1;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getImageURI() {
return imageURI;
}
public void setImageURI(int imageURI) {
this.imageURI = imageURI;
}}`

Consider storing your state in a viewmodel class using a live data, then you can observe for changes in your data and update your ui accordingly.

Related

When I click on the RecyclerView Item in MainActivity I want the TextView in MainActivity to display Item's title

>>>>>>>MAIN ACTIVITY XML<<<<<<<
As you can see the TextView is on the top, that's where I want to display the title of selected RecyclerView item. Most of the tutorials and blog teach to navigate to next activity when an item is clicked, but that isn't something I am looking for.
MainActivity.java
public class MainActivity extends AppCompatActivity implements ItemAdapterCallback {
private RecyclerView recyclerView;
private List<Item> itemList;
private ItemAdapter itemAdapter;
private SearchView searchView;
TextView itemname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize(savedInstanceState);
initializeLogic();
}
private void initialize(Bundle savedInstanceState) {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
searchView = (SearchView) findViewById(R.id.searchView);
searchView.clearFocus();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
filterList(newText);
return true;
}
});
}
private void filterList(String newText) {
List<Item> filteredList = new ArrayList<>();
for (Item item : itemList) {
if (item.getItemName().toLowerCase().contains(newText.toLowerCase())){
filteredList.add(item);
}
}
if (filteredList.isEmpty()) {
Toast.makeText(this, "No Match", Toast.LENGTH_SHORT).show();
} else {
itemAdapter.setFilteredList(filteredList);
}
}
private void initializeLogic() {
RecyclerView();
}
private void RecyclerView () {
itemList = new ArrayList<>();
// Adding Data to Item List
itemList.add(new Item("Black", R.drawable.android_black));
itemList.add(new Item("Blue", R.drawable.android_blue));
itemList.add(new Item("Green", R.drawable.android_green));
itemList.add(new Item("Pink", R.drawable.android_pink));
itemList.add(new Item("Red", R.drawable.android_red));
itemList.add(new Item("Yellow", R.drawable.android_yellow));
itemList.add(new Item("Black", R.drawable.android_black));
itemList.add(new Item("Blue", R.drawable.android_blue));
itemList.add(new Item("Green", R.drawable.android_green));
itemList.add(new Item("Pink", R.drawable.android_pink));
itemList.add(new Item("Red", R.drawable.android_red));
itemList.add(new Item("Yellow", R.drawable.android_yellow));
itemAdapter = new ItemAdapter(itemList, this);
recyclerView.setAdapter(itemAdapter);
}
#Override
public void onItemClicker() {
//????????????????
}
}
Item.java
public class Item {
private String itemName;
private int itemImage;
public Item(String itemName, int itemImage) {
this.itemImage = itemImage;
this.itemName = itemName;
}
public int getItemImage() {
return itemImage;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
ItemAdapter.java
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {
private List<Item> itemList;
int row_index = -1;
private ItemAdapterCallback callback;
public ItemAdapter(List<Item> itemList, ItemAdapterCallback callback) {
this.itemList = itemList;
this.callback = callback;
}
public void setFilteredList(List<Item> filteredList) {
this.itemList = filteredList;
notifyDataSetChanged();
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item, parent, false );
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
Item item = itemList.get(position);
holder.itemNameTv.setText(item.getItemName());
holder.itemImageView.setImageResource(item.getItemImage());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
////////////////////////////
//Toast.makeText(view.getContext(), "Item is clicked" + item.getItemName(), Toast.LENGTH_SHORT).show();
}
});
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
row_index = position;
notifyDataSetChanged();
Toast.makeText(v.getContext(), "Item is clicked " + position + " " + item.getItemName(), Toast.LENGTH_SHORT).show();
callback.onItemClicker();
}
});
if (row_index == position) {
holder.cardView.setBackgroundColor(Color.LTGRAY);
} else {
holder.cardView.setBackgroundColor(Color.WHITE);
}
}
#Override
public int getItemCount() {
if (itemList == null) {
return 0;
} else {
return itemList.size();
}
}
public class ItemViewHolder extends RecyclerView.ViewHolder{
public TextView itemNameTv;
public ImageView itemImageView;
public CardView cardView;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.eachCardView);
itemNameTv = itemView.findViewById(R.id.eachItemTextView);
itemImageView = itemView.findViewById(R.id.eachItemImageView);
}
}
}
ItemAdapterCallback (Interface)
public interface ItemAdapterCallback {
void onItemClicker();
}
You are just missing few things here.
1- if you want to get the title from the adapter you will need to pass the title in your Callback Interface
public interface ItemAdapterCallback {
void onItemClicker(String title);}
2- after this change you will override the onItemClickerCallback in your mainActivity
it will look like this
#Override
public void onItemClicker(String title) {
// your title ,
itemname.setText(title);
}
3- in onClick function of the adapter add this line
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(callback!=null){
callback.onItemClicker( item.getItemName());
}
}
});
that's all you need to do to show the title in your mainActivity from adapter.

when delete data from recycler view change check item to uncheck in recycler view

When i check item from recyclerview one i can add item in recyclerview second which is on same activity.
When i delete item from second recyclerview through image i want to clear selected checkbox as unselected
in recyclerview first one.In Advance Thanks!!
ListdataAdapter.java
#Override
public void onBindViewHolder(ListdataAdapter.MyViewHolder holder, final int position) {
final ListModel model = listData.get(position);
holder.tvNumber.setText(model.getId());
holder.tvName.setText(model.getName());
holder.cbAction.setOnCheckedChangeListener((buttonView, isChecked) -> {
if(isChecked){
addcheckvalue.add(new CheckedValueModel(model.getId(),model.getName()));
itemCheckListner.onClicked(addcheckvalue);
}else{
Toast.makeText(context,"Item Click", Toast.LENGTH_SHORT).show();
}
});
}
CheckedListAdapter
#Override
public void onBindViewHolder(CheckedListAdapter.MyViewHolder holder, final int position) {
final CheckedValueModel model = checkedList.get(position);
holder.tvNumber.setText(model.getId());
holder.tvName.setText(model.getName());
holder.crossImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckedValueModel item = checkedList.get(position);
checkedList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,checkedList.size());
Toast.makeText(context,"Removed : " + item, Toast.LENGTH_SHORT).show();
}
});
}
interface ItemCheckListner
public interface ItemCheckListner{
void onClicked(List<CheckedValueModel>list);
}
MainActivity
public class MainActivity extends Activity implements ItemCheckListner {
RecyclerView rvDataList;
ListdataAdapter listdataAdapter;
RecyclerView.LayoutManager layoutManager;
List<ListModel> dataList;
ArrayList<CheckedValueModel> checkedList;
RecyclerView rvCheckedList;
CheckedListAdapter checkedListAdapter;
CheckedValueModel checkedValueModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<>();
checkedList = new ArrayList<>();
rvDataList = findViewById(R.id.rvDataList);
rvCheckedList = findViewById(R.id.rvCheckedList);
listdataAdapter = new ListdataAdapter(dataList, this, this::onClicked);
layoutManager = new LinearLayoutManager(this);
rvDataList.setLayoutManager(layoutManager);
rvDataList.setAdapter(listdataAdapter);
listdataAdapter.notifyDataSetChanged();
datalist();
Log.d("checklist_size", "" + checkedList.size());
// checkedList.add(checkedValueModel);
checkedListAdapter = new CheckedListAdapter(checkedList, this);
layoutManager = new LinearLayoutManager(this);
rvCheckedList.setLayoutManager(layoutManager);
rvCheckedList.setAdapter(checkedListAdapter);
checkedListAdapter.notifyDataSetChanged();
}
private void datalist() {
dataList.add(new ListModel("1", "Piyush"));
dataList.add(new ListModel("2", "Raj"));
dataList.add(new ListModel("3", "Ravi"));
dataList.add(new ListModel("4", "Kapil"));
}
#Override
public void onClicked(List<CheckedValueModel>list) {
checkedList=(ArrayList<CheckedValueModel>)list;
checkedListAdapter.updateData(checkedList);
//Toast.makeText(this, data.getId() + data.getName(), Toast.LENGTH_SHORT).show();
}
}
****CheckedValueModel && ListModel ****
**
Both model are same.
**
public class CheckedValueModel {
String id;
String name;
public CheckedValueModel(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Having problem to fetching file from firestore recycle view [duplicate]

This question already has an answer here:
Firebase Android ListView not being displayed
(1 answer)
Closed 1 year ago.
I am an android developer beginner, I am having a problem fetch files from firestore recycle view in the main activity but I can fetch files from fragments.
This is my main activity
public class FoodInfoActivity extends AppCompatActivity {
RecyclerView recyclerView1,recyclerView2;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef;
private NoteAdapter adapter;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_info);
fAuth = FirebaseAuth.getInstance();
setUpRecyclerView();
}
private void setUpRecyclerView() {
notebookRef = db.collection("FoodInside");
Query query = notebookRef;
FirestoreRecyclerOptions<FoodAdapter> options = new FirestoreRecyclerOptions.Builder<FoodAdapter>()
.setQuery(query, FoodAdapter.class)
.build();
adapter = new NoteAdapter(options);
RecyclerView recyclerView = findViewById(R.id.fi);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
This is my Note adapter where i use model class to fetch file
public class NoteAdapter extends FirestoreRecyclerAdapter<FoodAdapter, NoteAdapter.NoteHolder> {
public NoteAdapter(#NonNull FirestoreRecyclerOptions<FoodAdapter> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull NoteHolder holder, int position, #NonNull FoodAdapter foodAdapter) {
holder.textViewTitle.setText(foodAdapter.getRestaurant());
holder.textViewDescription.setText(foodAdapter.getItem());
holder.textViewPriority.setText(String.valueOf(foodAdapter.getPrice()));
}
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_recycle_layout,
parent, false);
return new NoteHolder(v);
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
TextView textViewDescription;
TextView textViewPriority;
public NoteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.textView95a);
textViewDescription = itemView.findViewById(R.id.textView123a);
textViewPriority = itemView.findViewById(R.id.textView124a);
}
}
}
This is my adapter class ,
public class FoodAdapter {
String Restaurant;
String Item;
String Price;
String item_id;
public FoodAdapter() {
}
public FoodAdapter(String restaurant, String item, String price,String item_id) {
Restaurant = restaurant;
Item = item;
Price = price;
this.item_id = item_id;
}
public String getRestaurant() {
return Restaurant;
}
public void setRestaurant(String restaurant) {
Restaurant = restaurant;
}
public String getItem() {
return Item;
}
public void setItem(String item) {
Item = item;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
}
Why it is not working in main activity but work fragment. I am just afraid. and tired...working on the project. so need solution of this problem
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
Add this line to main activity.

How I connect recyclerview to firebase database insert,update and delete data

I create an app which contain recyclerview and I add data in recyclerview arrayList from alertDilog and edit,delete data from AlertDilog according to the user click .It works properly but when I connect my app to firebase Database, my app doesn't work properly.
Recyclerview Adapter:
public class recyclerviewadapter extends RecyclerView.Adapter<recyclerviewadapter.Viewholder> {
ArrayList<customitem> datalist;
vonclick mclick;
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerviewexdesign,parent,false);
return new Viewholder(v,mclick);
}
public recyclerviewadapter(ArrayList<customitem> datalist) {
this.datalist = datalist;
}
#Override
public void onBindViewHolder(#NonNull Viewholder holder, int position) {
customitem n = datalist.get(position);
holder.productname.setText(n.getproductname());
}
#Override
public int getItemCount() {
return datalist.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView productname;
public Viewholder(#NonNull View itemView, final vonclick listener) {
super(itemView);
productname = itemView.findViewById(R.id.titleid);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener!=null){
int possition =getAdapterPosition();
if (possition !=RecyclerView.NO_POSITION){
listener.cclick(possition);
}
}
}
});
}
}
public interface vonclick{
void cclick(int possition);
}
public void recyclerviewonclicl(vonclick possition){
mclick=possition;
}
}
and item class:
public class customitem {
String productname,size,price,box;
int kg;
public customitem(){
}
public customitem(String productname, String size,String price,String box,int kg) {
this.productname = productname;
this.size = size;
this.price = price;
this.box = box;
this.kg = kg;
}
public String getproductname() {
return productname;
}
public void setproductname(String productname) {
this.productname = productname;
}
public String getsize() {
return size;
}
public void setsize(String size) {
this.size = size;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getBox() {
return box;
}
public void setBox(String box) {
this.box = box;
}
public int getKg() {
return kg;
}
public void setKg(int kg) {
this.kg = kg;
}
}
last one main class:
public class addproduct extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<customitem> datalist =new ArrayList<customitem>();
FirebaseDatabase mdatabase;
DatabaseReference mreference;
EditText productname,price,size,b2;
Spinner sizespinner;
Button okbutton;
View mview;
ImageView cancel;
AlertDialog d;
AlertDialog.Builder alert;
recyclerviewadapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addproduct);
getSupportActionBar().setTitle("Add product");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mdatabase = FirebaseDatabase.getInstance();
//?????????????????????? my firebase referance ????????????
mreference = mdatabase.getReference().child("product");
mreference.keepSynced(true);
recyclerView = findViewById(R.id.recyclerviewid);
buildrecyclerview();
//mreference.child("product").setValue(datalist);
}
public void buildrecyclerview(){
adapter = new recyclerviewadapter(datalist);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this,4));
recyclerView.setAdapter(adapter);
mreference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
customitem j =dataSnapshot1.getValue(customitem.class);
datalist.add(j);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
adapter.recyclerviewonclicl(new recyclerviewadapter.vonclick() {
#Override
public void cclick(final int possition) {
//?????????????? alert dilog two for delete and update data ????????????????
AlertDialog.Builder bl = new AlertDialog.Builder(addproduct.this);
View v = getLayoutInflater().inflate(R.layout.manageralertdilogtwo,null);
bl.setView(v);
d=bl.create();
d.show();
final EditText productname2 = v.findViewById(R.id.productname2);
final EditText size2 = v.findViewById(R.id.packsizeid2);
final EditText price2 = v.findViewById(R.id.priceid2);
final EditText box2 = v.findViewById(R.id.Box2);
Button okbtn = v.findViewById(R.id.okbuttonid2);
Button dltbtn = v.findViewById(R.id.deleteid);
ImageView cross =v.findViewById(R.id.cancelid2);
final Spinner sp =v.findViewById(R.id.spinnerid2);
//String pn = datalist.get(possition).getproductname();
productname2.setText(datalist.get(possition).getproductname());
size2.setText(datalist.get(possition).getsize());
price2.setText(datalist.get(possition).getPrice());
box2.setText(datalist.get(possition).getBox());
sp.setSelection(datalist.get(possition).getKg());
cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
okbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//?????????????? update data accroding user selectiong ??????????????
//datalist.get(possition).setproductname(productname2.getText().toString());
//datalist.get(possition).setPrice(price2.getText().toString());
//datalist.get(possition).setsize(size2.getText().toString());
//datalist.get(possition).setBox(box2.getText().toString());
//datalist.get(possition).setKg(sp.getSelectedItemPosition());
customitem m = new customitem(productname2.getText().toString(),size2.getText().toString()
,price2.getText().toString(),box2.getText().toString(),sp.getSelectedItemPosition());
mreference.child(String.valueOf(datalist.get(possition))).setValue(m);
d.dismiss();
}
});
dltbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//???????????????? delete data from recycler view accroding user selection ???????????
//datalist.remove(possition);
mreference.child(String.valueOf(datalist.get(possition))).removeValue();
// adapter.notifyDataSetChanged();
d.dismiss();
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.addproductmenu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.addproduct:
buildalert();
break;
case R.id.seedetails:
Intent n = new Intent(addproduct.this,managermain.class);
startActivity(n);
break;
}
return super.onOptionsItemSelected(item);
}
public void buildalert(){
//?????? alert dilog one for take data ???????????????
alert = new AlertDialog.Builder(addproduct.this);
mview = getLayoutInflater().inflate(R.layout.manageralertalertdilog,null);
productname = mview.findViewById(R.id.productname);
price = mview.findViewById(R.id.priceid);
alert.setCancelable(true);
size = mview.findViewById(R.id.packsizeid);
cancel = mview.findViewById(R.id.cancelid);
sizespinner = mview.findViewById(R.id.spinnerid);
okbutton = mview.findViewById(R.id.okbuttonid);
b2 = mview.findViewById(R.id.Box);
alert.setView(mview);
final AlertDialog dl = alert.create();
dl.show();
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dl.dismiss();
}
});
okbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (productnamem() && sizem()){
//add data from alert dilog
String productnm = productname.getText().toString();
String pricec = price.getText().toString();
String sizee = size.getText().toString();
int kg = sizespinner.getSelectedItemPosition();
String box= b2.getText().toString();
//?? add data in recyclerview from alert dilog ???????????????
//datalist.add(new customitem(productnm,sizee,pricec,box,kg));
customitem n = new customitem(productnm,sizee,pricec,box,kg);
mreference.child(String.valueOf(datalist.size())).setValue(n);
//adapter.notifyDataSetChanged();
//mreference.setValue(datalist);
dl.dismiss();
}
}
});
}
public boolean productnamem(){
if (productname.getText().toString().trim().isEmpty()){
productname.setError("Please fill it");
productname.setFocusable(true);
return false;
}
else {
return true;
}
}
public boolean sizem(){
if (size.getText().toString().trim().isEmpty()){
size.setError("Please fill it");
size.setFocusable(true);
return false;
}
else {
return true;
}
}
}

FIrebase Adapter not populating data correctly

Sorry if i m asking lame questions i m new to android development.
I have a activity in which i m populating firebase recycler adapter problem is that it is not populating recycler (loadFoodlist) when i click on that activity once.
But when i click that activity twice or thrice after that it is getting data perfectly fine i don't know what is the problem it happens whenever i relaunch the app?
Database structure
database image
public class FoodDetailModel {
String name, price, description, type;
public FoodDetailModel(){
}
public FoodDetailModel(String name, String price, String description, String type) {
this.name = name;
this.price = price;
this.description = description;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class FoodDetailViewHolder extends RecyclerView.ViewHolder {
public TextView foodname,price,description;
public Button delete;
public ImageView type;
public FoodDetailViewHolder(#NonNull View itemView) {
super(itemView);
foodname = (TextView) itemView.findViewById(R.id.food_name);
price = (TextView) itemView.findViewById(R.id.food_price);
description = (TextView) itemView.findViewById(R.id.food_description);
delete = (Button) itemView.findViewById(R.id.add_to_cart);
type = itemView.findViewById(R.id.type);
}
}
public class FoodDetail extends AppCompatActivity {
FirebaseDatabase database;
FirebaseAuth mAuth;
DatabaseReference ref;
FirebaseRecyclerAdapter<FoodDetailModel, FoodDetailViewHolder> adapter;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
CollapsingToolbarLayout collapsingToolbarLayout;
ProgressDialog dialog1 ;
String resID = "", resName = "";
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
dialog1 = new ProgressDialog(FoodDetail.this);
mAuth = FirebaseAuth.getInstance();
imageView = (ImageView) findViewById(R.id.food_img);
if(getIntent() != null){
resID = getIntent().getStringExtra("restraunt_id");
resName = getIntent().getStringExtra("name");
}
// init firebase
collapsingToolbarLayout = findViewById(R.id.collapsing);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppBar);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppBar);
collapsingToolbarLayout.setTitle(resName);
// load restuarant list from firebase
recycler_menu = (RecyclerView) findViewById(R.id.foodmenu_list);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadFoodList();
loadName();
}
private void loadName() {
DatabaseReference ref1 = FirebaseDatabase.getInstance().getReference();
DatabaseReference mostafa = ref1.child("restaurant").child(resID).child("img");
mostafa.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String imgURL = dataSnapshot.getValue(String.class);
Picasso.with(getBaseContext()).load(imgURL).fit().into(imageView);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void loadFoodList() {
ref = FirebaseDatabase.getInstance().getReference().child("menu").child(resID);
System.out.println("getttts here" + ref.toString());
adapter = new FirebaseRecyclerAdapter<FoodDetailModel, FoodDetailViewHolder>
(FoodDetailModel.class,R.layout.food_detail_blueprint, FoodDetailViewHolder.class,ref) {
#Override
protected void populateViewHolder(final FoodDetailViewHolder viewHolder, final FoodDetailModel model, final int position) {
final String x = adapter.getRef(position).toString();
viewHolder.foodname.setText(model.getName());
viewHolder.price.setText("₹"+model.getPrice());
viewHolder.description.setText(model.getDescription());
String typ = model.getType();
if (typ.equals("veg")){
viewHolder.type.setImageResource(R.drawable.veg);
} else {
viewHolder.type.setImageResource(R.drawable.nonveg);
}
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder alert = new AlertDialog.Builder(FoodDetail.this);
alert.setTitle("Delete entry");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close dialog
dialog.cancel();
}
});
alert.show();
}
});
}
};
recycler_menu.setAdapter(adapter);
}
}

Categories