My firebase Realtime database path is not working - java

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());
}
});
}
});

Related

Always null value passed from fragment to adapter

I have a recycler view on my home page which is showing some posts from my db. I'm passing data like userID, username etc., into the adapter but the profile picture URL is always null inside the adapter. If I try to print it inside the fragment it shows the correct value.
My database structure:
PostRecyclerAdapter:
public class PostRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.ViewHolder> {
List<PostModel> postList;
Context context;
final private DatabaseReference postRef = FirebaseDatabase.getInstance().getReference("posts");
final private DatabaseReference likeRef = FirebaseDatabase.getInstance().getReference("likes");
final private DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
public PostRecyclerAdapter(ArrayList<PostModel> postModelArrayList, Context context) {
this.postList = postModelArrayList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// check if post is liked or not
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
// check if current post is liked from this user
if (snapshot.child(holder.id).hasChild(user.getUid())) {
// post is liked form this user
holder.like_btn.setImageResource(R.drawable.ic_thumb_up_filled);
} else {
// post is not liked from this user
holder.like_btn.setImageResource(R.drawable.ic_thump_up_outline);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "error: " + error, Toast.LENGTH_SHORT).show();
}
});
// Get current post id set username, authorID, profile picture URL, likes and post image URL
holder.id = postList.get(position).getId();
holder.username.setText(postList.get(position).getName());
holder.userID = postList.get(position).getAuthorID();
holder.like_counter_tv.setText(postList.get(position).getLikes());
Glide.with(context).load(postList.get(position).getImgUrl()).into(holder.postImg);
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
// profilePictureUrl IS ALWAYS NULL
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(holder.profileImage);
}
}
}
#Override
public int getItemCount() {
return postList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
CardView container;
String id;
TextView username, like_counter_tv;
ImageView postImg;
ImageButton like_btn;
CircleImageView profileImage;
boolean isLiked = false;
String userID;
public void updateLikes(String postID, boolean isNotLiked) {
postRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
String currentLikesToString = snapshot.child(postID).child("likes").getValue().toString();
int currentLikesToInt = Integer.parseInt(currentLikesToString);
if (isNotLiked) {
int newCurrentLikes = currentLikesToInt + 1;
String newCurrentLikesToString = Integer.toString(newCurrentLikes);
// Update likes on Real-time DB
postRef.child(postID).child("likes").setValue(newCurrentLikesToString);
// update likes on TextView
like_counter_tv.setText(newCurrentLikesToString);
} else {
int newCurrentLikes = currentLikesToInt - 1;
String newCurrentLikesToString = Integer.toString(newCurrentLikes);
// Update likes on Real-time DB
postRef.child(postID).child("likes").setValue(newCurrentLikesToString);
// update likes on TextView
like_counter_tv.setText(newCurrentLikesToString);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
}
public ViewHolder(#NonNull View itemView) {
super(itemView);
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
final ConstraintLayout sContainer = itemView.findViewById(R.id.second_container);
profileImage = itemView.findViewById(R.id.user_profile_image);
container = itemView.findViewById(R.id.post_item_container);
username = itemView.findViewById(R.id.post_username);
postImg = itemView.findViewById(R.id.post_image);
like_btn = itemView.findViewById(R.id.likeBtn);
like_counter_tv = itemView.findViewById(R.id.like_counter);
likeRef.keepSynced(true);
profileImage.setOnClickListener(v -> {
Intent intent = new Intent(context, UserProfileActivity.class);
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snap : snapshot.getChildren()) {
if (snap.child("name").getValue().toString().equals(username.getText().toString())) {
UserProfileActivity.username = username.getText().toString();
UserProfileActivity.userID = snap.child("id").getValue().toString();
break;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(context, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
context.startActivity(intent);
});
sContainer.setOnLongClickListener(v -> {
FragmentManager manager = ((AppCompatActivity) context).getSupportFragmentManager();
PostOptionsDialog optionsDialog = new PostOptionsDialog();
optionsDialog.setPostId(id);
if (username.getText().toString().equals(user.getDisplayName())) {
optionsDialog.setAuthor(true);
} else {
optionsDialog.setAuthor(false);
}
optionsDialog.show(manager, "options");
return false;
});
like_btn.setOnClickListener(v -> {
// animate like button when clicked
YoYo.with(Techniques.Shake)
.duration(500)
.repeat(0)
.playOn(like_btn);
isLiked = true;
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (isLiked) {
if (snapshot.child(id).hasChild(user.getUid())) {
// post is liked from this user, so user wants to unlike this post
like_btn.setImageResource(R.drawable.ic_thump_up_outline);
likeRef.child(id).child(user.getUid()).removeValue();
isLiked = false;
Toast.makeText(context, "You unliked this meme!", Toast.LENGTH_SHORT).show();
// update likes to DB
updateLikes(id, false);
} else {
// post is not liked from ths user, so the user wants to like this post
like_btn.setImageResource(R.drawable.ic_thumb_up_filled);
likeRef.child(id).child(user.getUid()).setValue("true");
Toast.makeText(context, "You liked this meme!", Toast.LENGTH_SHORT).show();
// update likes to DB
updateLikes(id, true);
}
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(itemView.getContext(), "Error: " + error, Toast.LENGTH_LONG).show();
}
});
});
}
}
}
HomeFragment:
public class HomeFragment extends Fragment {
LoadingDialog progressDialog;
final DatabaseReference postsRef = FirebaseDatabase.getInstance().getReference("posts");
final DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
final RecyclerView recyclerView = view.findViewById(R.id.home_recycler_view);
final ArrayList<PostModel> postModelArrayList = new ArrayList<>();
final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
final RecyclerView.Adapter recyclerAdapter = new PostRecyclerAdapter(postModelArrayList, getContext());
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
progressDialog = LoadingDialog.Companion.get(getActivity());
progressDialog.show();
postsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
progressDialog.hide();
for (DataSnapshot snap : snapshot.getChildren()) {
PostModel postModel = new PostModel();
postModel.setId(snap.child("id").getValue(String.class));
postModel.setImgUrl(snap.child("imgUrl").getValue(String.class));
postModel.setLikes(snap.child("likes").getValue(String.class));
postModel.setName(snap.child("name").getValue(String.class));
// find user id and set profile picture by name
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
for (DataSnapshot snap1 : snapshot1.getChildren()) {
if (snap1.child("name").getValue(String.class).equals(snap.child("name").getValue(String.class))) {
postModel.setAuthorID(snap1.child("id").getValue(String.class));
postModel.setProfileImgUrl(snap1.child("profileImgUrl").getValue(String.class));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
postModelArrayList.add(postModel);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(getContext(), "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}

Android List View not dynamically populating from Database

I am developing a realtime messaging application. I have gotten as far as the user messages being stored in Firebase Realtime Database. But not able to populate them back into a listview. I have a method called displayMessages() where I want to pull all the messages back from the Database and populate into a ListView. For some reason It is not populating the View and I am not sure why. Anyone able to help.
public class ChatRoom extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText input;
private FloatingActionButton fab;
private FirebaseListAdapter<Comment> adapter;
#SuppressLint("SimpleDateFormat")
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
fab = findViewById(R.id.fab);
input = findViewById(R.id.input);
mAuth = FirebaseAuth.getInstance();
final String userID = mAuth.getUid();
assert userID != null;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
assert user != null;
String userName = user.getUserName();
createMessage(userName);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ChatRoom.this, "Message is empty!", Toast.LENGTH_SHORT).show();
}
});
displayMessages();
}
public void createMessage(final String userName) {
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().isEmpty()) {
Toast.makeText(ChatRoom.this, "Message is empty!", Toast.LENGTH_SHORT).show();
} else {
Date date = new Date();
String currentDateTime = dateFormat.format(date);
mAuth = FirebaseAuth.getInstance();
final String userID = mAuth.getUid();
Comment comment = new Comment(input.getText().toString(), userName,userID,currentDateTime);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("Chat").push().setValue(comment).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ChatRoom.this, "Message Saved", Toast.LENGTH_SHORT).show();
input.setText("");
displayMessages();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatRoom.this, "Error Occurred: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
//I am able to write new messages to firebase realtime database
//I need to fix this method and populate the list with the messages from the database
public void displayMessages() {
Query query = FirebaseDatabase.getInstance().getReference().child("Chat");
ListView listOfMessages = findViewById(R.id.list_of_messages);
FirebaseListOptions<Comment> options =
new FirebaseListOptions.Builder<Comment>()
.setQuery(query, Comment.class)
.setLayout(R.layout.message)
.build();
adapter = new FirebaseListAdapter<Comment>(options){
#Override
protected void populateView(#NotNull View v, #NotNull Comment model, int position) {
TextView messageText = v.findViewById(R.id.message_text);
TextView messageUser = v.findViewById(R.id.message_user);
TextView messageTime = v.findViewById(R.id.message_time);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
messageTime.setText(model.getDateTime());
}
};
listOfMessages.setAdapter(adapter);
}
}

Can't convert object of type java.lang.String to type (Firebase,RecyclerView)

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

How to Delete the Firebase database Key from Recycle view based on position

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.

How can I display Firebase items in Android ListView?

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) {
}
});

Categories