How to show all users post in recyclerView in android Studio - android

I can show other user post in recycler view. But i can't show my own post in that recycler view.When i open HomeFragmentActivity its showing all others post with out owners post. I am trying to see my post in this recycler view but i can't.but other user can see my post .
Anyone can help me please....
here is my code...
Post Adapter
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
public Context mContext;
private List <Post>mPost;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPost) {
this.mContext = mContext;
this.mPost = mPost;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.post_item,parent,false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
final Post post=mPost.get(position);
Glide.with(mContext).load(post.getPostimage()).into(holder.post_image);
if(post.getDescription().equals("")){
holder.description.setVisibility(View.GONE);
}else {
holder.description.setVisibility(View.VISIBLE);
holder.description.setText(post.getDescription());
}
publisherInfo(holder.image_profile,holder.username,holder.publisher,post.getPublisher());
isLiked(post.getPostid(),holder.like);
nrLikes(holder.likes,post.getPostid());
getComments(post.getPostid(),holder.comments);
isSaved(post.getPostid(),holder.save);
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("profileid",post.getPublisher());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("profileid",post.getPublisher());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.publisher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("profileid",post.getPublisher());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("postid",post.getPostid());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PostDetailsFragment()).commit();
}
});
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent( mContext, CommentsActivity.class);
intent.putExtra("postid",post.getPostid());
intent.putExtra("publisherid",post.getPublisher());
mContext.startActivity(intent);
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.save.getTag().equals("save")){
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid()).
child(post.getPostid()).setValue(true);
}else {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid()).
child(post.getPostid()).removeValue();
}
}
});
holder.comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent( mContext, CommentsActivity.class);
intent.putExtra("postid",post.getPostid());
intent.putExtra("publisherid",post.getPublisher());
mContext.startActivity(intent);
}
});
holder.likes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext, FollowersActivity.class);
intent .putExtra("id",post.getPostid());
intent.putExtra("title","likes");
mContext. startActivity(intent);
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")){
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(firebaseUser.getUid()).setValue(true);
addNotifications(post.getPublisher(),post.getPostid());
}else {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(firebaseUser.getUid()).removeValue();
}
}
});
}
#Override
public int getItemCount() {
return mPost.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile,post_image,like,comment,save;
public TextView username,likes,comments, description,publisher;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile=itemView.findViewById(R.id.image_profile);
post_image=itemView.findViewById(R.id.post_image);
like=itemView.findViewById(R.id.like);
comment=itemView.findViewById(R.id.comment);
save=itemView.findViewById(R.id.save);
username=itemView.findViewById(R.id.username);
likes=itemView.findViewById(R.id.likes);
comments=itemView.findViewById(R.id.comments);
description=itemView.findViewById(R.id.description);
publisher=itemView.findViewById(R.id.publisher);
}
}
private void getComments(String postid, final TextView comments){
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Comments").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
comments.setText("View All"+dataSnapshot.getChildrenCount()+"Comments");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void isLiked(String postid, final ImageView imageView){
final FirebaseUser firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(firebaseUser.getUid()).exists()){
imageView.setImageResource(R.drawable.ic_liked);
imageView.setTag("liked");
}
else{
imageView.setImageResource(R.drawable.ic_like);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void addNotifications(String userid, String postid){
DatabaseReference reference=FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
HashMap<String,Object>hashMap=new HashMap<>();
hashMap.put("userid",firebaseUser.getUid());
hashMap.put("text","liked your post");
hashMap.put("postid",postid);
hashMap.put("ispost",true);
reference.push().setValue(hashMap);
}
private void nrLikes(final TextView likes, String postid){
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
likes.setText(dataSnapshot.getChildrenCount()+" likes");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void publisherInfo (final ImageView image_profile, final TextView username, final TextView publisher, final String userId ){
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(userId);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user=dataSnapshot.getValue(User.class);
Glide.with(mContext).load(user.getImageurl()).into(image_profile);
username.setText(user.getUsername());
publisher.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void isSaved(final String postId, final ImageView imageView){
FirebaseUser firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Saves").
child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(postId).exists()){
imageView.setImageResource(R.drawable.ic_save_black);
imageView.setTag("saved");
}else {
imageView.setImageResource(R.drawable.ic_save);
imageView.setTag("save");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Home Fragment
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private PostAdapter postAdapter;
private List<Post>postLists;
private List<String> followinglist;
ProgressBar progressBar;
#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);
progressBar=view.findViewById(R.id.progress_circular);
recyclerView=view.findViewById(R.id.recyler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
postLists=new ArrayList<>();
postAdapter=new PostAdapter(getContext(),postLists);
recyclerView.setAdapter(postAdapter);
checkFollowing();
return view;
}
private void checkFollowing(){
//
followinglist=new ArrayList<>();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Follow").
child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followinglist.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
followinglist.add(snapshot.getKey());
}
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void readPosts(){
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Post post=snapshot.getValue(Post.class);
for(String id : followinglist){
if(post.getPublisher().equals(id)){
postLists.add(post);
}
}
}
postAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}

Remove the
For (String Id : following list)
And let the codes
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private PostAdapter postAdapter;
private List<Post>postLists;
private List<String> followinglist;
ProgressBar progressBar;
#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);
progressBar=view.findViewById(R.id.progress_circular);
recyclerView=view.findViewById(R.id.recyler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
postLists=new ArrayList<>();
postAdapter=new PostAdapter(getContext(),postLists);
recyclerView.setAdapter(postAdapter);
checkFollowing();
return view;
}
private void checkFollowing(){
//
followinglist=new ArrayList<>();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Follow").
child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followinglist.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
followinglist.add(snapshot.getKey());
}
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void readPosts(){
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Post post=snapshot.getValue(Post.class);
{
postLists.add(post);
}
It will show all post each 1 time

Add all post's to the list
for(String id : followinglist){
postLists.add(post);
}

Related

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

Retrieve specific child from Firebase Realtime database into the RecyclerView - Android

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

How do I make recyclerView that retrives data from firebase, using getKey()?

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

How to remove parent from firebase database from the recycler adapter?

I am doing a project in firebase database and wanted to delete a parent from the firebase database in a recycler view. This what it looks like from my firebase Database I want to delete this key that has an arrow.
Problem:- The code does not delete a parent key in the image. I want to delete the key with an arrow mark.
This is my code for the view-holder
public class ViewHolder1 extends RecyclerView.Adapter<ViewHolder1.ImageViewHolder> {
private Context mContext1;
private List<Model1> mModel1;
private ImageAdapter.OnItemClickListener mListener;
public ViewHolder1(Context context1, List<Model1> models1) {
mContext1 = context1;
mModel1 = models1;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext1).inflate(R.layout.row1, viewGroup, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder imageViewHolder, int i) {
final Model1 mModelcur = mModel1.get(i);
imageViewHolder.img_food.setText(mModelcur.getFood());
imageViewHolder.img_order.setText(mModelcur.getOrder());
imageViewHolder.img_cost.setText(mModelcur.getPrice());
}
#Override
public int getItemCount() {
return mModel1.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
public TextView img_food;
public TextView img_order;
public TextView img_cost;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
img_food = itemView.findViewById(R.id.Foody);
img_order = itemView.findViewById(R.id.Ordery);
img_cost = itemView.findViewById(R.id.Costy);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if(mListener != null)
{
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION)
{
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuItem delete = menu.add(Menu.NONE, 1,1,"Delete");
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if(mListener != null)
{
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION)
{
switch(item.getItemId())
{
case 1:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener
{
void onItemClick(int position);
void onDeleteClick1(int position);
}
public void setOnItemClickListener(ImageAdapter.OnItemClickListener listener)
{
mListener = listener;
}
}
and this is for my mainactivity
mDatabaseReference2= FirebaseDatabase.getInstance().getReference("User");
mDatabaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(final DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
final String myParentNode = postSnapshot.getKey();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDatabaseReference.orderByKey().equalTo(myParentNode).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot posts: dataSnapshot.getChildren())
{
final String key = posts.getKey();
if(key.equals(myParentNode))
{
mDatabaseReference1 = FirebaseDatabase.getInstance().getReference(key).child("Ordered");
mDatabaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Model1 model2=postSnapshot.getValue(Model1.class);
mModel2.add(model2);
}
mAdapter2.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
}
#Override
public void onDeleteClick1(int position) {
Model1 selectedItem = mModel2.get(position);
String selectedKey = selectedItem.getFood();
mDatabaseReference2= FirebaseDatabase.getInstance().getReference("User");
mDatabaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(final DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
String myKey = postSnapshot.getKey();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDatabaseReference.orderByKey().equalTo(myKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot posts: dataSnapshot.getChildren())
{
String myKey = posts.getKey();
FirebaseDatabase.getInstance().getReference().child(myKey).child("Ordered").removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("Delete", "Notification has been deleted");
} else {
Log.d("Delete", "Notification couldn't be deleted");
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
mDatabaseReference1.removeEventListener(mDBListener);
}
Update Can someone help me, please? The code crash after I clicked a back button now. I really need help, please. I can't seem to delete the key or the child in the recycler adapter.

Data appear in fire base console but didn't appear in the simulator

I create fire base Real time data base project and try to display student List in Recycler View, the data appear normally in fire base console but didn't appear in the simulator ?
Here is the Recycler View Class code :
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.StudentHolder> {
private Context context;
private List<Student> studentList;
public StudentAdapter(Context context, List<Student> studentList) {
this.context = context;
this.studentList = studentList;
}
#Override
public StudentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_row, parent, false);
return new StudentHolder(row);
}
#Override
public void onBindViewHolder(StudentHolder holder, int position) {
final Student student = studentList.get(position);
holder.studentNameTv.setText(student.getName());
holder.studentAvgTv.setText(String.valueOf(student.getAverage()));
holder.editStudentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, EditStudentActivity.class);
intent.putExtra("name", student.getName());
context.startActivity(intent);
}
});
holder.deleteStudentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
Query query = ref.child("students").orderByChild("name").equalTo(student.getName());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
snapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return studentList.size();
}
class StudentHolder extends RecyclerView.ViewHolder {
TextView studentNameTv, studentAvgTv;
Button deleteStudentBtn, editStudentBtn;
public StudentHolder(View itemView) {
super(itemView);
studentNameTv = (TextView) itemView.findViewById(R.id.student_name);
studentAvgTv = (TextView) itemView.findViewById(R.id.student_avg);
deleteStudentBtn = (Button) itemView.findViewById(R.id.delete_student);
editStudentBtn = (Button) itemView.findViewById(R.id.edit_student);
}
}
}
and Here is the Main Activity Class code :
public class MainActivity extends AppCompatActivity {
List<Student> studentList = new ArrayList<>();
StudentAdapter adapter;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ref = database.getReference();
ref.child("students").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
studentList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Student student = snapshot.getValue(Student.class);
studentList.add(student);
adapter.notifyDataSetChanged();
}
Collections.reverse(studentList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
adapter = new StudentAdapter(MainActivity.this, studentList);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(adapter);
SearchView searchView = (SearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Query fireQuery = ref.child("students").orderByChild("name").equalTo(query);
fireQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();
} else {
List<Student> searchList = new ArrayList<Student>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Student student = snapshot.getValue(Student.class);
searchList.add(student);
adapter = new StudentAdapter(MainActivity.this, searchList);
recyclerView.setAdapter(adapter);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
adapter = new StudentAdapter(MainActivity.this, studentList);
recyclerView.setAdapter(adapter);
return false;
}
});
}
}

Categories

Resources