How not to show user that is online in recyclerview - android

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

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 to fetch Uploaded Images from Firebase Storage

I've been following this tutorial link on youtube about how I can upload and retrieve images. Everything was going great until I got to the part where you show the images. My images are not showing. I don't get any erros and or warning messages I just get a blank page when I run my app. Below is my code. Thanks in advance.
//UsersAcivity class
private RecyclerView recyclerView;
private UploadAdapter uploadAdapter;
private DatabaseReference dbReference;
private List<UploadModel> uploads;
FirebaseStorage firebaseStorage;
StorageReference storageR;
private ImageView imageView;
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
uploads = new ArrayList<>();
mAdapter = new ImageAdapter(getApplicationContext(), uploads);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
uploadAdapter.notifyDataSetChanged();
dbReference = FirebaseDatabase.getInstance().getReference("Users");
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
firebaseStorage = FirebaseStorage.getInstance();
storageR = firebaseStorage.getReference();
firebaseUser = firebaseAuth.getInstance().getCurrentUser();
firebaseDatabase.getInstance().getReference();
dbReference.orderByChild(userid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
UploadModel uploadModel = postsnapshot.getValue(Upload.class);
Uploads.add(uploadModel);
}
uploadAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(UsersActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
//UploadModel class
public class UploadModel {
private String image;
public UploadModel(){
//Empty constructor needed
}
public UploadModel (String imageUrl){
images=imageUrl;
}
public String getImageUrl() {
return image;
}
public void setImageUrl(String image) {
this.image = image;
}
}
UploadAdapter class
public class UploadAdapter extends RecyclerView.Adapter<UploadAdapter.ViewHolder>{
private Context ctext;
private List<Upload> list;
public UploadAdapter(Context context,List<Upload> uploads){
ctext = context;
list = uploads;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View V = LayoutInflater.from(ctext).inflate(R.layout.cardview, parent, false);
return new ViewHolder(V);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent=list.get(position);
Picasso.get().load(uploadCurrent.getImageUrl()).fit().centerCrop().into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public View view;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.imageview);
}
}
}
Your not getting any response from Firebase Realtime Database because of the path you provided.
dbReference.child("LoqCOxqzhpN3puCWwhYDtHJVXqg2").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
String imageUrl= (String) postsnapshot.child("ImageUrl").getValue();
Uploads.add(imageUrl);
}
uploadAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(UsersActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
Your orderByChild() finding id under the Users.

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

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

android: checkbox usage in fragment which contains recycler view

In my app about health, there is a fragment in which doctor can add or deny patient to his/her own patient list. I use a recyclerView to show all patients, in each items there are informations about patiens like names, birthday, city and a checkBox which shows patient is added or not. Top of the page there is another checkBox to select all patients, also there are add and deny textViews. I want to use these textViews to add or deny patients which is selected of their own checkBoxes. After click add textView patients will add to Firebase Database. I could not do that features.How can i do? Here is my codes:
public class FragmentHastaBasvurulari extends Fragment {
private ArrayList<String> hastaAdi=new ArrayList<>();
private ArrayList<String> hastaOzellikleri=new ArrayList<>();
private ArrayList<String> hastaliklar=new ArrayList<>();
private ArrayList<String> hastaOnayi=new ArrayList<>();
private ArrayList<Users> hastalar=new ArrayList<>();
private FirebaseAuth mAuth;
private FirebaseUser firebaseUser;
private FirebaseDatabase database;
private DatabaseReference myRef;
private RecyclerView rvHastaBasvuru;
private CheckBox checkBoxHepsiniSec;
private TextView tvReddet,tvOnayla;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Hasta Başvuruları");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hasta_basvurulari, container, false);
mAuth=FirebaseAuth.getInstance();
firebaseUser=mAuth.getCurrentUser();
database=FirebaseDatabase.getInstance();
myRef=database.getReference();
rvHastaBasvuru=(RecyclerView) view.findViewById(R.id.rvHastaBasvuru);
checkBoxHepsiniSec=(CheckBox) view.findViewById(R.id.checkBoxHepsiniSec);
tvOnayla=(TextView) view.findViewById(R.id.tvOnayla);
tvReddet=(TextView) view.findViewById(R.id.tvReddet);
myRef.child("kullanicilar")
.child(firebaseUser.getUid()).child("hastalar").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
EklenecekHasta eklenecekHasta = ds.getValue(EklenecekHasta.class);
DatabaseReference hastaRef= FirebaseDatabase.getInstance().getReference().child("kullanicilar").child(eklenecekHasta.getUserId());
hastaRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Users hasta = dataSnapshot.getValue(Users.class);
String sehir, dogumTarihi,hastaliklar1;
if(hasta.getSehir().equals("Seçiniz")){
sehir="---";
} else {
sehir=hasta.getSehir();
}
if(hasta.getDogumtarihi().equals("../../....")){
dogumTarihi="---";
} else {
dogumTarihi=hasta.getDogumtarihi();
}
if(hasta.getHastaliklar().equals("")){
hastaliklar1="---";
} else {
hastaliklar1=hasta.getHastaliklar();
}
hastaAdi.add(hasta.getAd()+" "+hasta.getSoyad());
hastaOzellikleri.add(hasta.getCinsiyet()+" "+sehir+" "+dogumTarihi);
hastaliklar.add(hastaliklar1);
hastaOnayi.add(hasta.getOnay());
hastalar.add(hasta);
}
rvHastaBasvuru.setAdapter(adapter);
rvHastaBasvuru.setLayoutManager(new LinearLayoutManager(getContext()));
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
HastaListesiAdapter adapter= new HastaListesiAdapter(getContext(),hastaAdi,hastaOzellikleri,hastaliklar,hastaOnayi,hastalar);
});
tvOnayla.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
tvReddet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
Here is my adapter class codes:
public class HastaListesiAdapter extends RecyclerView.Adapter<HastaListesiAdapter.ViewHolder>{
private static final String TAG="HekimListesiAdapter";
private ArrayList<String> hastaAdi=new ArrayList<>();
private ArrayList<String> hastaOzellikleri=new ArrayList<>();
private ArrayList<String> hastaliklar=new ArrayList<>();
private ArrayList<String> hastaOnayi=new ArrayList<>();
private ArrayList<Users> hastalar=new ArrayList<>();
private Context myContext;
public HastaListesiAdapter(Context myContext, ArrayList<String> hastaAdi, ArrayList<String> hastaOzellikleri,
ArrayList<String> hastaliklar,ArrayList<String> hastaOnayi,ArrayList<Users> hastalar) {
this.hastaAdi = hastaAdi;
this.hastaOzellikleri = hastaOzellikleri;
this.myContext = myContext;
this.hastaliklar=hastaliklar;
this.hastaOnayi=hastaOnayi;
this.hastalar=hastalar;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.hasta_item,parent,false);
ViewHolder holder=new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int i) {
holder.itemHastaAd.setText(hastaAdi.get(i));
holder.itemHastaOz.setText(hastaOzellikleri.get(i));
holder.itemHastaliklar.setText(hastaliklar.get(i));
//Hasta hekim tarafından onaylanmış mı onaylanmamış mı
if(hastaOnayi.get(i).equals("evet")){
holder.checkBoxHastaSec.setChecked(true);
} else if(hastaOnayi.get(i).equals("hayır")){
holder.checkBoxHastaSec.setChecked(false);
}
// CheckBox ın tıklanması üzerine yapılacak işlem
holder.checkBoxHastaSec.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
String secilimi;
if(buttonView.isChecked()){
secilimi="evet";
} else {
secilimi="hayır";
}
}
});
}
#Override
public int getItemCount() {
return hastaAdi.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView itemHastaAd,itemHastaOz,itemHastaliklar;
CheckBox checkBoxHastaSec;
public ViewHolder(#NonNull View itemView) {
super(itemView);
itemHastaAd=itemView.findViewById(R.id.itemHastaAd);
itemHastaOz= itemView.findViewById(R.id.itemHastaOz);
itemHastaliklar=itemView.findViewById(R.id.itemHastaliklar);
checkBoxHastaSec=itemView.findViewById(R.id.checkBoxHastaSec);
}
}
i suggest you to replace your string arrayLists with one arrayList of your custom model and also you can have a boolean for representing data in your checkbox.for example create a model like this:
class YourModel()
{
String hastaAdi;
String hastaOzellikleri;
//... another variables
Boolean isAdded;
//... set & get or other methods
}
now you should pass ArrayList to your adapter and set value for your recyclerView widgets by this arrayList. and then you can initialise or change checkBox value with your isAdded boolean.

Categories

Resources