How to display recycler view on start of app? - java

I had tried to retrieve data from firebase database and show in recyclerview.
Everything is going perfect. Now in my firebase database has lots of node for recyclerview and each node has image link and now i just seen that recyclerview only show when all images are loaded from firebase database first.
Database has a string and long both types of values.
But No any text values display until all images are not loaded. Here i shows what am i tried.
So the question is how to show recyclerview step by step.
if Text("string") is loaded than why it waiting for images loading?
mAdapter = new PostAdapter(MainActivity.this);
query = PostRef
.orderByChild("timestamp")
.limitToLast(mPostsPerPage);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Post> userModels = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
String o=userSnapshot.getKey();
userModels.add(userSnapshot.getValue(Post.class));
}
mAdapter.addAll(userModels);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
this is my adapter
public class PostAdapter extends RecyclerView.Adapter<PostHolder>
{
List<Post> mPost;
Context mContext;
Boolean likecheck=false;
public PostAdapter(Context c) {
this.mPost = new ArrayList<>();
mContext=c;
}
#NonNull
#Override
public PostHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new PostHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.all_post_layout, viewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull final PostHolder postHolder, final int i) {
postHolder.setData(mPost.get(i));
final String PostKey=mPost.get(i).getPostid();
FirebaseAuth mAuth=FirebaseAuth.getInstance();
final String currentUserID=mAuth.getCurrentUser().getUid();
final DatabaseReference post=FirebaseDatabase.getInstance().getReference().child("Posts");
post.child(PostKey).child("postimg").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
String postimagelink =dataSnapshot1.getValue().toString();
postimagelist.add(postimagelink);
}
String[] urls =postimagelist.toArray(new String[postimagelist.size()]);
postHolder.mPager.setAdapter(new SlidingImage_Adapter(mContext,urls));
postHolder.indicator.setViewPager(postHolder.mPager);
final float density = mContext.getResources().getDisplayMetrics().density;
postHolder.indicator.setRadius(5 * density);
postHolder.NUM_PAGES = urls.length;
postHolder.indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageSelected(int position) {
postHolder.currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
public int getItemCount() {
return mPost.size();
}
public void addAll(List<Post> newPost) {
int initialSize = mPost.size();
mPost.addAll(newPost);
notifyItemRangeInserted(initialSize, newPost.size());
}
public String getLastItemId() {
return mPost.get(mPost.size() - 1).getPostid();
}
}
viewholder
public class PostHolder extends RecyclerView.ViewHolder
{
AutoLinkTextView description;
TextView postfullname;
ViewPager mPager;
int currentPage = 0;
int NUM_PAGES = 0;
CirclePageIndicator indicator;
Context context;
public PostHolder(#NonNull View itemView) {
super(itemView);
postfullname = itemView.findViewById(R.id.user_post_full_name);
description = itemView.findViewById(R.id.user_post_description);
mPager = (ViewPager) itemView.findViewById(R.id.pager);
indicator = (CirclePageIndicator)itemView.findViewById(R.id.indicator);
}
public void setData(Post post)
{
description.setText(post.getDescription());
postfullname.setText(post.getFirstname()+" "+post.getLastname());
}
}

Ok, I see a couple of problems with your adapter.
First
public void addAll(List<Post> newPost) {
int initialSize = mPost.size();
mPost.addAll(newPost);
notifyItemRangeInserted(initialSize, newPost.size());
}
Here, you are passing a list of Post as a parameter, you are using mPost.size() wich will not do anything there, the addAll method can be replaced with just add and the newPost.size() could be empty as well as the mPost.size()
Second
#Override
public int getItemCount() {
return mPost.size();
}
You should also handle if the list is empty
#Override
public int getItemCount() {
if(mPost.size() > 0){
return mPost.size();
}else{
return 0;
}
}
Third
All your firebase code inside your onBindViewHolder is wrong because while you are binding the data into each row, you are also trying to get each time the values with firebase. Doing this will lend to multiple firebase calls to get the data for just 1 row instead of getting all the data that you want to show.
The solution of this is to do all your firebase logic in your main activity and pass the data to the adapter to set the values.
To solve this with a more cleaner approach, pass your Array as a parameter in your Adapter Constructor, delete the addAll method and do this.
public PostAdapter(Context c, List<Post> mPost) {
this.mPost = mPost
mContext=c;
}
Then as I said, delete all the firebase code from your onBindViewHolder and place it in your MainActivity
With the constructor changed of your Adapter, you should now use your data fetched from firebase like this to work with your adapter.
query = PostRef
.orderByChild("timestamp")
.limitToLast(mPostsPerPage);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Post> userModels = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
String o=userSnapshot.getKey();
userModels.add(userSnapshot.getValue(Post.class));
}
mAdapter = new PostAdapter(MainActivity.this,userModels)
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you want to notify your adapter about any change. Just make a global declaration of the adapter like
private PostAdapter adapter;
and then just use
adapter.notifySetDataChanged();
Make sure the instance has been executed at least once.
mAdapter = new PostAdapter(MainActivity.this,userModels);

Firebase has released firebaseRecyclerViewAdapter class. This will do a lot of the work for you.
the adapter takes 4 input arguments:
Object class
List item layout resource
Viewholder Class
Query/firebase reference
the populateViewHolder method is all that will be required
FirebaseRecyclerViewAdapter<Object, ObjectViewHolder> adapter = new FirebaseRecyclerViewAdapter<Object, ObjectViewHolder>
(Object.class, android.R.layout.*list_item_layout*, ObjectViewHolder.class, objectQuery) {
public void populateViewHolder(ObjectViewHolder ObjectViewHolder, Object Object) {
//populate your views, example:
ObjectViewHolder.textview.setText(object.getTextOne());
}
};
Then set the adapter:
recycler.setAdapter(mAdapter);
More info on this Firebase RecyclerView Adapter

Related

Passed data from Activity to Adapter, but when I try to use data as string, it displays as null

I have passed data from my Activity to My Adapter. When I debug, I can see the correct data has successfully passed to my adapter, but when I attempt to use it as a string ( for example, if I want to set the text as the data I just passed), it shows as null.
On the line that says " this.uniquesharedIds = uniquesharedId;" - the "uniqiuesharedIds" is showing as null.
"uniquesharedId" shows has the successfully passed data.
I need to be able to use the string of "uniqiuesharedIds."
Sorry if this is a silly question. Sending data from Activities to Adapters always confuses me and Im not able to find a ton of documentation/videos on the topic. Thank you.
My Activity In the On Create Method
myadapter = new Invite_Contributors_Adapter(contributorInviteList, getIntent().getStringExtra("uniquesharedId"));
The Adapter
public class Invite_Contributors_Adapter extends RecyclerView.Adapter<Invite_Contributors_Adapter.myviewholder> {
private ArrayList<Model_Invite_Contributors_List> model_invite_contributors_lists = new ArrayList<>();
FirebaseAuth mAuth;
private FirebaseUser currentuser;
private DatabaseReference UsersReference;
Context context;
String uniquesharedIds;
private InviteContributorsInterface inviteContributorsInterface;
public Invite_Contributors_Adapter() {
}
public void updateInviteList (ArrayList list) {
model_invite_contributors_lists .clear();
model_invite_contributors_lists .addAll(list);
notifyDataSetChanged();
}
public Invite_Contributors_Adapter(ArrayList<Model_Invite_Contributors_List>model_invite_contributors_lists, String uniquesharedId) {
this.model_invite_contributors_lists = model_invite_contributors_lists;
this.uniquesharedIds = uniquesharedId;
}
#NonNull
#Override
public Invite_Contributors_Adapter.myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout_invite_contributors_list, parent, false);
return new myviewholder(view);
}
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.setData(model_invite_contributors_lists.get(position));
mAuth = FirebaseAuth.getInstance();
holder.Name.setText(uniquesharedIds);
}
#Override
public int getItemCount() {
return model_invite_contributors_lists.size();
}
static class myviewholder extends RecyclerView.ViewHolder implements DialogInterface.OnClickListener {
TextView Name;
CircleImageView profileImageView;
public myviewholder(#NonNull View itemView) {
super(itemView);
Name = itemView.findViewById(R.id.contributor_name);
profileImageView = itemView.findViewById(R.id.member_profile_picture);
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
public void setData(Model_Invite_Contributors_List model) {
FirebaseUser currentuser;
currentuser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference NameRef = FirebaseDatabase.getInstance().getReference(Strings.UsersReference);
NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//this is very important. this says to not show the current user in the list of people to invite as a contributor.//
if (currentuser.getUid().equals(model.getUser_Id())){
ViewGroup.LayoutParams params = itemView.getLayoutParams();
params.height = 0;
itemView.setLayoutParams(params);
} else {
for(DataSnapshot ds : dataSnapshot.getChildren())
{
itemView.setVisibility(View.VISIBLE);
String profileImageString;
profileImageString = model.getProfileimage();
Glide.with(profileImageView.getContext()) //pulling in image and telling the image which imageview to go to once it comes in from the database
.load(profileImageString)
.placeholder(R.drawable.circle_placeholder)
.error(R.drawable.circle_placeholder)
.into(profileImageView);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
public void setInterface (Invite_Contributors_Adapter.InviteContributorsInterface inviteContributorsInterface) {
this.inviteContributorsInterface = inviteContributorsInterface;
}
public interface InviteContributorsInterface{
}
}
Are you using any primary constructor of the adapter like this?
myadapter = new Invite_Contributors_Adapter();
If yes, then that's where the problem is. If you're initializing object with two different constructors then you'll get the value of the object which you initialized later.
Make sure to check the adapter object & then proceed.

onBindview Holder of RecyclerView is not working for second position but i have count three in getItemCount

Iam getting data from firebase and it is populated in userMessageList.adapter is notified and getItemCount is showing correct count but onBindViewHolder only run once for 1st postion of userMessage list. onBindViewHolder is not working for further positions or data
i have got no solution related to my problem
THIS IS MY ADAPTER CLASS
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder> {
private List <Messages> userMessagesList;
private DatabaseReference firebaseDatabase,users;
private FirebaseAuth auth;
public MessageAdapter(List<Messages> userMessagesList){
this.userMessagesList = userMessagesList;
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.custom_messages_layout,viewGroup,false);
auth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder messageViewHolder, int i) {
String messageSenderID = auth.getCurrentUser().getUid();
Messages messages = userMessagesList.get(i);
String fromUserID = messages.getFrom();
String fromMessageType = messages.getType();
users = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild("image")){
final String receiverImage = dataSnapshot.child("image").getValue().toString();
Picasso.get()
.load(receiverImage)
.placeholder(R.drawable.profile_image)
.into(messageViewHolder.receiverProfileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if(fromMessageType.equals("text")){
messageViewHolder.receiverMessageText.setVisibility(View.INVISIBLE);
messageViewHolder.receiverProfileImage.setVisibility(View.INVISIBLE);
if(fromUserID.equals(messageSenderID)){
messageViewHolder.senderMessageText.setBackgroundResource(R.drawable.sender_messages_layout);
messageViewHolder.senderMessageText.setTextColor(Color.BLACK);
messageViewHolder.senderMessageText.setText(messages.getMessage());
}
else{
messageViewHolder.receiverMessageText.setVisibility(View.INVISIBLE);
messageViewHolder.receiverProfileImage.setVisibility(View.VISIBLE);
messageViewHolder.receiverMessageText.setVisibility(View.VISIBLE);
messageViewHolder.receiverMessageText.setBackgroundResource(R.drawable.receiver_messeges_layout);
messageViewHolder.receiverMessageText.setTextColor(Color.BLACK);
messageViewHolder.receiverMessageText.setText(messages.getMessage());
}
}
}
#Override
public int getItemCount() {
return userMessagesList.size();
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
public TextView senderMessageText, receiverMessageText;
public CircleImageView receiverProfileImage;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
senderMessageText =itemView.findViewById(R.id.sender_message_text);
receiverMessageText = itemView.findViewById(R.id.receiver_message_text);
receiverProfileImage =itemView.findViewById(R.id.message_profile_image);
}
}
}
THIS IS ACTIVITY CODE WHERE IAM POPULATING THE userMessageList
rootRef.child("Messages")
.child(messageSenderID).
child(messageReceivedID)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot
dataSnapshot, #Nullable String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
messagesList.add(messages);
messageAdapter.notifyDataSetChanged();
}
}
As Pemba Tamang in comment above rightly said you should not have any network or database related code in your adapter.
Algorithm to solve your problem:
1. Fetch list of Messages outside of adapter.
2. Subscribe for child change outside of adapter.
3. When child changed go to view model, find this Message by it's id and update this info.
4. Update your adapter
Also will be good if you will update your adapter with DiffUtils. It will bind only changed child, not all. See: https://developer.android.com/reference/android/support/v7/util/DiffUtil

Why aren't my images being displayed after logging in with different accounts?

I am trying to retrieve images and text from Firebase to my Recycle view and this works well. The only problem I'm experiencing is the images are not being loaded if I login with different phones but the text data are being loaded. Any help would be appreciated.
Gets data from Firebase
//Retrieves information stored inside Post node...
public void fetchUserInfo() {
postRef = FirebaseDatabase.getInstance().getReference().child("Post");
postRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
value = ds.getValue(Post.class);
postList.add(value);
}
adapter = new Adapter(Shop_Activity.this, postList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i("Error", databaseError.toString());
}
});
}
}
In this method I saved the necessary information inside a dictionary and uploaded it to Firebase
//saves user image and description inside firebase
public void saveToFirebase(){
String userId = mAuth.getCurrentUser().getUid();
postDictionary.put("desc", descriptionEditText.getText().toString());
postDictionary.put("image", selectedImageUri.toString());
postDictionary.put( "id",userId);
productsDatabaseRef.child("Post").push().setValue(postDictionary);
Intent intent = new Intent(Upload_Post.this, Shop_Activity.class);
startActivity(intent);
}
Adapter
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
ArrayList<Post> userPost;
public Adapter(Context context, ArrayList<Post> userPost){
this.context = context;
this.userPost = userPost;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.shop_layout_design,viewGroup, false));
}
//this is where you set the value for the ui elements
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.desc.setText(userPost.get(i).getdesc());
Glide.with(this.context).load(userPost.get(i).getimage()).into(viewHolder.image);
//Picasso.get().load(userPost.get(i).getimage()).into(viewHolder.image);
}
#Override
public int getItemCount() {
return userPost.size();
}
//links up ui elements
class ViewHolder extends RecyclerView.ViewHolder{
TextView desc;
TextView id;
ImageView image;
public ViewHolder(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.post_title);
desc = itemView.findViewById(R.id.post_desc);
image = itemView.findViewById(R.id.post_image);
}
}
}

How to remove one item on my data base when I click on my "delete" button?

I'm new to android studio, and for my android application I'm use Firebase.
I want to remove one item from my database when I click on my button delete(btnDelete).
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Query query= FirebaseDatabase.getInstance()
.getReference().child("users").child(uid).child("foto");
public ViewHolder(#NonNull View itemView) {
super(itemView);
foto_root=itemView.findViewById(R.id.foto_root);
tvNameF=itemView.findViewById(R.id.tvNameF);
tvPhoneF=itemView.findViewById(R.id.tvPhoneF);
tvAdressF=itemView.findViewById(R.id.tvAdressF);
tvMailF=itemView.findViewById(R.id.tvMailF);
tvNoteF=itemView.findViewById(R.id.tvNoteF);
btnDelete=itemView.findViewById(R.id.btnDelete);
}
public void setTvNameF(String tvNameFs){
tvNameF.setText(tvNameFs);
}
public void setTvPhoneF(String tvPhoneFs){
tvPhoneF.setText(tvPhoneFs);
}
}
/*
get on dataBase
*/
private void fetch() {
FirebaseRecyclerOptions<Foto> options=
new FirebaseRecyclerOptions.Builder<Foto>().setQuery(query, snapshot -> new Foto(
snapshot.child("id").getKey(),
snapshot.child("name").getValue().toString(),
snapshot.child("phone").getValue().toString(),
snapshot.child("adress").getValue().toString(),
snapshot.child("email").getValue().toString(),
snapshot.child("note").getValue().toString())).build();
adapter = new FirebaseRecyclerAdapter<Foto, FotoActivity.ViewHolder>(options) {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.foto_item,parent,false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder viewHolder, int i, #NonNull Foto foto) {
viewHolder.setTvNameF(foto.getNameF());
viewHolder.setTvPhoneF(foto.getPhoneF());
viewHolder.setTvAdressF(foto.getAdressF());
viewHolder.setTvMailF(foto.getEmailF());
viewHolder.setTvNoteF(foto.getNoteF());
viewHolder.btnDelete.setOnClickListener(v -> {
delete();
});
}
};
rvFoto.setAdapter(adapter);
}
private void delete() {
Toast.makeText(FotoActivity.this, "remove", Toast.LENGTH_SHORT).show();
}
private void viewRecyclerViewFoto() {
linearLayoutManager=new LinearLayoutManager(this);
rvFoto.setLayoutManager(linearLayoutManager);
rvFoto.setHasFixedSize(true);
}
}
// adapter class
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
private void setInfoFoto() {
DatabaseReference databaseReference=
FirebaseDatabase.getInstance().getReference().child("users").child(uid).child("foto").push();
Map<String,Object> mapFoto=new HashMap<>();
mapFoto.put("id",databaseReference.getKey());
mapFoto.put("name",etNameF.getText().toString());
mapFoto.put("phone",etPhoneF.getText().toString());
mapFoto.put("adress",etAdressF.getText().toString());
mapFoto.put("email",etMailF.getText().toString());
mapFoto.put("note",etNoteF.getText().toString());
databaseReference.setValue(mapFoto);
}
I want remove one item from foto and not all database.
Just use the following in your delete function, this will delete the value of "phone" node. You will need to know the uid of the user you want to delete otherwise you can replace it with a database node reference but then that will delete phone from all the user ids. Basically you will listen to the foto node, get all the push ids and loop through the push ids to remove the desired node.
Declare The Variables
private static final String TAG = "TestActivity";
private DatabaseReference fbDbRef;
OnCreate
final String uid = "youruid";
fbDbRef = FirebaseDatabase.getInstance().getReference().child("users")
.child(uid).child("foto");
Your Function
private void delete() {
fbDbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
final String pushKey = snapshot.getKey();
Log.d(TAG, "pushKey: " + pushKey);
fbDbRef.child(pushKey).child("phone").removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

why realtime database can not work in my recyclerview

I tried to change the database in the console firebase but the data in my adapter unchanged, recylerview was only changed when the application is closed and opened again
MainActivity.java
public class MainActivity extends AppCompatActivity {
private List<ModelDB> dbList = new ArrayList<>();
private AdapterDB adapter;
private RecyclerView recyclerView;
FirebaseDatabase database;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFirebase();
getData();
initRecylerView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_person:
Intent intent = new Intent(getApplicationContext(),RegisterActivity.class);
startActivity(intent);
break;
default:
Toast.makeText(getApplicationContext(),"lalalala",Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
private void initFirebase(){
database = FirebaseDatabase.getInstance();
reference = database.getReference("user");
}
private void initRecylerView(){
recyclerView = (RecyclerView)findViewById(R.id.rv_list);
recyclerView.setHasFixedSize(true);
adapter = new AdapterDB(dbList);
recyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
}
private void getData() {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//loop data all user
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
//instance object to get and set data
ModelDB modelDB = postSnapshot.getValue(ModelDB.class);
//adding data list from object
dbList.add(modelDB);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
AdapterDB.java
public class AdapterDB extends RecyclerView.Adapter<AdapterDB.MyViewHolder> {
private List<ModelDB> modelDBList;
public AdapterDB(List<ModelDB> modelDBList) {
this.modelDBList = modelDBList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_data,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ModelDB modelDB = modelDBList.get(position);
holder.tv_nama.setText(modelDB.getNama());
holder.tv_alamat.setText(modelDB.getAlamat());
}
#Override
public int getItemCount() {
return modelDBList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_nama, tv_alamat;
public MyViewHolder(View itemView) {
super(itemView);
tv_nama = (TextView) itemView.findViewById(R.id.tv_nama);
tv_alamat = (TextView) itemView.findViewById(R.id.tv_alamat);
}
}
}
You need to kind of let the adapter know that the data has changed and that the UI has to be refreshed or whatever. The OnDataChange in your code should be like this (check the last line within the method) -
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//loop data all user
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
//instance object to get and set data
ModelDB modelDB = postSnapshot.getValue(ModelDB.class);
//adding data list from object
dbList.add(modelDB);
adapter.notifyDataSetChanged();
}
}
This should do the trick assuming there are no other bugs in some other parts of your code

Categories