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);
}
}
Related
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.
I want to retrieve data from Firebase to recyclerView through FirebaseRecyclerOptionsbut it keeps showing blanks pages,I want to display the registered Users in my App and there details in a layout,I have no idea where I have gone wrong,I have multi check on my codes and I can't see any error Please can Anyone help me here.
Here Are Code for ListAdapter,Model and ListActivity
public class ListActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private DatabaseReference reference;
RecyclerView recyclerView;
ListAdapter listAdapter;
private String CurrentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
recyclerView = findViewById(R.id.children_home_list);
firebaseAuth = FirebaseAuth.getInstance();
CurrentUserID = firebaseAuth.getCurrentUser().getUid();
reference = FirebaseDatabase.getInstance().getReference().child("Children Home Details");
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<Model> options =
new FirebaseRecyclerOptions.Builder<Model>()
.setQuery(reference, Model.class)
.build();
listAdapter = new ListAdapter(options);
}
#Override
protected void onStart() {
super.onStart();
listAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
listAdapter.stopListening();
}
public class ListAdapter extends FirebaseRecyclerAdapter<Model,ListAdapter.ListViewHolder> {
public ListAdapter(#NonNull FirebaseRecyclerOptions<Model> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ListViewHolder holder, int position, #NonNull Model model) {
holder.Name.setText(model.getName());
holder.Phone.setText(model.getPhone());
holder.Location.setText(model.getLocation());
holder.Email.setText(model.getMailAddress());
//Glide.with(holder.circleImageView.getContext()).load(model.IMAGELINK()).into(holder.circleImageView);
}
#NonNull
#Override
public ListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow,parent,false);
return new ListViewHolder(view);
}
class ListViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
TextView Name,Phone,Email,Location;
public ListViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView = itemView.findViewById(R.id.img1);
Name = itemView.findViewById(R.id.HomeName);
Phone = itemView.findViewById(R.id.phoneName);
Email = itemView.findViewById(R.id.paypalAddress);
Location = itemView.findViewById(R.id.location);
}
}
}
public class Model {
String Name,Phone,Location,MailAddress;
public Model(String name, String phone, String location, String mailAddress) {
Name = name;
Phone = phone;
Location = location;
MailAddress = mailAddress;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getMailAddress() {
return MailAddress;
}
public void setMailAddress(String mailAddress) {
MailAddress = mailAddress;
}
}
I working with an app but when I am trying to access firebase data the getter method of the POJO returns null. I can not access data and setup in RecyclerView
Here is what I did:
My Firebase Structure:
My app debugging mode:
My Book Class
public class Book {
private String bookId;
private String bookImage;
private String bookName;
private String writerName;
private String publisherName;
private String shortDesc;
public Book() {
}
public Book(String bookImage, String bookName,
String writerName, String publisherName,String shortDesc) {
this.bookImage = bookImage;
this.bookName = bookName;
this.writerName = writerName;
this.publisherName = publisherName;
this.shortDesc = shortDesc;
}
public Book(String bookId, String bookImage, String bookName,
String writerName, String publisherName, String shortDesc) {
this.bookId = bookId;
this.bookImage = bookImage;
this.bookName = bookName;
this.writerName = writerName;
this.publisherName = publisherName;
this.shortDesc = shortDesc;
}
public String getBookId() {
return bookId;
}
public String getBookImage() {
return bookImage;
}
public String getBookName() {
return bookName;
}
public String getWriterName() {
return writerName;
}
public String getPublisherName() {
return publisherName;
}
public String getShortDesc() {
return shortDesc;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
My BookListFragment where I'm showing my book list
public class BookListFragment extends Fragment {
private Button button1,button2,button3;
private RecyclerView bookListRv;
private ArrayList<Book> bookList;
private BookAdapter bookAdapter;
private String adminId;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
public BookListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_book_list, container, false);
init(view);
adminId = firebaseAuth.getUid();
Book book = new Book();
String bookid =book.getBookId();
configRV();
getBooks();
return view;
}
private void init(View view) {
bookListRv = view.findViewById(R.id.bookRVId);
firebaseAuth = firebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
bookList = new ArrayList<>();
bookAdapter = new BookAdapter(bookList, getContext());
}
private void configRV() {
bookListRv.setLayoutManager(new LinearLayoutManager(getContext()));
bookListRv.setAdapter(bookAdapter);
}
private void getBooks() {
DatabaseReference showBookRef = databaseReference.child("Books").child(adminId);
showBookRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot data:dataSnapshot.getChildren()){
Book book = data.getValue(Book.class);
bookList.add(book);
bookAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
My AddBookActivity
public class AddBookActivity extends AppCompatActivity {
private Button addBookBtn;
private ImageView bookIv;
private EditText bookNameEt,writerNameEt,publisherNameEt,shortDescEt;
private Uri imgUrl = null;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
private StorageReference imgReference;
private String adminId,imgUri="";
private FirebaseUser mFirebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
init();
if(mFirebaseUser!=null){
adminId = mFirebaseUser.getUid();
}
bookIv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,1);
}
});
addBookBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addBookData();
}
});
}
private void init() {
firebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = firebaseAuth.getCurrentUser();
imgReference = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference();
addBookBtn = findViewById(R.id.addBookBtnId);
bookIv = findViewById(R.id.addBookIvId);
bookNameEt = findViewById(R.id.addBookNameEtId);
writerNameEt = findViewById(R.id.addBookWriterNameEtId);
publisherNameEt = findViewById(R.id.addBookPublisherNameEtId);
shortDescEt = findViewById(R.id.addBookDescripEtId);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1 && resultCode==RESULT_OK){
if(data!=null){
imgUrl = data.getData();
bookIv.setImageURI(imgUrl);
}
}
}
private void addBookData() {
if (imgUrl!=null) {
final StorageReference filePath = imgReference.child("Book_images").child(String.valueOf(System.currentTimeMillis()));
filePath.putFile(imgUrl).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imgUri=uri.toString();
}
});
}
}
});
}
String bookName = bookNameEt.getText().toString();
String writerName = writerNameEt.getText().toString();
String publisherName = publisherNameEt.getText().toString();
String bookDesc = shortDescEt.getText().toString();
String bookImg = imgUri;
if(TextUtils.isEmpty(bookName) && TextUtils.isEmpty(writerName)
&& TextUtils.isEmpty(publisherName) && TextUtils.isEmpty(bookDesc) && TextUtils.isEmpty(bookImg)){
Toast.makeText(this,"Please Fill The Blank Field",Toast.LENGTH_LONG).show();
}
else if(!TextUtils.isEmpty(bookName) && !TextUtils.isEmpty(writerName)
&& !TextUtils.isEmpty(publisherName) && !TextUtils.isEmpty(bookDesc) && !TextUtils.isEmpty(bookImg)){
saveBook(bookImg,bookName,writerName,publisherName,bookDesc);
}
}
private void saveBook(String url, String bookName, String writerName, String publisherName, String bookDesc) {
DatabaseReference bookRef = databaseReference.child("Books").child(adminId);
String bookId = bookRef.push().getKey();
if(bookId!=null){
Book book = new Book(bookId,url,bookName,writerName,publisherName,bookDesc);
bookRef.child(bookId).child("BookInfo").setValue(book).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
}
}
My BookAdapter
public class BookAdapter extends RecyclerView.Adapter {
private List<Book> books;
private Context context;
public BookAdapter(List<Book> books, Context context) {
this.books = books;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Book currentBook = books.get(position);
// holder.bookIv.setIm(currentBook.getBookImage());
holder.bookNameTv.setText(currentBook.getBookName());
holder.writerNameTv.setText(currentBook.getWriterName());
holder.publisherNameTv.setText(currentBook.getPublisherName());
holder.shortDescTv.setText(currentBook.getShortDesc());
}
#Override
public int getItemCount() {
return books.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView bookNameTv,writerNameTv,publisherNameTv,shortDescTv;
private ImageView bookIv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
bookIv = itemView.findViewById(R.id.bookListIvId);
bookNameTv = itemView.findViewById(R.id.bookListNameTvId);
writerNameTv = itemView.findViewById(R.id.bookListWriterNameTvId);
publisherNameTv = itemView.findViewById(R.id.bookListPubNameTvId);
shortDescTv = itemView.findViewById(R.id.bookListShortDescTvId);
}
}
}
Now when I am debugging my app the debugger showing me the Book class reference book is all field null.
Any help me for appreciated
It's because you are creating book object in app and book is not fetched from firebase. You need to query for books using adminId
You have to go one more level deep to get BookInfo. Try using below code:
showBookRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()) {
Book book = data.child("BookInfo").getValue(Book.class);
bookList.add(book);
}
bookAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
You have to have your BookInfo directly outside i.e. YourRootId->SubId->YourInfo but this is what you have used as YourRootId->SubId->BookInfo->YourInfo (this is right if you want to retrieve only that particular data)
So First setup a FirebaseRecyclerAdapter
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("yourRootId/");
FirebaseRecyclerOptions<Book> options = FirebaseRecyclerOptions.Builder<Book>()
.setQuery(query, Book.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Book, BookHolder>(options) {
#Override
public BookHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.yourlayout, parent, false);
return new BookHolder(view);
}
#Override
protected void onBindViewHolder(BookHolder holder, int position, Book model) {
// assign all data in here
}
};
then create a viewholder
public class BookHolder extends RecyclerView.ViewHolder {
public LinearLayout root;
public TextView abc;
public TextView xyz;
public ViewHolder(View itemView) {
super(itemView);
abc= itemView.findViewById(R.id.list_title);
xyz= itemView.findViewById(R.id.list_desc);
}
}
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;
}
}
}
What could be wrong in my code? I use HashMap to make update easier in the database, but whenever I try to fetch this data from the database to FirebaseRecyclerAdapter I keep getting an error.
I have searched for many similar problems, tried their solutions but not working.
Below is the exception
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.project.android.designlibdemo.model.RecipeModel
Getter and setter
public class RecipeModel {
private String name;
public RecipeModel(){
}
public RecipeModel(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
ViewHolder class
public class ViewHolderRecipe extends RecyclerView.ViewHolder {
String LOG_TAG = ViewHolderRecipe.class.getSimpleName();
public View view;
private TextView ingredient_txt;
public ViewHolderRecipe(View itemView) {
super(itemView);
view = itemView;
ingredient_txt = itemView.findViewById(R.id.ingredient_list);
}
public void setRecipeName(String recipe){
ingredient_txt.setText(recipe);
}
How i send data to database
Map postRecipeMap = new HashMap();
final DatabaseReference sendRecp = FirebaseDatabase.getInstance().getReference().child
("Post").child("PostRecipe").push();
sendRecp.updateChildren(postRecipeMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mProgressDialog.dismiss();
AlertDialog.Builder alertDialogBuilder = new android.support.v7.app
.AlertDialog.Builder(PostingRecipeActivity.this);
alertDialogBuilder.setTitle("Successfully");
alertDialogBuilder.setMessage("You can click next");
alertDialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//Launch PostDetailActivity
Intent i = new Intent(PostingRecipeActivity.this, ContentIngredientList.class);
final String reportKey = sendRecp.getKey();
i.putExtra(ContentIngredientList.EXTRA_FIR_KEY, reportKey);
mProgressDialog.dismiss();
startActivity(i);
}
});
AlertDialog aDialog = alertDialogBuilder.create();
aDialog.show();
}
How I retrieve the data
public class ContentIngredientList extends AppCompatActivity {
public static final String EXTRA_FIR_KEY = "recipeKey";
private FirebaseRecyclerAdapter<RecipeModel, ViewHolderRecipe> mAdapter;
//private RecyclerView mIngredient_list;
String LOG_TAG = PostingRecipeActivity.class.getSimpleName();
private String recipeKey;
public ContentIngredientList(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_ingredient_list);
// Get post key from intent
recipeKey = getIntent().getStringExtra(EXTRA_FIR_KEY);
if (recipeKey == null) {
throw new IllegalArgumentException("Must pass EXTRA_POST_KEY");
}
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Post").child
("PostRecipe").child(recipeKey);
RecyclerView mRcyclerViewIngredient = findViewById(R.id.ingredient_list_recycler);
//mIngredient_list = findViewById(R.id.ingredient_list);
Log.e(LOG_TAG, "url" + mDatabase.getRef()) ;
// [END create_database_reference]
// mDirectionList.setHasFixedSize(true);
mRcyclerViewIngredient.setLayoutManager(new LinearLayoutManager(this));
// mIngredient_list.setHasFixedSize(true);
//mIngredient_list.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new FirebaseRecyclerAdapter<RecipeModel, ViewHolderRecipe>(RecipeModel.class,
R.layout.ingredient_posting, ViewHolderRecipe.class, mDatabase) {
#Override
protected void populateViewHolder(ViewHolderRecipe viewHolder, RecipeModel model, int position) {
viewHolder.setRecipeName(model.getName());
}
};
mRcyclerViewIngredient.setAdapter(mAdapter);
}
}
To get the list of post recepies, then your database shoundn't be:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Post").child
("PostRecipe").child(recipeKey);
But rather:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Post").child
("PostRecipe");
You were referencing a particular PostRecipe, then when Firebase UI tried to get the object it only found the string name.