The display from the Firebase database works fine, but when I try to delete an item from the database, the application crashes, although the deletion occurs. Writes on a null object reference in the string:
String postDescription = dataSnapshot.child("desc").getValue().toString();
Here is my code:
public class PostFragment extends Fragment {
private RecyclerView recyclerPost;
private DatabaseReference postReference;
private View view;
private LinearLayoutManager layoutManager;
public PostFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_post, container, false);
recyclerPost = view.findViewById(R.id.recycler_post);
postReference = FirebaseDatabase.getInstance().getReference().child("Posts");
postReference.keepSynced(true);
layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerPost.setHasFixedSize(true);
recyclerPost.setLayoutManager(layoutManager);
return view;
}
#Override
public void onStart() {
super.onStart();
Query query = postReference.orderByChild("timestamp");
FirebaseRecyclerOptions<Posts> options =
new FirebaseRecyclerOptions.Builder<Posts>()
.setQuery(query, Posts.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Posts, PostViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final PostViewHolder holder, int position, #NonNull final Posts model) {
final String postId = getRef(position).getKey();
postReference.child(postId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String postDescription = dataSnapshot.child("desc").getValue().toString();
holder.postDesc.setText(postDescription);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postReference.child(postId).removeValue();
}
});
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int position) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.blog_item, viewGroup, false);
return new PostViewHolder(view);
}
};
adapter.startListening();
recyclerPost.setAdapter(adapter);
}
public class PostViewHolder extends RecyclerView.ViewHolder {
private TextView postDesc;
private Button delBtn;
private View view;
public PostViewHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
postDesc = (TextView) view.findViewById(R.id.post_description);
delBtn = (Button) view.findViewById(R.id.del_post_btn);
}
}
}
Please tell me the solution to this problem.
You can try the following:
postReference.child(postId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String postDescription = dataSnapshot.child("desc").getValue().toString();
holder.postDesc.setText(postDescription);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
You can use the method exists():
public boolean exists ()
Returns true if the snapshot contains a non-null value.
It will check if the datasnapshot is in the
database, if it is not in the database then you can add a snackbar or a toast.
More information here:
https://firebase.google.com/docs/reference/android/com/google/firebase/database/DataSnapshot#exists()
Every time a post is added to the adapter/list view, you now create a listener with addValueEventListener in your onBindViewHolder. This listener gets the value from the database, and then keeps listening for changes until you remove it. Since you never remove these listeners, over time they add up and things likely get out of sync.
The simplest solution is to use addListenerForSingleValueEvent:
#Override
protected void onBindViewHolder(#NonNull final PostViewHolder holder, int position, #NonNull final Posts model) {
final String postId = getRef(position).getKey();
postReference.child(postId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String postDescription = dataSnapshot.child("desc").getValue().toString();
holder.postDesc.setText(postDescription);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
When you use addListenerForSingleValueEvent, the listener is removed right after onDataChange fires for the first time.
Related
So I'm trying get my orders listed as users first and then later when clicked taken to the place where all items can be seen. I have set the order ID as the user uid and now I'm trying to get the uid and from that fetch user data. The mykey i have defined as public in starting but I think I'm using it inside loop and hence can't access it outside. Please help
Code I'm trying
firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Order");
firebaseDatabase.keepSynced(true);
firebaseDatabase2 = FirebaseDatabase.getInstance().getReference().child("Users");
firebaseDatabase.keepSynced(true);
firebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mykey = snapshot.getKey();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>().setQuery(firebaseDatabase2.child(mykey), Users.class).build();
FirebaseRecyclerAdapter<Users, Orders.UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, Orders.UsersViewHolder>(options)
{
#Override
public Orders.UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_layout,parent,false);
return new Orders.UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(Orders.UsersViewHolder holder, int position, Users model) {
holder.setName(model.getName());
holder.setStatus(model.getMobile());
}
};
mylist.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public class UsersViewHolder extends RecyclerView.ViewHolder {
View mview;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
mview = itemView;
}
public void setName(String name) {
TextView userNameView = mview.findViewById(R.id.username);
userNameView.setText(name);
}
public void setStatus(String status) {
TextView userStatusView = mview.findViewById(R.id.phone);
userStatusView.setText(status);
}
}
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();
}
I'm quite new to firebase and android world. I want to retrieve only specific groups in which the current logged in user has joined.
Here is my Firebase realtime database structure
However, all the users who logged in are displayed with all the groups exist in the database:
My app screenshot
I tried to filter the output inside the onBindViewHolder method of FirebaseRecylerAdapter but it dont seem to be working :
protected void onBindViewHolder(#NonNull final GroupChatViewHolder holder, final int position, #NonNull Group model) {
final String groups = getRef(position).getKey();
final String retGroupName = groups.toString();
RootRef.child("Groups").child(retGroupName).child("Users").child(currentUser.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
// If current user exist in that group
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
holder.txtGroupName.setText(retGroupName);
// Retrieve groupCreatedBy
RootRef.child("Groups").child(retGroupName).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String retGroupCreatedBy = dataSnapshot.child("groupCreatedBy").getValue().toString();
// Find username of the group creator
RootRef.child("Users").child(retGroupCreatedBy).child("profilename")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
holder.txtGroupCreatedBy.setText("Group created by: " + dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Here are my full codes. I implement all the process including the onBindViewHolder in a fragment class as shown below:
public class GroupChatFragment extends Fragment {
private View view;
private RecyclerView chatList;
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
DatabaseReference RootRef = FirebaseDatabase.getInstance().getReference();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_group_chat, container, false);
chatList = (RecyclerView) view.findViewById(R.id.group_chat_list);
chatList.setLayoutManager(new LinearLayoutManager(getContext()));
Toolbar toolbar = view.findViewById(R.id.toolbar_chat);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
return view;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions<Group> options = new FirebaseRecyclerOptions.Builder<Group>()
.setQuery(RootRef.child("Groups"), Group.class)
.build();
FirebaseRecyclerAdapter<Group, GroupChatViewHolder> adapter =
new FirebaseRecyclerAdapter<Group, GroupChatViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final GroupChatViewHolder holder, final int position, #NonNull Group model) {
...
}
};
chatList.setAdapter(adapter);
adapter.startListening();
}
public static class GroupChatViewHolder extends RecyclerView.ViewHolder {
TextView txtGroupName, txtGroupCreatedBy;
public GroupChatViewHolder(#NonNull View itemView) {
super(itemView);
txtGroupName = itemView.findViewById(R.id.group_name_display);
txtGroupCreatedBy = itemView.findViewById(R.id.group_createdby_display);
}
}
}
I would like to know how can I do a recyclerView that shows data that I got from this database reference:
Salas= new ArrayList<String>();
DatabaseReference referenceSalas = FirebaseDatabase.getInstance().getReference("salas/");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("usuarios/");
FirebaseAuth autenticacao = FirebaseAuth.getInstance();
String emailUsu = autenticacao.getCurrentUser().getEmail();
reference.orderByChild("email").equalTo(emailUsu).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
nomeProf = datas.child("nome").getValue().toString();
referenceSalas.orderByChild("nomeProf").equalTo(nomeProf).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
Salas.add(datas.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
I tried to do the RecyclerView like this:
public class salasFragment extends Fragment {
private RecyclerView mRecycleViewSalas;
private adapterSalas adapterSalas;
private ArrayList<salas> listaSalas= new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private TextView txtSalas, txtTeste;
private String nomeProf;
private String teste="", piru;
private DatabaseReference reference = FirebaseDatabase.getInstance().getReference("usuarios/");
private DatabaseReference referenceSalas = FirebaseDatabase.getInstance().getReference("salas/");
private ValueEventListener valueEventListenerSalas;
ArrayList<String> salasAula = new ArrayList<String>();
public salasFragment() {
// 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_salas, container, false);
final Context context = view.getContext();
txtSalas= view.findViewById(R.id.txtSalas);
txtTeste= view.findViewById(R.id.txtTeste);
mRecycleViewSalas= view.findViewById(R.id.recyclerSalas);
adapterSalas= new adapterSalas(listaSalas, context);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
mRecycleViewSalas.setLayoutManager(layoutManager);
mRecycleViewSalas.setHasFixedSize(true);
mRecycleViewSalas.setAdapter(adapterSalas);
return view; }
#Override
public void onStart() {
super.onStart();
recuperarSalas();
}
#Override
public void onStop() {
super.onStop();
reference.removeEventListener(valueEventListenerSalas);
}
public void recuperarSalas(){
FirebaseAuth autenticacao = FirebaseAuth.getInstance();
String emailUsu = autenticacao.getCurrentUser().getEmail();
valueEventListenerSalas = reference.orderByChild("email").equalTo(emailUsu).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
nomeProf = datas.child("nome").getValue().toString();
referenceSalas.orderByChild("nomeProf").equalTo(nomeProf).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
salas salas=datas.getKey(salas.class);
listaSalas.add(salas);
}
adapterSalas.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
my adapter:
public class adapterSalas extends RecyclerView.Adapter<adapterSalas.myViewHolder> {
private List<salas> Salas;
private Context context;
public adapterSalas(List<salas> listaSalas, Context c ) {
this.Salas= listaSalas;
this.context = c;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_salas, parent, false);
return new myViewHolder(itemLista);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
salas sala = Salas.get(position);
holder.btn1.setText(sala.getPrimeiro());
}
#Override
public int getItemCount() {
return Salas.size();
}
public class myViewHolder extends RecyclerView.ViewHolder{
Button btn1;
public myViewHolder(#NonNull View itemView) {
super(itemView);
btn1 = itemView.findViewById(R.id.btn1);
}
}
}
Although this line "salas salas=datas.getKey(salas.class);" does not work properly when I use "getKey", It only works when "getValue" is used. There is no way of me doing this project with "getValue" instead of "getKey". So there is any way that can make this recyclerView works properly with "getKey" ?
Have you got the data from the firebase already?
If you got the data in an arraylist already, simply plug it in an adapter (you will need to create a RecyclerView adapter, a class to describe the value of each RecyclerView items) and set it to the RecyclerView and you are good to go!
You can use FirebasRecyclerAdapter as you recyclerView adapter. check out this link for a guide on how to use it.
https://medium.com/android-grid/how-to-use-firebaserecycleradpater-with-latest-firebase-dependencies-in-android-aff7a33adb8b
I have a firebase strucuture as
The recycler view is only displaying the last added or say latest added node to the database instead of displaying each and every node
the database reference i am using is
r2 = FirebaseDatabase.getInstance().getReference().child("Uploads").child("Wheat").child(S).child(D).child(T).child(FirebaseAuth.getInstance().getUid());
and the code for recycler view is as
public class MyPost extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference r, r2, r3;
private String S, D, T;
FirebaseRecyclerAdapter<RecyclerCropView, ViewHolder2> Fbra1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_post);
r = FirebaseDatabase.getInstance().getReference().child("User_Data").child(MainDashboard.type).child(FirebaseAuth.getInstance().getUid());
recyclerView = (RecyclerView) findViewById(R.id.R_view2);
r.addListenerForSingleValueEvent(rr);
}
private ValueEventListener rr = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
S = dataSnapshot.child("State").getValue().toString();
D = dataSnapshot.child("City").getValue().toString();
T = dataSnapshot.child("Tehsil").getValue().toString();
// Toast.makeText(MyPost.this,S+D+T.toString(),Toast.LENGTH_LONG).show();
r2 = FirebaseDatabase.getInstance().getReference().child("Uploads").child("Wheat").child(S).child(D).child(T).child(FirebaseAuth.getInstance().getUid());
// Toast.makeText(MyPost.this,r2.toString(),Toast.LENGTH_LONG).show();
r2.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
r3=r2.child(dataSnapshot.getKey());
Toast.makeText(MyPost.this, r3.toString(), Toast.LENGTH_LONG).show();
FirebaseRecyclerOptions<RecyclerCropView> options = new FirebaseRecyclerOptions.Builder<RecyclerCropView>().setQuery(r3, RecyclerCropView.class).build();
Fbra1 = new FirebaseRecyclerAdapter<RecyclerCropView, ViewHolder2>(options) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder2 holder, int position, #NonNull RecyclerCropView model) {
holder.setProductImage(model.getProduct_Image());
holder.setProduct(model.getProduct());
holder.setMax(model.getMaximumPrice());
holder.setQuantityUnit(model.getQuantityUnit());
holder.setQuantity(model.getQuantity());
}
#NonNull
#Override
public ViewHolder2 onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_post, parent, false);
return new ViewHolder2(v);
}
};
Fbra1.notifyDataSetChanged();
recyclerView.hasFixedSize();
recyclerView.setLayoutManager(new LinearLayoutManager(MyPost.this));
Fbra1.startListening();
recyclerView.setAdapter(Fbra1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
#Override
protected void onRestart() {
super.onRestart();
finish();
}
}
Recycler view is only showing very last item that was added to database.
Note:-
The item.xml file has width set to wrap content.
if i remove the childEventListener the recyclerView shows multiple items with
null on the place of TextView(These are those textView on which data retrived was supposed to be set)
Here is the problem: r2.addChildEventListener
Classes implementing this interface can be used to receive events about changes in the child locations of a given DatabaseReference ref. Attach the listener to a location using addChildEventListener(ChildEventListener) and the appropriate method will be triggered when changes occur.
Firebase Docs
What you should use is a r2.addListenerForSingleValueEvent
This returns the children of the specific node. But now since you are using FirebaseUI library, you will not need to listen as it is a listener itself.
So your code should listen to the root of the posts. This r3=r2.child(dataSnapshot.getKey()); is unnecessary because it only gets one entry
Change to this
FirebaseRecyclerOptions<RecyclerCropView> options = new FirebaseRecyclerOptions.Builder<RecyclerCropView>().setQuery(r2, RecyclerCropView.class).build();
Fbra1 = new FirebaseRecyclerAdapter<RecyclerCropView, ViewHolder2>(options) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder2 holder, int position, #NonNull RecyclerCropView model) {
holder.setProductImage(model.getProduct_Image());
holder.setProduct(model.getProduct());
holder.setMax(model.getMaximumPrice());
holder.setQuantityUnit(model.getQuantityUnit());
holder.setQuantity(model.getQuantity());
}
#NonNull
#Override
public ViewHolder2 onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_post, parent, false);
return new ViewHolder2(v);
}
};
Fbra1.notifyDataSetChanged();
recyclerView.hasFixedSize();
recyclerView.setLayoutManager(new LinearLayoutManager(MyPost.this));
Fbra1.startListening();
recyclerView.setAdapter(Fbra1);