Getting data from firebase but not showing in recyclerview - android

I am new in android development. I am trying to create list of firebase data. so i have created a recyclerview and represent the data in recyclerview.
I have featched data from firebase and assign to adapter class. but data is not showing in recyclerview.
Fragment Class
public class HomeFragment extends Fragment {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Carmodel> list = new ArrayList<>();;
CarAdapter adapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.recyclerview, container, false);
recyclerView = (RecyclerView) root.findViewById(R.id.recycler);
recyclerView.setLayoutManager( new LinearLayoutManager(getContext()));
reference = FirebaseDatabase.getInstance().getReference().child("AddCar");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Carmodel p = dataSnapshot1.getValue(Carmodel.class);
Log.e("Get Data", p.getCarName());
list.add(p);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), "Opsss.... Something is wrong", Toast.LENGTH_SHORT).show();
}
});
adapter = new CarAdapter(getContext(), list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return root;
}
}
Adapert Class
public class CarAdapter extends RecyclerView.Adapter<CarAdapter.MyViewHolder> {
Context context;
ArrayList<Carmodel> profiles;
public CarAdapter(Context c , ArrayList<Carmodel> p)
{
context = c;
profiles = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.fragment_admin_home, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.name.setText(profiles.get(position).getCarName());
holder.seater.setText(profiles.get(position).getSeater());
holder.price.setText(profiles.get(position).getPrice());
holder.status.setText(profiles.get(position).getAvailable());
Picasso.get().load(profiles.get(position).getImageURL()).into(holder.car_image);
}
#Override
public int getItemCount() {
return profiles.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
TextView name,seater,price, status;
ImageView car_image;
#SuppressLint("CutPasteId")
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.CarName);
seater = (TextView) itemView.findViewById(R.id.Seater);
price = (TextView) itemView.findViewById(R.id.Seater);
car_image = (ImageView) itemView.findViewById(R.id.imageView);
status = (TextView) itemView.findViewById(R.id.Status);
}
}

Carmodel p = dataSnapshot1.getValue(Carmodel.class);
make you sure it is (p) not empty

You are notifying your adapter in wrong time for data change
adapter = new CarAdapter(getContext(), list);
recyclerView.setAdapter(adapter);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Carmodel p = dataSnapshot1.getValue(Carmodel.class);
Log.e("Get Data", p.getCarName());
list.add(p);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), "Opsss.... Something is wrong", Toast.LENGTH_SHORT).show();
}
});
Please modify your method like this

Related

android recylerview not displaying firebase data

I am trying to retrieve data from another firebase project, but the data is not displaying in the recylerview. I am not getting any errors but just a blank cardview. Can someone help me solve this issue that I am having. My code is below.
// This my code
public class ExampleFragment extends Fragment {
LinearLayout linearLayoutWithoutItems,linearLayoutNoConnection;
View rootView;
private RecyclerView recyclerView;
private Adapter1 aAdapter;
ImageButton menu_click;
ImageView imageView;
//Variables
NavigationView navigationView;
Toolbar toolbar;
Menu menu;
LinearLayout linearLayout;
TextView textView;
BottomNavigationView bottomNavigationView;
private DatabaseReference databaseReference;
private ArrayList<Model_Information> myUploads;
FirebaseStorage firebaseStorage;
StorageReference storageReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView =inflater.inflate(R.layout.fragment_example, container, false);
init();
return rootView;
}
public void init()
{
recyclerView = rootView.findViewById(R.id.WithItems_recyclerview);
linearLayoutWithoutItems = rootView.findViewById(R.id.WithoutItems);
linearLayoutNoConnection = rootView.findViewById(R.id.no_connection);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(),1);
recyclerView.setLayoutManager(layoutManager);
myUploads = new ArrayList<Model_Information>();
aAdapter = new Adapter1(getContext(), myUploads);
recyclerView.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
databaseReference = FirebaseDatabase.getInstance("https://liou-43081.firebaseio.com").getReference().child("Post");
if (InternetConnection.checkConnection(getContext())) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//progressBar.setVisibility(View.GONE);
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
Model_Information upload=postsnapshot.getValue(Model_Information.class);
//myUploads.clear();
myUploads.add(upload);
aAdapter = new Adapter1(getContext(), myUploads);
recyclerView.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
recyclerView.invalidate();
}
linearLayoutWithoutItems.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
aAdapter.notifyDataSetChanged();
}else{
linearLayoutWithoutItems.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else {
linearLayoutNoConnection.setVisibility(View.VISIBLE);
linearLayoutWithoutItems.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
}
//Adapter1.class
public class Adapter1 extends RecyclerView.Adapter<Adapter1.ImageViewHolder>{
private Context mContext;
private ArrayList<Model_Information> users;
DatabaseReference databaseReference;
public Adapter1(Context context, ArrayList<Model_Information> uploads){
mContext = context;
users = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View V = LayoutInflater.from(mContext).inflate(R.layout.cardview1, parent, false);
return new ImageViewHolder(V);
}
#Override
public void onBindViewHolder(#NonNull final ImageViewHolder holder, final int position) {
//String uploadCurrent=users.get(position).getmImageUrl();
Glide.with(mContext).load(users.get(position).getmImageUrl()).thumbnail(0.05f).transition(DrawableTransitionOptions.withCrossFade()).fitCenter().centerInside().into(holder.imageView);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(mContext,users.get(position).getCategory(), Toast.LENGTH_LONG).show();
Long l= Long.valueOf(1);
databaseReference = FirebaseDatabase.getInstance("https://louie-43081.firebaseio.com").getReference("Clicks_and_Views").child(users.get(position).id);
databaseReference.child("views").setValue(ServerValue.increment(l));
/*
Intent intent=new Intent(mContext,ViewActivity.class);
intent.putExtra("website",users.get(position).getWebsiteurl());
intent.putExtra("action",users.get(position).getAction());
intent.putExtra("image",users.get(position).getmImageUrl());
intent.putExtra("id",users.get(position).id);
mContext.startActivity(intent);
*/
}
});
}
#Override
public int getItemCount() {
return users.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.image);
}
}
You should not initialize adapter twice.
Your code block should look like this,
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
Model_Information upload=postsnapshot.getValue(Model_Information.class);
myUploads.add(upload);
aAdapter.notifyDataSetChanged();
recyclerView.invalidate();
}

How not to show user that is online in recyclerview

I am currently trying to create a messaging app.The users who have registered on to my app are showed in users tab but along with those users the user who is currently logged into my app also sees himself in users tab .I don't want user to see himself in users tab.
My code
UserAdapter.java
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean ischat;
public UserAdapter(Context mContext, List<User> mUsers,boolean ischat) {
this.mContext = mContext;
this.mUsers = mUsers;
this.ischat=ischat;
}
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.user_item,parent,false);
return new UserAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
final User user=mUsers.get(position);
holder.username.setText(user.getFirst());
if (user.getImageURL().equals("default")){
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(mContext).load(user.getImageURL()).into(holder.profile_image);
}
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("UserName",user.getFirst());
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;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username=itemView.findViewById(R.id.username);
profile_image=itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
}
}
}
UsersFragment.java
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
String TAG = "MyTag";
public UsersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_users, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
readUser();
return view;
}
private void readUser() {
final FirebaseUser firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
User user=snapshot.getValue(User.class);
mUsers.add(user);
}
mUserAdapter=new UserAdapter(getContext(),mUsers,false);
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Make condition to check if whether current login user is not not equals to the key node then it will add users in array
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
if(!FirebaseAuth.getInstance().getCurrentUser().getUid().equals(snapshot.getId())){
User user=snapshot.getValue(User.class);
mUsers.add(user);
}
}
mUserAdapter=new UserAdapter(getContext(),mUsers,false);
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

E/RecyclerView: No adapter attached; skipping layout on recyclerview inside fragment

I have "E/RecyclerView: No adapter attached; skipping layout" error message.
I have recycleView inside fragment so I must have done something wrong on fragment1.java.
here is the code. I set adapter on the code as you can see, but I am getting this error. Any help would be appreciated. Thank you.
public class Fragment1 extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Bible> arrayList;
private FirebaseDatabase database;
private DatabaseReference databaseReference;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
recyclerView = rootView.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
//GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
arrayList = new ArrayList<>();
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("Bible");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
arrayList.clear();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Bible bible = snapshot.getValue(Bible.class);
arrayList.add(bible);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("fragment1", String.valueOf(databaseError.toException()));//에러문 출력
}
});
adapter = new BibleAdapter(arrayList, getContext());
recyclerView.setAdapter(adapter);
return rootView;
}
}
public class BibleAdapter extends RecyclerView.Adapter {
private ArrayList<Bible> arrayList;
private Context context;
private OnVerseItemClickListener listener;
public BibleAdapter(ArrayList<Bible> arrayList, Context context) {
this.arrayList = arrayList;
this.context = context;
}
public void setOnItemClickListener(OnVerseItemClickListener listener){
this.listener = listener;
}
#NonNull
#Override
public BibleAdapter.BibleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.verse_item, parent, false);
BibleViewHolder holder = new BibleViewHolder(view, listener);
return holder;
}
#Override
public void onBindViewHolder(#NonNull BibleAdapter.BibleViewHolder holder, int position) {
Glide.with(holder.imageView)
.load(arrayList.get(position).getImage())
.into(holder.imageView);
holder.bibleType.setText(arrayList.get(position).getBibleType());
holder.keysentance.setText(arrayList.get(position).getKeysentance());
holder.verse.setText(arrayList.get(position).getVerse());
}
#Override
public int getItemCount() {
return (arrayList!=null? arrayList.size():0);
}
public class BibleViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView bibleType;
TextView verse;
TextView keysentance;
public BibleViewHolder(#NonNull View itemView, final OnVerseItemClickListener listener) {
super(itemView);
this.imageView = itemView.findViewById(R.id.imageView);
this.bibleType = itemView.findViewById(R.id.bibleType);
this.keysentance = itemView.findViewById(R.id.keysentance);
this.verse = itemView.findViewById(R.id.verse);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if(listener != null){
listener.onItemClick(BibleViewHolder.this, v, position);
}
}
});
}
}
}
in your code you have create adapter with empty arrayList, but never after that you update the list.
in adapter create swapData() method and call it when you have to refresh data or have refreshed data, in your case you will get it in onDataChange().
And also define adapter before adding listener:
adapter = new BibleAdapter(arrayList, getContext());
recyclerView.setAdapter(adapter);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
arrayList.clear();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Bible bible = snapshot.getValue(Bible.class);
arrayList.add(bible);
}
adapter.swapData(arrayList);
//adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("fragment1", String.valueOf(databaseError.toException()));//에러문 출력
}
});
in adapter class create method as:
public void swapData(ArrayList<Bible> filtersList) {
if (filtersList != null) {
this.arrayList.clear();
this.arrayList.addAll(filtersList);
notifyDataSetChanged();
}
}

Recyclerview fetch existing data after delete an item from adapter and does not update properly

I try to implement a friend request feature in the fragment using custom adapter with firebase database. The problem is when a user accepts or delete someone request, it deletes from firebase but not properly update in the RecyclerView. this problems occurred in only runtime. If I refresh the page then my problem goes away.
Let I have two friend request. If I delete 2nd data then 2nd data will gone from RecyclerView but the problem is RecyclerView shows 1st data doubles. and if I delete 1st data then 1st data goes in the 2nd row and 2nd data came into the first row.
here is my database screenshot
Fragment class-
public class NotificationFragment extends Fragment {
private RecyclerView NotificationRecyclerView;
private NotificationAdapter adapter;
private List<Friend> friendList;
public NotificationFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_notification, container, false);
NotificationRecyclerView = view.findViewById(R.id.NotificationRecyclerView);
NotificationRecyclerView.setHasFixedSize(true);
LinearLayoutManager LayoutManager = new LinearLayoutManager(getContext());
NotificationRecyclerView.setLayoutManager(LayoutManager);
friendList = new ArrayList<>();
adapter = new NotificationAdapter(getContext(), friendList);
NotificationRecyclerView.setAdapter(adapter);
readAllNotification();
return view;
}
private void readAllNotification() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("FriendRequest");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Friend friend = snapshot.getValue(Friend.class);
if (firebaseUser.getUid().equals(friend.getReceiverID())) {
friendList.add(friend);
}
}
Collections.reverse(friendList);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Custom Adapter -
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.NotificationViewHolder> {
private Context context;
private List<Friend> friendList;
public NotificationAdapter(Context context, List<Friend> friendList) {
this.context = context;
this.friendList = friendList;
}
#NonNull
#Override
public NotificationViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_notification_item, parent, false);
return new NotificationAdapter.NotificationViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final NotificationViewHolder holder, final int position) {
final Friend friend = friendList.get(position);
getUserInfo(holder.profileImage, holder.NotificationUserName, friend.getSenderID());
holder.cancelRequestButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase.getInstance().getReference("FriendRequest")
.child(friend.getRequestID()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
removeItem(position);
Toast.makeText(context, "removed", Toast.LENGTH_SHORT).show();
}
});
}
});
}
public void removeItem(int position) {
friendList.remove(position);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return friendList.size();
}
private void getUserInfo(final CircleImageView prfileImage, final TextView NotificationUserName, String senderID) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(senderID);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users users = dataSnapshot.getValue(Users.class);
NotificationUserName.setText(users.getUserName());
Picasso.with(context).load(users.getImageUrl()).into(prfileImage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public class NotificationViewHolder extends RecyclerView.ViewHolder {
private TextView NotificationUserName;
private Button cancelRequestButton;
private CircleImageView profileImage;
public NotificationViewHolder(#NonNull View itemView) {
super(itemView);
NotificationUserName = itemView.findViewById(R.id.NotificationUserName);
cancelRequestButton = itemView.findViewById(R.id.cancelRequestBtn);
profileImage = itemView.findViewById(R.id.profileImage);
}
}
}
My APP Problems screenshot -
let I have two request
1) if I delete 2nd data 1st data show doubles:
2) if I delete 1st data, 1st data goes into 2nd row and 2nd data came into 1st row:
Replace
removeItem(position);
with
removeItem(holder.getAdapterPosition());
You initialize your recyclerView and adapter in onCreateView which was not appropriate.You have to override the method onViewCreated then initialize your recyclerView and adapter.try like this
public class NotificationFragment extends Fragment {
private RecyclerView NotificationRecyclerView;
private NotificationAdapter adapter;
private List<Friend> friendList;
public NotificationFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_notification, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
NotificationRecyclerView = view.findViewById(R.id.NotificationRecyclerView);
NotificationRecyclerView.setHasFixedSize(true);
LinearLayoutManager LayoutManager = new LinearLayoutManager(getContext());
NotificationRecyclerView.setLayoutManager(LayoutManager);
friendList = new ArrayList<>();
adapter = new NotificationAdapter(getContext(), friendList);
NotificationRecyclerView.setAdapter(adapter);
readAllNotification();
}
private void readAllNotification() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("FriendRequest");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Friend friend = snapshot.getValue(Friend.class);
if (firebaseUser.getUid().equals(friend.getReceiverID())) {
friendList.add(friend);
}
}
Collections.reverse(friendList);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Ok I just noticed you passed a parameter in removeItem method using holder.getAdapterPosition() which is causing your problem.Try to pass the position which is provided by public void onBindViewHolder(#NonNull final NotificationViewHolder holder, final int position).So the basic error is when you are in onBindViewHolder you don't need to use holder.getAdapterPosition() because onBindViewHolder already giving you the position
In your removeItem method use notifyDataSetChanged instead of notifyItemRemoved(position)
try like this
#Override
public void onBindViewHolder(#NonNull final NotificationViewHolder holder, final int position) {
final Friend friend = friendList.get(position);
holder.cancelRequestButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase.getInstance().getReference("FriendRequest").child(friend.getRequestID()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
removeItem(position);
Toast.makeText(context, "removed", Toast.LENGTH_SHORT).show();
}
});
}
});
}
public void removeItem(int position) {
friendList.remove(position);
notifyDataSetChanged();
}

Firebase database Listener can't receive variable's values when it end of work

I have implement a Listener for my database. The listener is being called but my menuAdapter is not receiving my values.
I don't know why this is happening.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Menu/思慕雪");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
listStr.add(String.valueOf(dataSnapshot.getKey()));
picUrl.add(dataSnapshot.child("pic").getValue().toString().trim());
m_price.add(dataSnapshot.child("M").getValue().toString().trim());
l_price.add(dataSnapshot.child("L").getValue().toString().trim());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
menuAdapter menuAdapter = new menuAdapter(listStr,picUrl,m_price,l_price);
recyclerView.setAdapter(menuAdapter);
This is my menuAdapter codes.
public class menuAdapter extends RecyclerView.Adapter {
private List<String> mListString;
private List<String> mPicUrl;
private List<String> mMPrice;
private List<String> mLPrice;
public class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
ImageView mImgView;
TextView mTxt;
TextView m_MPrice;
TextView m_LPrice;
ViewHolder(View itemView) {
super(itemView);
mImgView = (ImageView) itemView.findViewById(R.id.drink_pic);
mTxt = (TextView) itemView.findViewById(R.id.drink_name);
m_MPrice = (TextView) itemView.findViewById(R.id.drink_m_price);
m_LPrice = (TextView) itemView.findViewById(R.id.drink_l_price);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),
mListString.get(getAdapterPosition()), Toast.LENGTH_LONG)
.show();
}
}
public menuAdapter(List<String> listString,List<String> picUrl,List<String> m_price,List<String> l_price) {
mListString = listString;
mPicUrl=picUrl;
mMPrice=m_price;
mLPrice=l_price;
}
#Override
public menuAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.menu_card, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
new downloadImageTask(holder.mImgView)
.execute(mPicUrl.get(position));
holder.mTxt.setText(mListString.get(position));
if(!mMPrice.get(position).equals("0")){
holder.m_MPrice.setText("M: $"+mMPrice.get(position));
}else{
holder.m_MPrice.setText("--");
}
if(!mLPrice.get(position).equals("0")){
holder.m_LPrice.setText("L: $"+mLPrice.get(position));
}else{
holder.m_LPrice.setText("--");
}
}
#Override
public int getItemCount() {
return mListString.size();
}
}

Categories

Resources