How can i fill the recylerview with firebase realtime database data? - android

I tried so many solutions about this, but none of this resolve my problem. I can not reach the database using recyclerview. I have firebase realtime database data like this;
Tag
--- Main Category
----- keyID
------ main-Category, sub-category
Tags class
public class Tags {
private String id;
private String mainTags;
private String subTags;
public Tags() {}
public Tags(String id, String mainTags, String subTags) {
this.id = id;
this.mainTags = mainTags;
this.subTags = subTags;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMainTags() {
return mainTags;
}
public void setMainTags(String mainTags) {
this.mainTags = mainTags;
}
public String getSubTags() {
return subTags;
}
public void setSubTags(String subTags) {
this.subTags = subTags;
}
}
and this is TagAdapter
public class TagAdapter extends RecyclerView.Adapter<TagAdapter.ItemViewHolder> {
private List<Tags> mTagList;
private Context mContext;
public TagAdapter(List<Tags> mTagList, Context mContext) {
this.mTagList = mTagList;
this.mContext = mContext;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item_tags, parent,false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
Tags tags = mTagList.get(position);
holder.tvTags.setText(tags.getSubTags());
holder.tvMainTags.setText(tags.getMainTags());
}
#Override
public int getItemCount() {
return mTagList.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder{
private TextView tvMainTags, tvTags;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
tvMainTags = itemView.findViewById(R.id.tvMainTag);
tvTags = itemView.findViewById(R.id.tvTags);
}
}
}
TagsFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tags, container, false);
rvTags = view.findViewById(R.id.rvTags);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvTags.setLayoutManager(linearLayoutManager);
rvTags.hasFixedSize();
tagAdapter = new TagAdapter(tagsList, getContext());
rvTags.setAdapter(tagAdapter);
return view;
}
private void getTagView(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference dbRefTags = firebaseDatabase.getReference().child("Tag");
dbRefTags.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
if (ds.exists()) {
try {
Tags tags = ds.getValue(Tags.class);
tagsList.add(tags);
}catch (Exception e){
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(getContext(), "Bir hata oluştu", Toast.LENGTH_SHORT).show();
}
}
tagAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
There is no error show up when running but i couldn't be able to retrieve data. And i tried firebaseRecyclerView.Adapter also and in the last dependency, i couldn't make it work. I don't know what is wrong in here. how can i solve this?

Get The data with child name ds.child("SubTag").getValue()
dbRefTags.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot parentDS : dataSnapshot.getChildren()) {
Log.d("Tag:", String.valueOf(parentDS.getKey()));
for (DataSnapshot ds : parentDS.getChildren()) {
Tags tags = new Tags();
tags.setMainTag(parentDS.getKey());
tags.setSubTag(ds.child("SubTag").getValue().toString());
Log.d("Tag: -> SubTag)", tags.getSubTag());
tagsList.add(tags);
}
}
tagAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});

Related

How to retrieve data from Firebase and show the childrens one by one in recyclerView

I have 2 clases.One is Groups and the other one is GroupListAdapter. With the method RetrieveGroups i try to get the children of GroupName and show them one by one in recyclerView.
The value of string "retrieveGroupsName" its like in database.
TX!
i
public void RetrieveGroups(){
GroupReF.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (final DataSnapshot ds :dataSnapshot.getChildren()){
String uid = ds.getKey();
DatabaseReference groupRef = GroupReF.child(uid).child("GroupName");
groupRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String retrieveGroupsName = dataSnapshot.getValue().toString();
Log.i(TAG,"value --------+++++++++++++" + retrieveGroupsName);
Groups groups = new Groups(retrieveGroupsName);
groupsList.clear();
groupsList.add(groups);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public class GroupsListAdapter extends RecyclerView.Adapter<GroupsListAdapter.GroupListViewHolder> {
private final String TAG = "Groups adapter Activity";
ArrayList<Groups> groupsList;
public GroupsListAdapter(ArrayList<Groups> groupsList) {
this.groupsList = groupsList;
}
#NonNull
#Override
public GroupsListAdapter.GroupListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.display_group_layout,parent,false);
RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(layoutParams);
GroupListViewHolder groupListViewHolder = new GroupListViewHolder(view);
return groupListViewHolder;
}
#Override
public void onBindViewHolder(#NonNull GroupListViewHolder holder, int position) {
holder.groupName.setText(groupsList.get(position).getGroupName());
}
#Override
public int getItemCount() {
return (groupsList == null) ? 0 : groupsList.size();
}
public class GroupListViewHolder extends RecyclerView.ViewHolder{
public TextView groupName;
public GroupListViewHolder(#NonNull View itemView) {
super(itemView);
groupName = itemView.findViewById(R.id.display_group_name);
}
}
}
public class Groups {
public String groupName;
public Groups(String groupName) {
this.groupName = groupName;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
You should chang your codes like this:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
groupsList.clear();
for(DataSnapshot data : dataSnapshot.getChildren()){
String retrieveGroupsName = data.getValue(String.class);
Log.i(TAG,"value --------+++++++++++++" + retrieveGroupsName);
Groups groups = new Groups(retrieveGroupsName);
groupsList.add(groups);
}
yourAdapter.notifyDataSetChanged();
}

OnChild event Listener is being called multiple times

I am currently using Value Event Listener in my Code to show messages and it does not shows any error but my only problem is when whenever i add a new send or receive a new message my whole list gets updated all the previous messages are called and it uses a lot of memory currently i am taking care of it my clearing recyclerview every time the value event listener is called but now i want to add Child Event Listener in place of value event listener to save memory but whenever i add child event listener my messages are shown multiple times in recyclerview but after i restart the activity there is only one message in recyclerview.
MyCode
MessageActivity.java
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView user_name;
FirebaseFirestore fstore;
FirebaseAuth fAuth;
FirebaseUser fuser;
DatabaseReference reference;
Toolbar toolbar;
ImageButton imageButton;
EditText textsend;
String userID;
MessageAdapter messageAdapter;
List<Chat> mChat;
RecyclerView recyclerView;
String TAG = "MyTag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
fAuth=FirebaseAuth.getInstance();
fstore=FirebaseFirestore.getInstance();
userID = fAuth.getCurrentUser().getUid();
profile_image=findViewById(R.id.profile_image);
user_name=findViewById(R.id.username);
imageButton=findViewById(R.id.btn_send);
textsend=findViewById(R.id.text_send);
recyclerView=findViewById(R.id.recycler_view2);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager= new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
toolbar=findViewById(R.id.myToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
Intent intent=getIntent();
fuser=FirebaseAuth.getInstance().getCurrentUser();
String userid=intent.getStringExtra("userid");
String username= intent.getStringExtra("UserName");
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
user_name.setText(user.getFirst());
if (user.getImageURL().equals("default")){
profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
//and this
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
readMessages(fuser.getUid(), userid, user.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg=textsend.getText().toString();
textsend.setText("");
if (!msg.equals("")){
sendMessage(fuser.getUid(),userid,msg);
}
else {
Toast.makeText(MessageActivity.this,"Empty messages cant be send",Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendMessage(String sender, final String receiver, String message) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
String key = reference.push().getKey();
reference.child(key).setValue(hashMap);
}
private void readMessages(String myid,String userid,String imageurl){
mChat=new ArrayList<>();
reference=FirebaseDatabase.getInstance().getReference("Chats");
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Chat chat= dataSnapshot.getValue(Chat.class);
assert chat!=null;
if (chat.getReceiver().equals(myid) && chat.getSender().equals(userid)||
chat.getReceiver().equals(userid)&&chat.getSender().equals(myid)){
chat.setMessageId(dataSnapshot.getKey());
mChat.add(chat);
Log.d(TAG,"msg "+chat.getMessage());
}
messageAdapter=new MessageAdapter(MessageActivity.this,mChat, imageurl);
recyclerView.setAdapter(messageAdapter);
messageAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
Chat chat=dataSnapshot.getValue(Chat.class);
chat.setMessageId(dataSnapshot.getKey());
mChat.remove(chat);
messageAdapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
/*
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
for (DataSnapshot snapshot:dataSnapshot.getChildren()) {
Chat chat=snapshot.getValue(Chat.class);
assert chat != null;
if (chat.getReceiver().equals(myid) && chat.getSender().equals(userid)||
chat.getReceiver().equals(userid)&&chat.getSender().equals(myid)){
mChat.add(chat);
Log.d(TAG,"msg "+chat.getMessage());
}
messageAdapter=new MessageAdapter(MessageActivity.this,mChat, imageurl);
recyclerView.setAdapter(messageAdapter);
messageAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
*/
}
}
MessageAdapter.java
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
private Context mContext;
private List<Chat> mChat;
String imageurl;
FirebaseUser fuser;
public MessageAdapter(Context mContext, List<Chat> mChat,String imageurl) {
this.mContext = mContext;
this.mChat = mChat;
this.imageurl=imageurl;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT) {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
}
else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat=mChat.get(position);
holder.show_message.setText(chat.getMessage());
if (imageurl.equals("default")){
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(mContext).load(imageurl).into(holder.profile_image);
}
holder.show_message.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
String message_id=chat.getMessageId();
Task<Void> task = Utils.removeUser(message_id);
task.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(mContext,"Message Deleted",Toast.LENGTH_SHORT).show();
}
});
return true;
}
});
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView show_message;
public ImageView profile_image;
public ViewHolder(#NonNull View itemView) {
super(itemView);
show_message=itemView.findViewById(R.id.show_message);
profile_image=itemView.findViewById(R.id.profile_image);
}
}
#Override
public int getItemViewType(int position) {
fuser= FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fuser.getUid())){
return MSG_TYPE_RIGHT;
}
else {
return MSG_TYPE_LEFT;
}
}
}
Use below code. Remove ValueEventListener calls. You should add your logic inside onChildAdded
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Chat chat= dataSnapshot.getValue(Chat.class);
assert chat!=null;
if (chat.getReceiver().equals(myid) && chat.getSender().equals(userid)||
chat.getReceiver().equals(userid)&&chat.getSender().equals(myid)){
mChat.add(chat);
Log.d(TAG,"msg "+chat.getMessage());
}
messageAdapter=new MessageAdapter(MessageActivity.this,mChat, imageurl);
recyclerView.setAdapter(messageAdapter);
messageAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Users information not displaying in recyclerview

I'm working on this project where users are able to upload more than one character image along with other information. Such as the name of the character, what the character will do, the color of the character and its height. Now everything saves successfully in the database. However, when I want to display all of the character's information on the user's profile page, using a recyclerView, the saved information in the database will not display on the user's profile page. Below is my code. Thanks in advance
//Users profile page
#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);
mUploads = new ArrayList<>();
mAdapter = new ImageAdapter(getApplicationContext(), mUploads);
recyclerView = findViewById(R.id.recyclerView);
//recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
if (firebaseAuth != null) {
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
//upload = findViewById(R.id.button_upload);
//button2 = findViewById(R.id.submit);
//imageView = findViewById(R.id.view_image);
//upload.setOnClickListener(this);
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
String imageUrl = (String) postsnapshot.child("mImageUrl").getValue();
mUploads.add(imageUrl);
//mUploads = new ArrayList<>();
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
//Model Upload.class
public class Upload {
private String mImageUrl;
public Upload(){
//Empty constructor needed
}
public Upload (String imageUrl){
mImageUrl=imageUrl;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
}
// Image adapter class
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder>{
private Context mContext;
private List<String> mUploads;
public ImageAdapter(Context context, List<String> uploads){
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View V = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
return new ImageViewHolder(V);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
String uploadCurrent=mUploads.get(position);
Picasso.get().load(uploadCurrent).fit().centerCrop().into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.imageview);
}
}
}
Change this:
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
String imageUrl = (String) postsnapshot.child("mImageUrl").getValue();
mUploads.add(imageUrl);
//mUploads = new ArrayList<>();
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
into this:
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
String imageUrl = postsnapshot.child("mImageUrl").getValue(String.class);
mUploads.add(imageUrl);
//mUploads = new ArrayList<>();
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
If you want to read inside the children of children, you need to do double loop like this.
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot : postsnapshot.getChildren()) {
String imageUrl = snapshot.child("mImageUrl").getValue(String.class);
mUploads.add(imageUrl);
//mUploads = new ArrayList<>();
}
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
Edited:
If you want to pass all of them, you need to change a bit of your model class
public class Upload {
private String mImageUrl;
private String Character_Name;
private String What_Character_Does;
private String color;
private String height;
public Upload() {
//Empty constructor needed
}
public Upload(String imageUrl) {
mImageUrl = imageUrl;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
public String getCharacter_Name() {
return Character_Name;
}
public void setCharacter_Name(String character_Name) {
Character_Name = character_Name;
}
public String getWhat_Character_Does() {
return What_Character_Does;
}
public void setWhat_Character_Does(String what_Character_Does) {
What_Character_Does = what_Character_Does;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
}

Data is not loaded from Firebase database to RecyclerView

I am using Firebase database + FirebaseUI to load certain data from Firebase to Android, but the data is not shown in recycler View.
However, by logging the getCount(), I can see that "2" is returned, which means there is data present, but not visible in recyclerView.
Here is my Model class:
public SlideshowModel(){
}
public SlideshowModel(String title, String desc, String image, String date) {
this.title = title;
this.desc = desc;
this.image = image;
this.date = date;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public String getImage() {
return image;
}
public String getDate() {
return date;
}
}
Here is my Adapter class:
public class SlideShowAdapter extends FirebaseRecyclerAdapter<SlideshowModel, SlideShowAdapter.ViewHolder> {
public SlideShowAdapter(#NonNull FirebaseRecyclerOptions<SlideshowModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, final int position, #NonNull SlideshowModel model) {
Picasso.get().load(R.drawable.notification).fit().centerCrop().placeholder(R.drawable.placeholders).into(holder.image);
holder.title.setText(model.getTitle());
holder.description.setText(model.getDesc());
holder.date.setText(model.getDate());
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase.getInstance().getReference("notifications").child(getRef(position).getKey()).removeValue();
}
});
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_layout_notifications,
parent, false);
return new ViewHolder(view);
}
class ViewHolder extends RecyclerView.ViewHolder {
ImageView image, notif_icon, share_image, download_image, delete;
TextView title, description, date;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.notif);
title = itemView.findViewById(R.id.title);
description = itemView.findViewById(R.id.description);
date = itemView.findViewById(R.id.date);
delete = itemView.findViewById(R.id.delete_notif);
Here is my Activity:
List<SlideshowModel> slideshowModelList;
SlideShowAdapter adapter;
ProgressDialog pd;
RecyclerView recycler_view;
AdView adView;
DatabaseReference dbProducts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_notif);
recycler_view = findViewById(R.id.recycler_view);
pd = new ProgressDialog(this);
recycler_view.setHasFixedSize(true);
setTitle("Show Notifications");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
slideshowModelList = new ArrayList<>();
dbProducts = FirebaseDatabase.getInstance().getReference("notifications");
// adView = findViewById(R.id.adView);
// MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713");
// AdRequest adRequest = new AdRequest.Builder().build();
// adView.loadAd(adRequest);
if (isNetworkConnected()) {
pd.setMessage("Loading");
pd.setCanceledOnTouchOutside(false);
pd.show();
final DatabaseReference dbProducts = FirebaseDatabase.getInstance().getReference("notifications");
Log.e("path1", dbProducts.toString());
dbProducts.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
// Toast.makeText(ShowNotifActivity.this, "Child Changed", Toast.LENGTH_SHORT).show();
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dbProducts.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists() || !slideshowModelList.isEmpty()) {
for (DataSnapshot productSnapshot : dataSnapshot.getChildren()) {
SlideshowModel p = productSnapshot.getValue(SlideshowModel.class);
slideshowModelList.add(p);
}
FirebaseRecyclerOptions<SlideshowModel> options =
new FirebaseRecyclerOptions.Builder<SlideshowModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("notifications"), SlideshowModel.class)
.build();
adapter = new SlideShowAdapter(options);
recycler_view.setAdapter(adapter);
// adapter = new SlideShowAdapter(SlideshowModel)
String current_counts = String.valueOf(dataSnapshot.getChildrenCount());
Log.e("Curr_Count : ", current_counts);
Collections.reverse(slideshowModelList);
recycler_view.setAdapter(adapter);
// lovelyProgressDialog.dismiss();
pd.dismiss();
}
else {
Toast.makeText(ShowNotifActivity.this, "No Notifications Available", Toast.LENGTH_SHORT).show();
pd.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "Some Error Occured", Toast.LENGTH_SHORT).show();
pd.dismiss();
}
});
} else {
pd.dismiss();
new AlertDialog.Builder(getApplicationContext())
.setTitle("No Internet Available")
.setMessage("Please connect to Internet to get the Notifications")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recycler_view.setLayoutManager(linearLayoutManager); // set LayoutManager to RecyclerView
}
Update
I initialised the Constructors in AdapterClass, but still no luck.
Everytime you set data to your adapter you need to call
notifyDataSetChanged()
To refresh the adapter's data.
Useful link

Items are added in RecyclerView but not visible

I'm retrieving list of few users which being added and but are not visible. When I added Toast on item click it shows data null and android studio give warning also in model class the constructor is never used .I'm using ChildEventListener and a custom adapter
Custom adapter code
class CustomMemberAdapter extends RecyclerView.Adapter<SetMeeting_2.User_MemberHolder>{
List<UserModel_member_DP_NAME> mList;
CustomMemberAdapter(List<UserModel_member_DP_NAME> mList) {
this.mList = mList;
}
#Override
public User_MemberHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_meeting_userlist_item,parent,false);
return new User_MemberHolder(v);
}
#Override
public void onBindViewHolder(User_MemberHolder holder, int position) {
final UserModel_member_DP_NAME model = mList.get(position);
holder.txt.setText(model.getName());
Picasso.with(holder.itemView.getContext()).load(model.getDp()).into(holder.img);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), String.valueOf(model.getName()), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mList.size();
}
}
Model Class code
private static class UserModel_member_DP_NAME {
String dp,name;
UserModel_member_DP_NAME(){}
UserModel_member_DP_NAME(String dp, String name) { //never used warning
this.dp = dp;
this.name = name;
}
public String getDp() {
return dp;
}
public void setDp(String dp) {
this.dp = dp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ChildEventListener code
mDatabase = FirebaseDatabase.getInstance().getReference();
defaultQuery = mDatabase.child("users").child(current_user).child("directorylist");
defaultQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
UserModel_member_DP_NAME model = dataSnapshot.getValue(UserModel_member_DP_NAME.class);
memberList.add(model);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
recyclerView.setAdapter(adapter);
here is my database structure

Categories

Resources