I am trying to display some Firebase records in an Android ListView. At present, my code is returning a solitary 0 to the ListView when I go to enter a new record, however my Firebase database is displaying the information that I want perfectly.
I have spent quite a bit of time over this issue and can't quite seem to pinpoint the problem.
Any help on this would be much appreciated.
Below is my code for displaying/adding new records:
TenantList tenantListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_tenants);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String uid = user.getUid();
//databaseTenantsList = FirebaseDatabase.getInstance().getReference("tenants").child(uid);
textViewPropertyName = (TextView) findViewById(R.id.textViewPropertyName);
editTextTenantsName = (EditText) findViewById(R.id.editTextTenantsName);
seekBarAge = (SeekBar) findViewById(R.id.seekBarAge);
buttonAddTenant = (Button) findViewById(R.id.buttonAddTenant);
listViewTenants = (ListView) findViewById(R.id.listViewTenants);
tenants = new ArrayList<>();
tenantListAdapter = new TenantList(this, tenants);
listViewTenants.setAdapter(tenantListAdapter);
Intent intent = getIntent();
tenants = new ArrayList<>();
String id = intent.getStringExtra(PropertyActivity.PROPERTY_ID);
String name = intent.getStringExtra(PropertyActivity.PROPERTY_NAME);
textViewPropertyName.setText(name);
databaseTenants = FirebaseDatabase.getInstance().getReference("tenants").child(uid).child(id).child(uid);
//databaseTenants = FirebaseDatabase.getInstance().getReference("tenants").child(id);
buttonAddTenant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveTenant();
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseTenants.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tenants.clear();
for(DataSnapshot tenantSnapshot : dataSnapshot.getChildren()){
Tenant tenant = tenantSnapshot.getValue(Tenant.class);
tenants.add(tenant);
}
tenantListAdapter.notifyDatasetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void saveTenant() {
String tenantName = editTextTenantsName.getText().toString().trim();
int age = seekBarAge.getProgress();
if(!TextUtils.isEmpty(tenantName)){
String id = databaseTenants.push().getKey();
Tenant tenant = new Tenant(id, tenantName, age);
FirebaseUser user = mAuth.getCurrentUser();
String uid = user.getUid();
databaseTenants.child(uid).child(id).setValue(tenant);
Toast.makeText(this, "Tenant saved successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Tenant name should not be empty", Toast.LENGTH_LONG).show();
}
}
}
TenantList
public class TenantList extends ArrayAdapter<Tenant> {
private Activity context;
private List<Tenant> tenants;
public TenantList(Activity context, List<Tenant> tenants) {
super(context, R.layout.tenant_list_layout, tenants);
this.context = context;
this.tenants = tenants;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.tenant_list_layout, null, true);
TextView textViewTenant = (TextView) listViewItem.findViewById(R.id.textViewTenant);
TextView textViewAge = (TextView) listViewItem.findViewById(R.id.textViewAge);
Tenant tenant = tenants.get(position);
textViewTenant.setText(tenant.getTenantName());
textViewAge.setText(String.valueOf(tenant.getTenantAge()));
return listViewItem;
}
}
To add a bit more context, here is my data structure:
From what I'm seeing there's still one level until you get to the tennat object.
databaseTenants = FirebaseDatabase.getInstance().getReference("tenants").child(uid).child(id).child(uid);
Also, pull your adapter creation to the onCreate method so you can access it globally:
Add a member variable:
TenantList tenantListAdapter
and initialize it after your listview, pull the tennants to before the adapter instantiation so you can access it:
listViewTenants = (ListView) findViewById(R.id.listViewTenants);
tenants = new ArrayList<>();
tenantListAdapter = new TenantList(this, tenants);
listViewTenants.setAdapter(tenantListAdapter);
Then, in your event listener just do:
databaseTenants.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tenants.clear();
for(DataSnapshot tenantSnapshot : dataSnapshot.getChildren()){
for(DataSnapshot lastSnapshot: tenantSnapshot.getChildren()){
Tenant tenant = lastSnapshot.getValue(Tenant.class);
tenants.add(tenant);
}
}
tenantListAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
I kinda confused, how to get specific name inside child key, i only know set recyclerview, but don't know how to get grandprice set to TextView, because grandprice is inside another child, my database down below.
key is CardView and grandprice is TextView.
this is my code
//RecyclerView
mRecyclerView = view.findViewById(R.id.recommeneded);
mRecyclerView.setHasFixedSize(true);
//mRecyclerView.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
final RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1);
mRecyclerView.setLayoutManager(mLayoutManager);
mProgressBar = view.findViewById(R.id.myDataLoaderProgressBar);
mProgressBar.setVisibility(View.VISIBLE);
final int position = 0;
recommended = new ArrayList<>();
mAdapter = new InvoiceAdapter(getActivity(), recommended);
mRecyclerView.setAdapter(mAdapter);
//mAdapter.setOnItemClickListener(HomeActivity.this);
rootRef = FirebaseDatabase.getInstance().getReference();
usersRef = rootRef.child("order");
uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDBListener = usersRef.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
recommended.clear();
for (DataSnapshot invoiceSnapshot : dataSnapshot.getChildren()) {
InvoiceModels upload = invoiceSnapshot.getValue(InvoiceModels.class);
upload.setKey(invoiceSnapshot.getKey());
recommended.add(position, upload);
}
mAdapter.notifyDataSetChanged();
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressBar.setVisibility(View.INVISIBLE);
}
});
//RecyclerView
my adapter
#Override
public void onBindViewHolder(RecyclerViewHolder holder, final int position) {
InvoiceModels currentProduct = recomended.get(position);
//holder.totalPrice.setText(currentProduct.getTotalPrice());
Toast.makeText(mContext, currentProduct.getTotalPrice(), Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return recomended.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView totalPrice;
public RelativeLayout relativelayout;
public RecyclerViewHolder(View itemView) {
super(itemView);
totalPrice = itemView.findViewById(R.id.totalPrice);
relativelayout = (RelativeLayout) itemView.findViewById(R.id.relativeLayout);
}
}
Thank for helping, sincerely,
AL.
First you need to get the id of that inv-details. Next you can call the data inside it. You can try this.
recommended.clear();
//At here you get the id first.
final String keyOfChild = dataSnapshot.getKey();
usersRef.child(uid).child(keyOfChild).child("inv-details").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
InvoiceModels upload = dataSnapshot.getValue(InvoiceModels.class);
upload.setKey(invoiceSnapshot.getKey());
recommended.add(position, upload);
mAdapter.notifyDataSetChanged();
mProgressBar.setVisibility(View.GONE);
}
I am making an app based on firebase Realtime database.
I want my database structure like the tree given below:-
I am trying to get that data written in my firebase Realtime database by the following java code:-
public class AddActivity extends AppCompatActivity {
private EditText etName;
EditText etRoll;
Button btnAdmit;
Button btnView;
String stName;
String stRoll;
FirebaseDatabase myfire;
DatabaseReference myRef;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
etName = (EditText) findViewById(R.id.idUser);
etRoll = (EditText) findViewById(R.id.idPass);
btnView = (Button) findViewById(R.id.idView);
btnAdmit= (Button) findViewById(R.id.idAdmit);
myfire = FirebaseDatabase.getInstance();
myRef = myfire.getReference("Users")
.child("uid");// I dont know what
// to write in this child
// in stead of
// "uid"
btnAdmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stName = etName.getText().toString();
stRoll = etRoll.getText().toString();
etName.setText("");
etRoll.setText("");
myRef.child("101").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
model model =new basic();
model.setFb01name(stName);
model.setFb04roll(stRoll);
myRef.setValue(model);
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.toast_id));
TextView text = (TextView) layout.findViewById(R.id.idToast);
text.setText("Added.");
Toast toast = new Toast(AddActivity.this);
toast.setGravity(Gravity.CENTER ,0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
// btnAdmit.setEnabled(false);
// btnAdmit.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.toast_id));
TextView text = (TextView) layout.findViewById(R.id.idToast);
text.setText(" Database Error.");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER ,0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
DatabaseError e = null;
Log.e("Database", "Error", e.toException());
}
});
}
});
My model class goes like this:
public class model {
String fb01name;
String fb04roll;
public model() {
}
public model(String fb01name, String fb04roll) {
this.fb01name = fb01name;
this.fb04roll = fb04roll;
}
public String getFb01name() {
return fb01name;
}
public void setFb01name(String fb01name) {
this.fb01name = fb01name;
}
public String getFb04roll() {
return fb04roll;
}
public void setFb04roll(String fb04roll) {
this.fb04roll = fb04roll;
}
}
There is nothing in logcat error message. I am getting nothing written in the firebase Realtime database.
I am not able to find the error. The app is displaying the toast "added" as given in on data change method. My database rules are like this:
{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data
"rules": {
"Users": {
"$uid": {
".read": true,
// or ".read": "auth.uid != null" for only authenticated users
".write": "auth.uid == $uid"
}
}
}
}
Please look into the matter and provide your insight and practical solution.
Try below code
public class AddActivity extends AppCompatActivity {
private EditText etName;
EditText etRoll;
Button btnAdmit;
Button btnView;
String stName;
String stRoll;
FirebaseDatabase myfire;
DatabaseReference myRef;
#Override
public void onBackPressed() {
}
private String getUID() {
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
if (mUser != null) {
String strUID = mUser.getUid();
if (!TextUtils.isEmpty(strUID)) {
return strUID;
}
}
return "";
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
etName = (EditText) findViewById(R.id.idUser);
etRoll = (EditText) findViewById(R.id.idPass);
btnView = (Button) findViewById(R.id.idView);
btnAdmit = (Button) findViewById(R.id.idAdmit);
myfire = FirebaseDatabase.getInstance();
String strUID = getUID();
if (TextUtils.isEmpty(strUID)) {
//handle case of null UID
}
myRef = myfire.getReference("Users/" + strUID);
btnAdmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stName = etName.getText().toString();
stRoll = etRoll.getText().toString();
etName.setText("");
etRoll.setText("");
myRef.child("101").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
model model = new basic();
model.setFb01name(stName);
model.setFb04roll(stRoll);
myRef.setValue(model);
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.toast_id));
TextView text = (TextView) layout.findViewById(R.id.idToast);
text.setText("Added.");
Toast toast = new Toast(AddActivity.this);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
// btnAdmit.setEnabled(false);
// btnAdmit.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.toast_id));
TextView text = (TextView) layout.findViewById(R.id.idToast);
text.setText(" Database Error.");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
DatabaseError e = null;
Log.e("Database", "Error", e.toException());
}
});
}
});
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.