How to get specific name inside child firebase database into recyclerview? - java

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

Related

Remove a Row from recycle view and Firebase

Hi I am trying to remove A row from a recycle view and once it is removed from the recycle view it should also be removed from the firebase realtime database. I am able to remove it from the recycle view but when I go back into my activity it repopulates with all the rows as I am unsure on how to remove it from Firebase. Can anyone help?
public class FindAllContacts extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
ArrayList<Contacts> contacts = new ArrayList<>();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = mAuth.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_all);
getSupportActionBar().setTitle("View All Contacts");
getAllContacts();
}
public void getAllContatcs() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Contacts");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
Contact contact = userSnapshot.getValue(Contact.class);
assert contact != null;
contatcs.add(contact);
recyclerView = findViewById(R.id.findAllRV);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(FindAll.this));
adapter = new MainAdapter(contacts);
new ItemTouchHelper(itemTouch).attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(FindAll.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
ItemTouchHelper.SimpleCallback itemTouch = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
contatcs.remove(viewHolder.getAdapterPosition());
adapter.notifyDataSetChanged();
}
};
}

Remove RecyclerView Firebase Item Android Java

I've created a favourites page using a RecyclerView with data saved on firebase. I'm attempting to delete an item from both firebase and the recyclerview in realtime. I can remove the item using
dataSnapshot.child(countries.get(position).getId()).getRef().removeValue();
countries.remove(position);
However, I can't remove the last item, but it deletes in firebase. I've tried different combinations of
notifyDataSetChanged();
notifyItemRemoved(position);
notifyItemRangeChanged(position, countries.size());
But with no luck so far, I can't see where I'm going wrong.
Populating recyclerview
Public class FavouritesFragment extends Fragment {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
ArrayList<Country> countries;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_favourites, container, false);
getActivity().setTitle("Favourites");
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
FirebaseUser user = firebaseAuth.getCurrentUser();
String userID = user.getUid();
databaseReference = databaseReference.child("users").child(userID).child("Favourites");
recyclerView = view.findViewById(R.id.favourites_recycler);
countries = new ArrayList<>();
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
addFavourites();
return view;
}
public void addFavourites(){
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Country c = ds.getValue(Country.class);
countries.add(c);
}
adapter = new FavouritesAdapter(countries);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Deleting from RecyclerView in adapter class
public class FavouritesAdapter extends RecyclerView.Adapter<FavouritesAdapter.MyViewHolder>{
ArrayList<Country> countries;
private View view;
ImageBindingAdapter imageBindingAdapter = new ImageBindingAdapter();
RecyclerView recyclerView;
private int position;
private FirebaseDatabase firebaseDatabase;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
public FavouritesAdapter(ArrayList<Country> countries1){
countries = countries1;
}
#NonNull
#Override
public FavouritesAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.favourites, viewGroup, false);
recyclerView = view.findViewById(R.id.favourites_recycler);
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference();
FirebaseUser user = firebaseAuth.getCurrentUser();
String userID = user.getUid();
databaseReference = databaseReference.child("users").child(userID).child("Favourites");
return new FavouritesAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final FavouritesAdapter.MyViewHolder myViewHolder, final int i) {
myViewHolder.name.setText(countries.get(i).getName());
myViewHolder.snippet.setText(countries.get(i).getSnippet());
myViewHolder.popUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(view.getContext(), view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.popup_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_to_favs:
deleteFavourite();
break;
default:
return false;
}
return true;
}
});
}
});
#Override
public int getItemCount() {
return countries.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public ImageView popUp;
public MyViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.cityName);
popUp = itemView.findViewById(R.id.dotsPopUp);
}
}
public void deleteFavourite(){
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String id = countries.get(position).getId();
if(dataSnapshot.exists() && dataSnapshot.child(id).exists()){
dataSnapshot.child(countries.get(position).getId()).getRef().removeValue();
countries.remove(position);
// notifyDataSetChanged();
// notifyItemRemoved(position);
// notifyItemRangeChanged(position, countries.size());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}); }
}
In your adapter you didn't set the position to the position of the item you need to delete. So when the user hits the delete item in the popUp menu, you call deleteFavourite();, but you need to set the class field position before calling deleteFavourite().
So, in onBindViewHolder, you need to assign the value of the second parameter to the position, and it's better to pass it to deleteFavourite() method as a paraemter like deleteFavourite(position):
#Override
public void onBindViewHolder(#NonNull final FavouritesAdapter.MyViewHolder myViewHolder, final int pos) {
....
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_to_favs:
deleteFavourite(pos);
break;
default:
return false;
}
return true;
}
});
Then change your deleteFavourite to accept the new parameter, and notifyItemRemoved(position);
public void deleteFavourite(int pos){
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String id = countries.get(pos).getId();
if(dataSnapshot.exists() && dataSnapshot.child(id).exists()){
dataSnapshot.child(countries.get(pos).getId()).getRef().removeValue();
countries.remove(pos);
notifyItemRemoved(pos);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Do this to remove object from list, in deleteFavourite() function:
..........
if(dataSnapshot.exists() && dataSnapshot.child(id).exists()){
dataSnapshot.child(countries.get(position).getId()).getRef().removeValue();
countries.remove(countries.get(position));
notifyDataSetChanged();
}
..............

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

RecyclerView shows the same item many times in my app

I've created a match system in my Android program that also includes a chat section which has 2 fragments. The first fragment shows your chats, the second one shows your matches by using RecyclerView and UsersAdapter. However, in the second (match) fragment, people who you matched with are shown many times. For example, the same person is seen many times as you can see here.
My code is below.
UserFragment:
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UsersAdapter usersAdapter;
private List<User> mUsers;
FirebaseFirestore usersfragmentstore;
FirebaseAuth readauth;
DocumentReference readref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
usersfragmentstore = FirebaseFirestore.getInstance();
readauth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_users, container, false);
readref = usersfragmentstore.collection("users").document(readauth.getCurrentUser().getUid());
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
readref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot shot = task.getResult();
List<String> matchedid2 = new ArrayList<>();
matchedid2 = (List<String>) shot.get("matchlist");
if (matchedid2.contains(snapshot.getKey())) {
User user = snapshot.getValue(User.class);
mUsers.add(user);
usersAdapter = new UsersAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(usersAdapter);
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
}
UserAdapter:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean ischat;
String theLastMessage;
public UsersAdapter(Context mContext, List<User> mUsers, boolean ischat) {
this.mUsers = mUsers;
this.mContext = mContext;
this.ischat = ischat;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item_chat, parent, false);
return new UsersAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
User user = mUsers.get(position);
holder.username.setText(user.getName());
if (user.getImageURL().equals("default")) {
holder.profile_image.setImageResource(R.drawable.profilepicture);
} else {
Glide.with(mContext).load(user.getImageURL()).into(holder.profile_image);
}
if (ischat) {
lastMessage(user.getId(), holder.last_msg);
} else {
holder.last_msg.setVisibility(View.GONE);
}
if (ischat) {
if (user.getStatus().equals("online")) {
holder.img_on.setVisibility(View.VISIBLE);
holder.img_off.setVisibility(View.GONE);
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.VISIBLE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MessageActivity.class);
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView username;
public ImageView profile_image;
private ImageView img_on;
private ImageView img_off;
private TextView last_msg;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.chatusername);
profile_image = itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
last_msg = itemView.findViewById(R.id.last_msg);
}
}
private void lastMessage(final String userid, final TextView last_msg) {
theLastMessage = "defalut";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) || chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage) {
case "default":
last_msg.setText("No message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
What am I missing?
befor adding new data first clear list by mUsers.clear(); as below
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
readref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot shot = task.getResult();
List<String> matchedid2 = new ArrayList<>();
matchedid2 = (List<String>) shot.get("matchlist");
if (matchedid2.contains(snapshot.getKey())) {
mUsers.clear();
User user = snapshot.getValue(User.class);
mUsers.add(user);
usersAdapter = new UsersAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(usersAdapter);
}
}
});
}

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