android: checkbox usage in fragment which contains recycler view - android

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.

Related

Images showing slow from firebase realtime database

I am creating an Android app which is based on wallpaper. I have different categories in my app that shows images and after clicking on particular image it will show full image. The problem is when I click on any categories the images are shown are very slow. I am retrieving images from firebase realtime database. I am showing images in grid layout in two columns. I have also compress all the images then to the process of showing images is very slow.
This is one of the category code.
public class AnimalWallpaper extends AppCompatActivity {
private RecyclerView recyclerView;
private ProgressBar progressBar;
private DatabaseReference reference;
private ArrayList<String> list;
private WallpaperAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animal_wallpaper);
reference = FirebaseDatabase.getInstance().getReference().child("animal");
recyclerView = findViewById(R.id.recyclerViewAnimal);
progressBar = findViewById(R.id.progressBarAnimal);
getData();
}
private void getData() {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
progressBar.setVisibility(View.GONE);
list = new ArrayList<>();
for (DataSnapshot shot : snapshot.getChildren()) {
String data = shot.getValue().toString();
list.add(data);
}
recyclerView.setLayoutManager(new GridLayoutManager(AnimalWallpaper.this, 2));
adapter = new WallpaperAdapter(list, AnimalWallpaper.this);
recyclerView.setAdapter(adapter);
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(AnimalWallpaper.this, "Error : "+error.getMessage() , Toast.LENGTH_SHORT).show();
}
});
}
}
This is wallpaperadapter class code.
public class WallpaperAdapter extends RecyclerView.Adapter<WallpaperAdapter.WallpaperViewHolder> {
private ArrayList<String> list;
private Context context;
public WallpaperAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#org.jetbrains.annotations.NotNull
#Override
public WallpaperViewHolder onCreateViewHolder(#NonNull #org.jetbrains.annotations.NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_image_layout, parent, false );
return new WallpaperViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull #org.jetbrains.annotations.NotNull WallpaperAdapter.WallpaperViewHolder holder, int position) {
Glide.with(context).load(list.get(position)).into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, FullImageActivity.class);
intent.putExtra("images", list.get(position));
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class WallpaperViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public WallpaperViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.item_image);
}
}
}

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

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 to filter RecyclerView data in Fragment

I do not know how to filter results from RecyclerView which is being displayed in Fragment.
If possible, I want to merge some of these codes into one java file.
i have searched on Google for some examples, but most of them are implemented in Activity instead.
My fragment code :
public class SearchFragment extends Fragment {
private RecyclerView recyclerView;
private AdvertiseAdapter advertiseAdapter;
private List<Advertise> advertiseList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search,container,false);
recyclerView = view.findViewById(R.id.searchResult_view);
new DatabaseHelper().readProperty(new DatabaseHelper.DataStatus() {
#Override
public void DataIsLoaded(List<Advertise> advertiseList, List<String> keys) {
new RecyclerViewConfig().setConfig(recyclerView,getContext(),advertiseList,keys);
}
});
return view;
}
My DatabaseHelper
public class DatabaseHelper {
private FirebaseDatabase firebaseDatabase;
private DatabaseReference reference;
private List<Advertise> property = new ArrayList<>();
public interface DataStatus{
void DataIsLoaded(List<Advertise> ads,List<String> keys);
}
public DatabaseHelper() {
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference("Property");
}
public void readProperty(final DataStatus dataStatus){
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
property.clear();
List<String> propertyKeys = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()){
for (DataSnapshot propertySnapshot : userSnapshot.getChildren()){
propertyKeys.add(propertySnapshot.getKey());
Advertise advertise = propertySnapshot.getValue(Advertise.class);
property.add(advertise);
}
}
dataStatus.DataIsLoaded(property,propertyKeys);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
My RecyclerViewConfig code :
public class RecyclerViewConfig {
private Context mContext;
private PropertyAdapter propertyAdapter;
public void setConfig(RecyclerView recyclerView, Context context, List<Advertise> advertiseList, List<String> keys){
mContext = context;
propertyAdapter = new PropertyAdapter(advertiseList,keys);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(propertyAdapter);
}
class PropertyItemView extends RecyclerView.ViewHolder{
//private ImageView PropertyImage;
private TextView PropertyName;
private TextView PropertyPostal;
private TextView PropertyState;
private TextView PropertyDetail;
private String key;
public PropertyItemView(ViewGroup parent){
super(LayoutInflater.from(mContext)
.inflate(R.layout.search_view,parent,false));
//PropertyImage = itemView.findViewById(R.id.advertiseImage);
PropertyName = itemView.findViewById(R.id.advertiseName);
PropertyState = itemView.findViewById(R.id.advertiseState);
PropertyPostal = itemView.findViewById(R.id.advertisePostal);
PropertyDetail = itemView.findViewById(R.id.advertiseDetail);
}
public void bind(Advertise advertise,String key){
//PropertyImage.setImageDrawable(advertise.getProperty_imageUrl());
PropertyName.setText(advertise.getName());
PropertyState.setText(advertise.getState());
PropertyPostal.setText(advertise.getPostal());
PropertyDetail.setText(advertise.getDetail());
this.key = key;
}
}
class PropertyAdapter extends RecyclerView.Adapter<PropertyItemView>{
private List<Advertise> advertiseList;
private List<String> mkeys;
public PropertyAdapter(List<Advertise> advertiseList, List<String> mkeys) {
this.advertiseList = advertiseList;
this.mkeys = mkeys;
}
#NonNull
#Override
public PropertyItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new PropertyItemView(parent);
}
#Override
public void onBindViewHolder(#NonNull PropertyItemView holder, int position) {
holder.bind(advertiseList.get(position),mkeys.get(position));
final Advertise ads = advertiseList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent redirect = new Intent(mContext,PropertyActivity.class);
redirect.putExtra("propertyID", ads.getPropertyID());
mContext.startActivity(redirect);
}
});
}
#Override
public int getItemCount() {
return advertiseList.size();
}
public void updateList(List<String> newList){
mkeys = new ArrayList<>();
mkeys.addAll(newList);
notifyDataSetChanged();
}
}

RecyclerView In Fragment Not Working (Unable to add data to it)

Here is my fragment
public class TransactionsFragment extends Fragment {
private FirebaseAuth mAuth;
private DatabaseReference mDBref;
FirebaseUser Fuser;
private String UID;
private RecyclerView recyclerView;
private RecyclerView.Adapter trpAdapter;
private List<TransGetterSetter> DataList;
String trans_id;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_transactions, container, false);
DataList = new ArrayList<>();
recyclerView = (RecyclerView) v.findViewById(R.id.RVList);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
TransactionRVAdapter trvAdapter = new TransactionRVAdapter(DataList, getContext());
recyclerView.setAdapter(trvAdapter);
mAuth = FirebaseAuth.getInstance();
mDBref = FirebaseDatabase.getInstance().getReference();
Fuser = mAuth.getInstance().getCurrentUser();
UID = Fuser.getUid();
mDBref.child("transactions").child(UID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot chidSnap : dataSnapshot.getChildren()) {
trans_id = chidSnap.getKey();
DataList.add(new TransGetterSetter("" + trans_id));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
trvAdapter.notifyDataSetChanged();
return v;
}
}
If i toast "trans_id" string im getting expected result.
Here is My Adapter class
public class TransactionRVAdapter extends RecyclerView.Adapter<TransactionRVAdapter.rvViewHolder> {
Context mContext;
List<TransGetterSetter> DataList = new ArrayList<>();
public class rvViewHolder extends RecyclerView.ViewHolder{
private TextView TransId;
public rvViewHolder(#NonNull View itemView) {
super(itemView);
TransId = (TextView) itemView.findViewById(R.id.TransIdTxt);
}
}
public TransactionRVAdapter( List<TransGetterSetter> DataList,Context mContext){
this.DataList = DataList;
this.mContext = mContext;
}
#NonNull
#Override
public rvViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.fragment_transactions_item, viewGroup, false);
return new rvViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull rvViewHolder rvViewHolder, int i) {
rvViewHolder.TransId.setText(DataList.get(i).getTrans_id());
}
#Override
public int getItemCount() {
return DataList.size();
}
}
Here is my GetterSetter class
public class TransGetterSetter {
private String trans_id;
public TransGetterSetter() {
}
public TransGetterSetter(String trans_id) {
this.trans_id = trans_id;
}
public String getTrans_id() {
return trans_id;
}
public void setTrans_id(String trans_id) {
this.trans_id = trans_id;
}
}
Im able to get Data from firebase, but when i try to add it to recycler view it dosen't show any data. Recycler view is showing empty. I checked my code many time but haven't found solution.
You should call :
trvAdapter.notifyDataSetChanged();
After the for loop inside the (onDataChange) event listener.
Try to called ..
DataList.add(new TransGetterSetter("" + trans_id));
after this line called ..
trvAdapter.notifyDataSetChanged();

Categories

Resources