I have a problem/ question. I want to save different objects to firebase realtime database every time I click a button, but I have a problem because, since I have a Shopping list I click more items and I want to save them to the database but it saves just the last item I clicked and I want to understand what I'm doing wrong. I'm new to Android / Firebase, it's the first time I'm doing it so if anyone can tell me what I'm doing wrong it would be awesome. Thank you so much. I will attach the code and the photo of the database.
Activity :
public class FirebaseSearch extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;
int position=0;
String searchText="";
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
public static int cart_count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firebasesearch);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");
mSearchField = findViewById(R.id.search_field);
mSearchBtn = findViewById(R.id.search_btn);
mResultList = findViewById(R.id.result_list_cart);
AddToCart = findViewById(R.id.imageButton2);
Cart = findViewById(R.id.cartButton);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
Cart.setOnClickListener(new View.OnClickListener() {
private Object Tag="Activity";
#Override
public void onClick(View v) {
if (cart_count < 1) {
} else {
startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
}
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
invalidateOptionsMenu();
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
String nome;
String surname;
Long prezzo;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);
addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Users a = new Users(nome,surname,prezzo);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Cart");
myRef.setValue(a);
}
});
}
public void getDetails(String name,String cognome,Long price){
nome=name;
surname=cognome;
prezzo=price;
}
public void setDetails(String name, String surname, Long price) {
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
TextView user_price = (TextView)mView.findViewById(R.id.price);
user_name.setText(name);
user_surname.setText(surname);
user_price.setText(Long.toString(price));
}
}
}
enter code here
You need to use the push() method:
myRef.push().setValue(a);
Currently the last data you are adding is overriding the data before it. The push() method will create a random ID and separate each user.
Or if you are using firebase authentication then you can use the user uid instead of push() to separate each user that you are saving.
Related
This is a list of qna in the firebase. I want to print this out.
But my output list doesn't show anything.
https://i.stack.imgur.com/6ctRB.png
QNA Activity
public class QnaActivity extends AppCompatActivity {
private RecyclerView qnaRv;
private ArrayList<ModelQna> qnaList;
private AdapterQna adapterQna;
private ImageButton writeBtn;
private ImageButton backbtn;
private TextView tabQnaTv;
private RelativeLayout QnaRl;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qna);
getSupportActionBar().hide();
qnaRv = findViewById(R.id.qnaRv);
tabQnaTv = findViewById(R.id.tabQnaTv);
QnaRl = findViewById(R.id.QnaRl);
backbtn = findViewById(R.id.backBtn);
writeBtn = findViewById(R.id.writeBtn);
firebaseAuth = FirebaseAuth.getInstance();
loadAllQna();
showQnaUI();
backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
writeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), AddQnaActivity.class);
startActivity(intent);
}
});
tabQnaTv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//load products
}
});
}
private void loadAllQna() {
qnaList = new ArrayList<>();
adapterQna = new AdapterQna(this, qnaList);
qnaRv.setAdapter(adapterQna);
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Employees");
reference.child(firebaseAuth.getUid()).child("Qna").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//before getting reset List
qnaList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
ModelQna modelQna = dataSnapshot.getValue(ModelQna.class);
qnaList.add(modelQna);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseerror) {
}
});
}
private void showQnaUI() {
//show orders ui and hide products ui
QnaRl.setVisibility(View.GONE);
}
}
Model
public class ModelFaq {
private String faqId,faqTitle,faqContent, timestamp,uid,faqCategory;
public ModelFaq() {
}
public ModelFaq(String faqId, String faqTitle, String faqContent, String timestamp, String uid, String faqCategory) {
this.faqId = faqId;
this.faqTitle = faqTitle;
this.faqContent = faqContent;
this.timestamp = timestamp;
this.uid = uid;
this.faqCategory = faqCategory;
}
public String getFaqId() {
return faqId;
}
public void setFaqId(String faqId) {
this.faqId = faqId;
}
public String getFaqTitle() {
return faqTitle;
}
public void setFaqTitle(String faqTitle) {
this.faqTitle = faqTitle;
}
public String getFaqContent() {
return faqContent;
}
public void setFaqContent(String faqContent) {
this.faqContent = faqContent;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getFaqCategory() {
return faqCategory;
}
public void setFaqCategory(String faqCategory) {
this.faqCategory = faqCategory;
}
}
Qna Adapter
public class AdapterQna extends RecyclerView.Adapter<AdapterQna.HolderQna> {
private Context context;
public ArrayList<ModelQna> qnaList;
public AdapterQna(Context context, ArrayList<ModelQna> qnaList) {
this.context = context ;
this.qnaList = qnaList ;
}
#NonNull
#Override
public HolderQna onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate layout
View view = LayoutInflater.from(context).inflate(R.layout.qna_item, parent, false);
return new HolderQna(view);
}
#Override
public void onBindViewHolder(#NonNull HolderQna holder, int position) {
ModelQna modelQna = qnaList.get(position);
String id = modelQna.getQnaId();
String uid = modelQna.getUid();
String qnaContent = modelQna.getQnaContent();
String qnaTitle = modelQna.getQnaTitle();
String timestamp = modelQna.getTimestamp();
//set data
holder.titleTextView.setText(qnaTitle);
holder.ContentTextView.setText(qnaContent);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle item clicks, show item details
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle item clicks, show item details
}
});
}
#Override
public int getItemCount() {
return qnaList.size();
}
class HolderQna extends RecyclerView.ViewHolder{
/*holds views of recyclerview*/
private TextView titleTextView, ContentTextView;
public HolderQna(#NonNull View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.item_post_title);
ContentTextView = itemView.findViewById(R.id.item_post_content);
}
}
}
Can you please change the code in your HolderQna to:
class HolderQna extends RecyclerView.ViewHolder{
/*holds views of recyclerview*/
private TextView titleTextView, ContentTextView;
public HolderQna(#NonNull View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.item_post_title);
ContentTextView = itemView.findViewById(R.id.item_post_content);
}
public void bind(qna: ModelQna){
titleTextView.setText(qna.qnaTitle);
ContentTextView.setText(qna.qnaContent);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle item clicks, show item details
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle item clicks, show item details
}
});
}
}
And your onBindViewHolder override of the AdapterQna to:
#Override
public void onBindViewHolder(#NonNull HolderQna holder, int position) {
ModelQna modelQna = qnaList.get(position);
String id = modelQna.getQnaId();
String uid = modelQna.getUid();
String qnaContent = modelQna.getQnaContent();
String qnaTitle = modelQna.getQnaTitle();
String timestamp = modelQna.getTimestamp();
//set data
holder.bind(modelQna);
}
Finally change your loadQna() function declaration as follows:
private void loadAllQna() {
qnaList = new ArrayList<>();
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Employees");
reference.child(firebaseAuth.getUid()).child("Qna").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//before getting reset List
qnaList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
ModelQna modelQna = dataSnapshot.getValue(ModelQna.class);
qnaList.add(modelQna);
}
adapterQna = new AdapterQna(this, qnaList);
qnaRv.setAdapter(adapterQna);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseerror) {
Log.e("QnaActivity", databaseError.toString());
}
});
}
As far as I can see in your screenshot, the Qna node it's not nested under any UID, but directly under the Employees node. So when you attach a listener to the following node:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Employees");
reference.child(firebaseAuth.getUid()).child("Qna").addValueEventListener(/*...*/);
You will not be able to get any results, because such a reference doesn't exist. To solve this, you either create a reference that points exactly to "Qna":
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference qnaRef = db.child("Employees").child("Qna");
qnaRef.addValueEventListener(/*...*/);
Or you move the "Qna" node under the UID of the user, and leave the code unchanged.
Besides that, there is also another problem. The name of the fields in your ModelFaq class are different than the name of the properties in your database. You have in your ModelFaq class four fields called faqId, faqTitle, faqContent, faqCategory, all starting with faq while in the database I see that the names are different, qnaId, qnaTitle, qnaContent, qnaCategory, all are starting wiht qna, and this is not correct. So in order to be able to map a node into an object of type ModelFaq, the names must match. The only two fields that match are the timestamp and the uid.
In this case, you have two solutions. The first one would to change the name of your fieds in the ModelFaq class according to what it already exists in the database or you can use the PropertyName annotation in front of the getters like this:
#PropertyName("qnaId")
public String getFaqId() {
return faqId;
}
I have Cart activity where user can add,update and delete their cart. Each of the function has it owns java activity and I also have CartAdapter activity. I want to perform a calculation that can display the total price of customer item in the ViewCart activity. I did the calculation on CartAdapter but I have a problem with displaying the totalPrice inside my ViewCart activity.
I got error that said
java.lang.NumberFormatException: For input string: "99.00"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.valueOf(Integer.java:801)
at com.example.g.Customer.CartAdapter.onBindViewHolder(CartAdapter.java:68)
at com.example.g.Customer.CartAdapter.onBindViewHolder(CartAdapter.java:28)
Here is my CartAdapter
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.MyViewHolder> {
private Context context;
List<String> key;
ArrayList<Cart> CartList;
int totalPrice = 0;
int totalPrice1 = 0;
public CartAdapter(ArrayList<Cart> CartListList) {
this.CartList = CartListList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cust_view_cart, viewGroup, false);
context = viewGroup.getContext();
return new CartAdapter.MyViewHolder(view);
}
#NonNull
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
Picasso.with(context).load(CartList.get(i).getPro_image()).into(myViewHolder.image);
myViewHolder.name.setText(CartList.get(i).getPro_name());
myViewHolder.category.setText(CartList.get(i).getPro_category());
myViewHolder.price.setText(CartList.get(i).getPro_price());
myViewHolder.size.setText(CartList.get(i).getSize());
myViewHolder.quantity.setText(CartList.get(i).getQuantity());
totalPrice1 = (int)Double.parseDouble((CartList.get(i).getPro_price())) * Integer.valueOf(CartList.get(i).getQuantity());
totalPrice = totalPrice + totalPrice1;
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cart_id = CartList.get(i).getCart_id();
String keyB = CartList.get(i).getBrand_id();
String pid = CartList.get(i).getPro_id();
String cust_id = CartList.get(i).getCust_id();
String name = CartList.get(i).getPro_name();
String category = CartList.get(i).getPro_category();
String price = CartList.get(i).getPro_price();
String image = CartList.get(i).getPro_image();
String size = CartList.get(i).getSize();
String quantity = CartList.get(i).getQuantity();
Intent intent = new Intent(context, UpdateCart.class);
intent.putExtra("cust_id", cust_id);
intent.putExtra("Cart_id", cart_id);
intent.putExtra("keyB", keyB);
intent.putExtra("pid", pid);
intent.putExtra("pro_name", name);
intent.putExtra("pro_category", category);
intent.putExtra("pro_price", price);
intent.putExtra("pro_image", image);
intent.putExtra("size", size);
intent.putExtra("quantity", quantity);
context.startActivity(intent);
}
});
myViewHolder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pro_name = CartList.get(i).getPro_name();
String cart_id = CartList.get(i).getCart_id();
String cust_id = CartList.get(i).getCust_id();
DatabaseReference dbCart = FirebaseDatabase.getInstance().getReference("Cart").child(cust_id);
dbCart.child(cart_id).removeValue();
//set url of image to storageref
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl(CartList.get(i).getPro_image());
// Delete the file
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception exception) {
// Uh-oh, an error occurred!
}
});
//Toolbar
// Remove the item on remove/button click
CartList.remove(i);
/*
Parameters
position : Position of the item that has now been removed
*/
notifyItemRemoved(i);
/*
Parameters
positionStart : Position of the first item that has changed
itemCount : Number of items that have changed
*/
notifyItemRangeChanged(i, CartList.size());
// Show the removed item label
Toast.makeText(context, pro_name + " has been removed from your cart", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return CartList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name, category, price, size, quantity;
ImageView image, btnDelete;
public MyViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
category = itemView.findViewById(R.id.category);
image = itemView.findViewById(R.id.image);
price = itemView.findViewById(R.id.price);
size = itemView.findViewById(R.id.size);
quantity = itemView.findViewById(R.id.quantity);
btnDelete = itemView.findViewById(R.id.delete);
}
}
}
ViewCart
public class ViewCart extends AppCompatActivity {
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
FirebaseUser currentUser;
ArrayList<Cart> CartList;
RecyclerView recyclerView;
private int totalPrice = 0;
TextView total;
private String userID, cust_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_cart);
total = findViewById(R.id.total);
total.setText( String.valueOf(totalPrice));
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
if (currentUser != null) {
userID = currentUser.getUid();
cust_id = firebaseAuth.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("Cart").child(cust_id);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
CartList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CartList.add(ds.getValue(Cart.class));
}
CartAdapter cartAdapter = new CartAdapter(CartList);
recyclerView.setAdapter(cartAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else
openDialog();
}
private void openDialog() {
LoginDialog loginlDialog = new LoginDialog();
loginlDialog.show(getSupportFragmentManager(), "login dialog");
}
use this
public class ViewCart extends AppCompatActivity {
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
FirebaseUser currentUser;
ArrayList<Cart> CartList;
RecyclerView recyclerView;
private int totalPrice = 0;
TextView total;
private String userID, cust_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_cart);
total = findViewById(R.id.total);
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
if (currentUser != null) {
userID = currentUser.getUid();
cust_id = firebaseAuth.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("Cart").child(cust_id);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
CartList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CartList.add(ds.getValue(Cart.class));
Cart cart = ds.getValue(Cart.class);
totalPrice = totalPrice + (int)Double.parseDouble(cart.getPrice()) * Integer.valueOf(cart.getQuantity());
}
CartAdapter cartAdapter = new CartAdapter(CartList);
recyclerView.setAdapter(cartAdapter);
total.setText( String.valueOf(totalPrice));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else
openDialog();
}
private void openDialog() {
LoginDialog loginlDialog = new LoginDialog();
loginlDialog.show(getSupportFragmentManager(), "login dialog");
}
Why have you kept price as String , instead of float or int?
You probably have kept price as String so that you can display it in TextView, but with this you are forced to cast it every time.
You should keep price as float and to set it as text in TextView simply use string concatenation :
float price = 99.00;
textView.setText(value+ "");
I got two RecyclerView on the same page at this moments which are Breakfast and Lunch RecyclerView but I am facing the following error Can't convert object of type java.lang.String to type com.example
It highlights this line
userRecordslist.add(ds.getValue(UserRecordsModel.class));
I have tried several ways.
but when I used this code , the data from different record was displayed in the Breakfast RecyclerView
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record);
these are the screenshots of my Firebase and my App. You can see both data from different record is displayed on the same RecyclerView.
and later I tried to use this "new" code for database reference, the data that was supposedly retrieved from Firebase was NOT be displayed on the Breakfast Recycler View and I got the Can't convert object of type java.lang.String to type error
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("BreakfastRecord");
I want to fetch the data and display it in the "suppose" RecyclerView. Please help out.
This code for my PlanMeal activity:
//BUTTON
Button backBtn;
Button addMealBreakBtn;
Button addMealLunchBtn;
Button addMealDinnerBtn;
//DATABASE
FirebaseAuth mAuth;
FirebaseUser currentUser;
DatabaseReference userRecordRef, myRef,requiredCalorieRef, mylunchRef;
//TEXT VIEW
TextView userRequiredCalorie;
ArrayList<UserRecordsModel> userRecordslist;
RecyclerView recyclerView, recyclerViewlunch;
private RecyclerView.Adapter userRecordHolder;
//DATE
String date_record ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plan_meal_user);
date_record = new SimpleDateFormat("yyMMdd", Locale.getDefault()).format(new Date());
//create a date string.
String date_n = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault()).format(new Date());
//get hold of textview.
TextView date = (TextView) findViewById(R.id.datePlanMeal);
//set it as current date.
date.setText(date_n);
//INI VIEWS
userRequiredCalorie= (TextView) findViewById(R.id.outputPlanMealCalorie);
//FIREBASE AUTH
mAuth = FirebaseAuth.getInstance();
currentUser=mAuth.getCurrentUser();
//DATABASE REFERENCE
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record);
/*mylunchRef=FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("LunchRecord");*/
//myRef = FirebaseDatabase.getInstance().getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//mylunchRef = FirebaseDatabase.getInstance().getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//RECYCLER VIEW
//*********BREAKFAST******************************************//
recyclerView = findViewById(R.id.userRecordRecylerView);
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
//ADAPTER
userRecordslist = new ArrayList<>();
userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerView.setAdapter(userRecordHolder);
//*********LUNCH******************************************//
recyclerViewlunch = findViewById(R.id.userRecordRecylerViewLunch);
LinearLayoutManager manager1 = new LinearLayoutManager(this);
recyclerViewlunch.setLayoutManager(manager1);
recyclerViewlunch.setHasFixedSize(true);
//ADAPTER
userRecordslist = new ArrayList<>();
userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerViewlunch.setAdapter(userRecordHolder);
//BUTTON
addMealBreakBtn = (Button) findViewById(R.id.addMealBreakBtn);
backBtn = (Button)findViewById(R.id.backBtnPlan) ;
//**********************DATABASE REFERENCE FOR USER REQUIRED CALORIE***************************//
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
userRequiredCalorie.setText((userCalorieSuggestion +"kcal"));
/*String userCalorieSuggestion = Double.toString((Double) dataSnapshot.child("daily calorie").getValue());
showDailyCalorie.setText(("Daily Calorie Suggestion: " + userCalorieSuggestion +"kcal"));*/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//BACK BUTTON*************************************************
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,HomepageUser.class);
startActivity(signIn);
}
});
//ADD MEAL BUTTONS**********************************************
addMealBreakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent breakfast = new Intent(PlanMealUser.this,ViewProduct.class);
startActivity(breakfast);
}
});
addMealLunchBtn = (Button) findViewById(R.id.addMealLunchBtn);
addMealLunchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,ViewProduct_Lunch.class);
startActivity(signIn);
}
});
addMealDinnerBtn = (Button) findViewById(R.id.addMealDinnerBtn);
addMealDinnerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,ViewProduct.class);
startActivity(signIn);
}
});
}
#Override
protected void onStart() {
super.onStart();
if (myRef != null) {
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userRecordslist = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userRecordslist.add(ds.getValue(UserRecordsModel.class));
}
UserRecordsHolder userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerView.setAdapter(userRecordHolder);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(PlanMealUser.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
This is my Model :
package com.example.buddymealplanneruser.Child.UserRecords;
public class UserRecordsModel {
private String foodName;
private String foodCalorie;
//constructor
public UserRecordsModel (String foodName,
String foodCalorie
)
{
this.foodName = foodName;
this.foodCalorie = foodCalorie;
}
public UserRecordsModel(){
}
//Getter and Setter
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getFoodCalorie() {
return foodCalorie;
}
public void setFoodCalorie(String foodCalorie) {
this.foodCalorie = foodCalorie;
}
}
This is my Adapter
public class UserRecordsHolder extends RecyclerView.Adapter<UserRecordsHolder.MyURHolder> {
Context context;
ArrayList<UserRecordsModel> userRecordslist;
public UserRecordsHolder (ArrayList<UserRecordsModel> userRecordslist)
{
this.userRecordslist=userRecordslist;
}
#NonNull
#Override
public MyURHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_user_records, viewGroup,false);
return new MyURHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyURHolder myURHolder, int i) {
myURHolder.foodName.setText(userRecordslist.get(i).getFoodName());
myURHolder.foodCalorie.setText(userRecordslist.get(i).getFoodCalorie());
}
#Override
public int getItemCount()
{
return userRecordslist.size();
}
class MyURHolder extends RecyclerView.ViewHolder
{
TextView foodName, foodCalorie;
public MyURHolder (#NonNull View itemView){
super(itemView);
foodName = itemView.findViewById(R.id.userRecordsFName);
foodCalorie = itemView.findViewById(R.id.userRecordsKcal);
}
}
}
Hope someone can help.
You'll need one more level beneath BreakfastRecord or LunchRecord:
UserRecords
UID
Date
BreakfastRecord
1
foodCalorie
foodName
2
foodCalorie
foodName
3
foodCalorie
foodName
I'm building an app as college project for Blood Donation where user can register using Firebase authentication Email and Password and can post request for Blood which is then added to Firebase DataBase which is shown in Recycle view inside an app
I'was able to complete that part.
Now I want to add button which will be visible in the recycle view with option to delete the request if He wish in case he received call from donor or if he no longer in need. But this button should only be visible to user who has posted for request and will remain hidden for other help post inside recycle adapter.
and when he click the button it should delete the particular Data from Firebase Database also.
To summarize.
1. I need button visible only to user who has posted the help request which will delete the post if he wish to
On click event of that Button, will also delete the particular post from Firebase Database
I'm using Firebase authentication sing in of Email and Password.
Here is the Firebase Database Structure
Here is the Code where user wants to upload the Help request and is added
to firebase Data as well
public class EnquiryActivity extends AppCompatActivity {
//UI
Button btnRequest;
EditText edtName,edtBlood,edtPlace,edtMobile,edtEmail;
//DB
DatabaseReference mHelper;
FirebaseAuth mAuth;
//progress
ProgressDialog mProgress;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enquiry);
//initialisation
edtBlood=(EditText)findViewById(R.id.enq_blood);
edtMobile=(EditText)findViewById(R.id.enq_mobile);
edtEmail=(EditText)findViewById(R.id.enq_email);
edtName=(EditText)findViewById(R.id.enq_name);
edtPlace=(EditText)findViewById(R.id.enq_place);
btnRequest=(Button)findViewById(R.id.button2);
//firebase
mHelper= FirebaseDatabase.getInstance().getReference();
final String mCurrentUser=FirebaseAuth.getInstance().getCurrentUser().getUid().toString();
mAuth=FirebaseAuth.getInstance();
//progress
mProgress=new ProgressDialog(this);
mProgress.setTitle("Loading");
mProgress.setMessage("Please wait..");
btnRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProgress.show();
String blood=edtBlood.getText().toString();
String name=edtName.getText().toString();
String mobile=edtMobile.getText().toString();
String email=edtMobile.getText().toString();
String place=edtPlace.getText().toString();
String temp=blood.toUpperCase();
if(!TextUtils.isEmpty(blood)||!TextUtils.isEmpty(name)||!TextUtils.isEmpty(mobile)||
!TextUtils.isEmpty(place)){
HashMap<String, String> userMap = new HashMap<>();
userMap.put("name", name);
userMap.put("blood_group","Blood Group:- " + blood);
userMap.put("email", email);
userMap.put("mobile", mobile);
userMap.put("place","Location:- " + place);
mHelper.child("Help").child(mCurrentUser).setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mProgress.dismiss();
Toast.makeText(getApplicationContext(), "Registered Successfully..!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
}else{
Toast.makeText(getApplicationContext(),"Please enter the details in all fields",Toast.LENGTH_LONG).show();
}
}
});
}
}
Here is the Code where list of help post is show including user who has posted of his/her own
* A simple {#link Fragment} subclass.
*/
public class NeedHelpFragment extends Fragment {
FloatingActionButton floatingActionButton;
private View mMainView;
private RecyclerView mHelpList;
private DatabaseReference mUsersDatabase;
private DatabaseReference mUsers;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
public NeedHelpFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mMainView = inflater.inflate(R.layout.fragment_need_help, container, false);
floatingActionButton = (FloatingActionButton) mMainView.findViewById(R.id.float_add);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), EnquiryActivity.class));
}
});
//init
mHelpList = (RecyclerView) mMainView.findViewById(R.id.need_recyclerview);
mAuth = FirebaseAuth.getInstance();
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Help");
mUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mCurrent_user_id = mAuth.getCurrentUser().getUid();
//
mHelpList.setHasFixedSize(true);
LinearLayoutManager linearVertical = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mHelpList.setLayoutManager(linearVertical);
DividerItemDecoration mDividerItemDecoration = new DividerItemDecoration(
mHelpList.getContext(),
linearVertical.getOrientation()
);
mHelpList.addItemDecoration(mDividerItemDecoration);
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Help, HelpViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Help, HelpViewHolder>(
Help.class,
R.layout.help_single_layout,
HelpViewHolder.class,
mUsersDatabase) {
#Override
protected void populateViewHolder(final HelpViewHolder helpViewHolder, Help help, int i) {
helpViewHolder.setDate(help.getDate());
final String list_user_id = getRef(i).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String blood = dataSnapshot.child("blood_group").getValue().toString();
final String phone = dataSnapshot.child("mobile").getValue().toString();
final String email = dataSnapshot.child("email").getValue().toString();
String address = dataSnapshot.child("place").getValue().toString();
helpViewHolder.setName(userName);
helpViewHolder.setBlood(blood);
helpViewHolder.setAddress(address);
helpViewHolder.setPhone(phone);
helpViewHolder.setEmail(email);
helpViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{"Email", "Call"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if (i == 0) {
}
if (i == 1) {
String uri = phone;
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
}
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mHelpList.setAdapter(friendsRecyclerViewAdapter);
}
// viewholder class..
public static class HelpViewHolder extends RecyclerView.ViewHolder {
View mView;
public HelpViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setBlood(String blood){
TextView userStatusView = (TextView) mView.findViewById(R.id.help_blood);
userStatusView.setText(blood.toUpperCase());
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.help_name);
userNameView.setText(name.toUpperCase());
}
public void setPhone(String phone){
TextView userNameView = (TextView) mView.findViewById(R.id.help_mobile);
userNameView.setText(phone);
}
public void setEmail(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.help_email);
userNameView.setText(name.toUpperCase());
}
public void setAddress(String address) {
TextView userNameView = (TextView) mView.findViewById(R.id.help_place);
address.toUpperCase();
userNameView.setText(address.toUpperCase());
}
public void setDate(String date){
}
}
}
Any help is well appreciated
Thanks in advance.
Add delete button in your help_single_layout . And add a new key posted in firebase database to check whether this user posted or not . On that basis , you can define visibiltiy of Delete button.
I am developing an android application with firebase as my database. I want to insert some data on the press of a button, but some of the objects I want to insert in the database, is placed in different methods in my fragment. How can I insert data to my database across different methods using the same button?
public class mFragment extends Fragment implements
DateFragment.DatePickerEvent {
DatabaseReference database;
FirebaseAuth mAuth;
EditText text1;
EditText text2;
#Override
public void onDateSelected(String date) {
Button buttonDateText = (Button) getView().findViewById(R.id.buttonDate);
buttonDateText.setText(date);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_frag, container, false);
database = FirebaseDatabase.getInstance().getReference("Persons");
mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
Button pickDateButton = (Button) rootView.findViewById(R.id.buttonDate);
Button submitButton = (Button) rootView.findViewById(R.id.buttonSubmit);
text1= (EditText) rootView.findViewById(R.id.oddsView);
text2= (EditText) rootView.findViewById(R.id.betAmountView);
pickDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DateFragment picker = new DateFragment();
picker.setDatePickerEvents(mFragment.this);
picker.show(getFragmentManager(), "datePicker");
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
database.child("Person").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String myText= text1.getText().toString().trim();
String myAnotherText= text2.getText().toString().trim();
String id = database.push().getKey();
database.child(user.getDisplayName()).child(id).child("Adress").setValue(myText);
database.child(user.getDisplayName()).child(id).child("name").setValue(myAnotherText);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
return rootView;
}
}
You can use instance variables. Something like that:
public class MyFrag extends Fragment {
private Object obj1, obj2;
private void method1() {
obj1 = new Object();
}
private void method2() {
obj2 = new Object();
}
private void doSomething() {
// obj1 and obj2 are available here
}
}