Recycler view adapter now displaying data in fragment - java

I am trying to display data from my database in my fragment through recycler view. I used a for loop to go through all the users in my database. All the users who are neither friends nor have sent requests should be displayed as implemented in the if condition of fragment class. The code for fragment class is written below.
public class AddMemberFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private View view ;
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
String userId;
String n_team ;
ArrayList<Friend> friends;
public AddMemberFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.addnewfriend_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
userId = firebaseUser.getUid();
ManageTeamTabbedActivity activity = (ManageTeamTabbedActivity) getActivity();
n_team = activity.getMyData();
mRecyclerView = (RecyclerView) getView().findViewById(R.id.addNewFriend);
//mRecyclerView.setHasFixedSize(true);//
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
friends = new ArrayList<>();
mAdapter = new AddMemberAdapter(getActivity(), friends, n_team) ;
mRecyclerView.setAdapter(mAdapter);
mRootRef.child("users");
mRootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<Friend> friendArrayList = new ArrayList<>();
DataSnapshot friendsData = dataSnapshot.child(firebaseUser.getUid()).child("friends");
DataSnapshot requests = null;
DataSnapshot currentFriends = null;
if (friendsData.hasChild("requests")) {
requests = dataSnapshot.child(firebaseUser.getUid()).child("friends").child("requests");
}
if (friendsData.hasChild("currentFriends")) {
currentFriends = dataSnapshot.child(firebaseUser.getUid()).child("friends").child("currentFriends");
}
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
Log.d("demo", "USERID " + FirebaseAuth.getInstance().getCurrentUser().getUid());
Friend friend = new Friend();
if ((userSnapshot.getKey().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())) || (requests != null && requests.hasChild(userSnapshot.getKey()))
|| (currentFriends != null && currentFriends.hasChild(userSnapshot.getKey()))) {
} else {
friend.setId(userSnapshot.getKey());
friend.setFriendName((String) userSnapshot.child("profiles").child("fname").getValue());
friendArrayList.add(friend);
}
}
friends = friendArrayList;
if (friends != null && !friends.isEmpty()) {
mAdapter.setFriendList(friends);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
And the corresponding adapter code is written here :
public class AddMemberAdapter extends RecyclerView.Adapter<AddMemberAdapter.RecyclerViewHolder>{
private ArrayList<Friend> mData;
private Context mContext;
private FirebaseAuth auth;
private String u_team ;
public AddMemberAdapter(Context mContext, ArrayList<Friend> friendList , String u_team) {
this.mData = friendList;
this.mContext = mContext;
this.u_team= u_team;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.addnewfriend_layout, parent, false);
AddMemberAdapter.RecyclerViewHolder viewHolder = new AddMemberAdapter.RecyclerViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, final int position) {
final Friend frnd =(Friend) mData.get(position);
holder.friendName.setText(frnd.getFriendName());
holder.addFriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
frnd.setStatus("sent");
final DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final String UID = firebaseUser.getUid();
mRootRef.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mRootRef.child("users").child(UID).child("friends").child("requests").child(frnd.getId()).setValue(frnd);
Friend temp = new Friend();
temp.setId(firebaseUser.getUid());
temp.setFriendName(firebaseUser.getDisplayName());
temp.setStatus("received");
mRootRef.child("users").child(frnd.getId()).child("friends").child("requests").child(firebaseUser.getUid()).setValue(temp);
mData.remove(frnd);
notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView friendName;
ImageButton addFriend;
public RecyclerViewHolder(View itemView) {
super(itemView);
friendName = (TextView)itemView.findViewById(R.id.textViewFriendName);
addFriend = (ImageButton) itemView.findViewById(R.id.imagebuttonFriendAdd);
}
}
public void setFriendList(ArrayList<Friend> friendList){
this.mData = friendList;
notifyDataSetChanged();
}
}
The output I am getting is attached here.
Users who are not friends and have not been sent friend requests by the current user should have been displayed in this Add New Member fragment through this RecyclerView. I tried to debug it myself and removed the if condition but it did not work either. Please guide how to display it. The
The database screenshot is attached as well.

I could not find a problem with your firebase query and the data-extraction techniques, however, with this data structure, as the list grows you will have a difficult time getting the list of your friends. From my understanding, it is just taking a lot of time to display the list in that fragment.
Also, you might consider setting up the adapter with the RecyclerView while you are initializing the RecyclerView.
You might consider doing something like the following.
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
userId = firebaseUser.getUid();
ManageTeamTabbedActivity activity = (ManageTeamTabbedActivity) getActivity();
n_team = activity.getMyData();
mRecyclerView = (RecyclerView) getView().findViewById(R.id.addNewFriend);
// mRecyclerView.setHasFixedSize(true); // Remove this line
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
// Set the adapter here with an empty list first.
friends = new ArrayList<>();
mAdapter = new AddMemberAdapter(getActivity(), friends, n_team);
mRecyclerView.setAdapter(mAdapter);
mRootRef.child("users");
mRootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<Friend> friendArrayList = new ArrayList<>();
DataSnapshot friendsData = dataSnapshot.child(firebaseUser.getUid()).child("friends");
DataSnapshot requests = null;
DataSnapshot currentFriends = null;
if (friendsData.hasChild("requests")) {
requests = dataSnapshot.child(firebaseUser.getUid()).child("friends").child("requests");
}
if (friendsData.hasChild("currentFriends")) {
currentFriends = dataSnapshot.child(firebaseUser.getUid()).child("friends").child("currentFriends");
}
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
Log.d("demo", "USERID " + FirebaseAuth.getInstance().getCurrentUser().getUid());
Friend friend = new Friend();
if ((userSnapshot.getKey().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())) || (requests != null && requests.hasChild(userSnapshot.getKey()))
|| (currentFriends != null && currentFriends.hasChild(userSnapshot.getKey()))) {
} else {
friend.setId(userSnapshot.getKey());
friend.setFriendName((String) userSnapshot.child("profiles").child("fname").getValue());
friendArrayList.add(friend);
}
}
friends = friendArrayList;
if (friends != null && !friends.isEmpty()) {
mAdapter.setFriendList(friends); // Set the friend list to the adapter when the list is loaded.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
And in your adapter, you will need a function to set the friends' list and call notifyDataSetChanged().
// In your adapter class, add the following method.
public void setFriendList(ArrayList<Friend> friendList) {
this.mData = friendList;
notifyDataSetChanged();
}
I hope that helps.

Related

How to Fetch data form firebase to fragments in Recyclerview?

Java
Here is the code of fragment of my app and when I run it my app crashes as soon as I start the app got Customer home fragment it crashes, In logcat its showing there is error in CustomerHomefragemnt so here's the code as I am not being able to troubleshoot it Please answer if someone can help. Here is my fragment code`
public class CustomerHomeFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
RecyclerView recyclerView;
private List<UpdateDishModel> updateDishModelList;
private CustomerHomeAdapter adapter;
String State, City, Sub;
DatabaseReference dataaa, databaseReference;
SwipeRefreshLayout swipeRefreshLayout;
SearchView searchView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_customerhome, null);
setHasOptionsMenu(true);
recyclerView = v.findViewById(R.id.recycle_menu);
recyclerView.setHasFixedSize(true);
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.move);
recyclerView.startAnimation(animation);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
updateDishModelList = new ArrayList<>();
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipelayout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark, R.color.green);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
dataaa = FirebaseDatabase.getInstance()
.getReference("Customer").child(userid);
dataaa.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Customer cust = dataSnapshot.getValue(Customer.class);
State = cust.getState();
City = cust.getCity();
Sub = cust.getSuburban();
customermenu();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
return v;
}
#Override
public void onRefresh() {
customermenu();
}
private void customermenu() {
swipeRefreshLayout.setRefreshing(true);
DatabaseReference databaseReference =
FirebaseDatabase.getInstance().getReference("FoodSupplyDetails")
.child(State).child(City).child(Sub);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
updateDishModelList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
UpdateDishModel updateDishModel =
snapshot1.getValue(UpdateDishModel.class);
updateDishModelList.add(updateDishModel);
}
}
adapter = new CustomerHomeAdapter(getContext(), updateDishModelList);
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
swipeRefreshLayout.setRefreshing(false);
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
private void search(final String searchtext) {
ArrayList<UpdateDishModel> mylist = new ArrayList<>();
for (UpdateDishModel object : updateDishModelList) {
if (object.getDishes().toLowerCase().contains(searchtext.toLowerCase())) {
mylist.add(object);
}
}
adapter = new CustomerHomeAdapter(getContext(), mylist);
recyclerView.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search, menu);
MenuItem menuItem = menu.findItem(R.id.Searchdish);
searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search Dish");
}
}
```
`here is my Homeadapter code`
public class CustomerHomeAdapter extends
RecyclerView.Adapter<CustomerHomeAdapter.ViewHolder>
{
private Context mcontext;
private List<UpdateDishModel>updateDishModellist;
DatabaseReference databaseReference;
public CustomerHomeAdapter(Context context,List<UpdateDishModel>updateDishModellist)
{
this.updateDishModellist=updateDishModellist;
this.mcontext=context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=
LayoutInflater.from(mcontext)
.inflate(R.layout.customer_menudish,parent,false);
return new CustomerHomeAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final UpdateDishModel updateDishModel=updateDishModellist.get(position);
Glide.with(mcontext).load(updateDishModel.getImageURL()).into(holder.imageView);
holder.Dishname.setText(updateDishModel.getDishes());
updateDishModel.getRandomUID();
updateDishModel.getChefId();
holder.price.setText("Price: ₹ " + updateDishModel.getPrice());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mcontext,OrderDish.class);
intent.putExtra("FoodMenu",updateDishModel.getRandomUID());
intent.putExtra("ChefId",updateDishModel.getChefId());
mcontext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return updateDishModellist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView Dishname,price;
ElegantNumberButton additem;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.menu_image);
Dishname=itemView.findViewById(R.id.dishname);
price=itemView.findViewById(R.id.dishprice);
additem=itemView.findViewById(R.id.number_btn);
}
}
}
I think error is in this code as i am not able to trouble shoot is please help me with this
private void customermenu() {
swipeRefreshLayout.setRefreshing(true);
DatabaseReference databaseReference =
FirebaseDatabase.getInstance().getReference("FoodSupplyDetails")
.child(State).child(City).child(Sub);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
updateDishModelList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
UpdateDishModel updateDishModel =
snapshot1.getValue(UpdateDishModel.class);
updateDishModelList.add(updateDishModel);
}
}
adapter = new CustomerHomeAdapter(getContext(), updateDishModelList);
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
swipeRefreshLayout.setRefreshing(false);
}
});
enter image description here
enter image description here
From your code, your issue seems to be on below line:
FirebaseDatabase.getInstance().getReference("FoodSupplyDetails")
.child(State).child(City).child(Sub);
Error tells you you cannot pass null for ".child()". So it is telling you the values for State, City and Sub are null. You can confirm this by going to your Firebase's console database and seeing the data structure for the corresponding "Customer" with the firebase id.
Please check your Firebase database and make sure the customer data exists.
Before you run your query you should make sure the values are not null.
if (State != null && City != null && Sub != null) {
// Run your query here
} else {
Log.d("TAG", "Data provided is null")
}
When you are fetching customer's information, try logging that and check which of them is null:
String State, City, Sub;
//...
State = cust.getState();
City = cust.getCity();
Sub = cust.getSuburban();
Log.d("TAG", State);
Log.d("TAG", City);
Log.d("TAG", Sub);
// call customermenu now
customermenu();
The error tells you you cannot pass null for ".child()". So it is telling you the values for data(stored in the firebase database) are null. You can confirm this by going to your Firebase's console database and seeing the data structure corresponding with the firebase id.

I wanted to see all users post using a recycler view

I wanted all users post to be shown on the home fragment, it is showing all users post but it show each post 7 times. I am not sure where the error is but I would like some help with this part so that I could finish this project, I'm a newbie in java coding could anyone help me out please. Thank you in advance
Here is my post adapter
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.myViewHolderClass> {
public static final String HOME_POSTS_TYPE = "FROM_VIEW_PROFILE";
public static final String IMAGE_LIKED = "IMAGE_LIKED";
public static final String IMAGE_NOT_LIKED = "IMAGE_NOT_LIKED";
public static final String FROM_HOME_FRAGMENT = "FROM_HOME_FRAGMENT";
private static final String TAG = "POST_ADAPTER";
Context context;
ArrayList<UsersPosts> usersPosts;
LinearLayoutManager layoutManager;
ArrayList<Comment> commentList = new ArrayList<>();
public PostsAdapter(Context context, ArrayList<UsersPosts> usersPosts, LinearLayoutManager layoutManager) {
this.context = context;
this.usersPosts = usersPosts;
this.layoutManager = layoutManager;
}
#NonNull
#Override
public myViewHolderClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.posts_recycler_view_layout, parent, false);
return new myViewHolderClass(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myViewHolderClass holder, int position) {
if (usersPosts.get(position).getImageUri().toLowerCase().contains(Constants.VIDEO_FILE_FIREBASE)) {
holder.postImageView.setVisibility(View.GONE);
holder.imgPlaceHolder.setVisibility(View.GONE);
holder.mainVideoLayout.setVisibility(View.VISIBLE);
playVideo(holder, usersPosts.get(position).getImageUri());
} else {
holder.playIcon.setVisibility(View.GONE);
holder.mainVideoLayout.setVisibility(View.GONE);
holder.imgPlaceHolder.setVisibility(View.VISIBLE);
holder.postImageView.setVisibility(View.VISIBLE);
GlideImageLoader.loadImageWithPlaceHolder(context, usersPosts.get(position).getImageUri()
, holder.postImageView, holder.imgPlaceHolder);
//If Posts Turn off Comments is enabled.
if (usersPosts.get(position).isTurnOffComments()) {
holder.allCommentsLayout.setVisibility(View.GONE);
holder.commentIcon.setVisibility(View.GONE);
} else {
holder.allCommentsLayout.setVisibility(View.VISIBLE);
holder.commentIcon.setVisibility(View.VISIBLE);
}
}
//Likes
HashMap<String, Object> hashMap = usersPosts.get(position).getLikes();
if (hashMap == null) {
holder.likeIcon.setTag(IMAGE_NOT_LIKED);
holder.likesCount.setText("0 Likes");
}
//Date
holder.timeCreated.setText(DateUtils.getRelativeTimeSpanString(
Long.parseLong(usersPosts.get(position).getDateCreated()),
System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS));
bindUsersData(holder.profilePic, holder.usernameAndCaption, holder.userName, usersPosts.get(position).getCaption(),
usersPosts.get(position).getUserId(), position);
HelperMethods ob1 = new HelperMethods(context, usersPosts.get(position).getPostId(), holder.likeIcon);
ob1.likeListener(holder.likesCount);
getComments(usersPosts.get(position).getPostId(), holder.allCommentsLayout, holder.viewAllCommentsTxt);
}
private void playVideo(myViewHolderClass holderClass, String imageUri) {
holderClass.playIcon.setVisibility(View.GONE);
holderClass.videoView.setVisibility(View.VISIBLE);
holderClass.videoLoadingLayout.setVisibility(View.VISIBLE);
String videoUriLastPathSegment = Uri.parse(imageUri).getLastPathSegment();
if (CachingVideos.isVideoExistsInCache(context, videoUriLastPathSegment)) {
assert videoUriLastPathSegment != null;
holderClass.videoView.setVideoPath(CachingVideos.getVideoFile(context, videoUriLastPathSegment).getPath());
} else
CachingVideos.putVideoIntoCache(context, holderClass.videoView, imageUri);
holderClass.mainVideoLayout.setOnClickListener(v -> {
if (holderClass.videoView.isPlaying()) {
holderClass.playIcon.setVisibility(View.VISIBLE);
holderClass.videoView.pause();
} else {
holderClass.videoView.start();
holderClass.playIcon.setVisibility(View.GONE);
}
});
holderClass.videoView.setOnCompletionListener(mp -> holderClass.videoView.start());
holderClass.videoView.setOnPreparedListener(mp -> {
holderClass.videoLoadingLayout.setVisibility(View.GONE);
});
}
public void getComments(String postID, final LinearLayout viewAllComment, final TextView commentTxt) {
FirebaseDatabase.getInstance().getReference(context.getString(R.string.DB_COMMENTS))
.child(postID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
commentList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Comment comment = dataSnapshot.getValue(Comment.class);
commentList.add(comment);
}
if (commentList.size() == 0)
viewAllComment.setVisibility(View.GONE);
else {
viewAllComment.setVisibility(View.VISIBLE);
commentTxt.setText(context.getString(R.string.com___, commentList.size()));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return usersPosts.size();
}
private void bindUsersData(final ImageView profilePic, final TextView nameAndCaption, final TextView userName,
final String caption, String userID, final int position) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(context.getString(R.string.DB_USERS)).child(userID);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userDetails = snapshot.getValue(User.class);
usersPosts.get(position).setUser(userDetails);
assert userDetails != null;
if (userDetails.getProfilePic() != null) {
if (!userDetails.getProfilePic().equals(""))
Glide.with(context.getApplicationContext()).load(userDetails.getProfilePic()).into(profilePic);
}
userName.setText(userDetails.getUsername());
nameAndCaption.setText(HelperMethods.usernameAndCaption(userDetails.getUsername(), caption));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public class myViewHolderClass extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView playIcon;
VideoView videoView;
FrameLayout videoLoadingLayout;
ConstraintLayout mainVideoLayout;
ImageView profilePic, postImageView, likeIcon,
optionMenu, commentIcon, shareIcon;
TextView userName, usernameAndCaption, likesCount,
viewAllCommentsTxt, timeCreated;
LinearLayout allCommentsLayout, imgPlaceHolder;
public myViewHolderClass(#NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.textView46);
likeIcon = itemView.findViewById(R.id.imageView13);
profilePic = itemView.findViewById(R.id.profile_pic_2);
postImageView = itemView.findViewById(R.id.imageView8);
commentIcon = itemView.findViewById(R.id.imageView14);
optionMenu = itemView.findViewById(R.id.imageView5);
timeCreated = itemView.findViewById(R.id.textView59);
likesCount = itemView.findViewById(R.id.textView8);
videoView = itemView.findViewById(R.id.videoView2);
playIcon = itemView.findViewById(R.id.cardView31);
shareIcon = itemView.findViewById(R.id.imageView15);
mainVideoLayout = itemView.findViewById(R.id.frameLayout);
videoLoadingLayout = itemView.findViewById(R.id.placeholder);
viewAllCommentsTxt = itemView.findViewById(R.id.textView11);
imgPlaceHolder = itemView.findViewById(R.id.linearLayout44);
usernameAndCaption = itemView.findViewById(R.id.textView47);
allCommentsLayout = itemView.findViewById(R.id.linearLayout26);
likeIcon.setOnClickListener(this);
optionMenu.setOnClickListener(this);
userName.setOnClickListener(this);
commentIcon.setOnClickListener(this);
allCommentsLayout.setOnClickListener(this);
shareIcon.setOnClickListener(this);
}
#Override
public void onClick(View view) {
HelperMethods ob1 = new HelperMethods(context, usersPosts.get(getAdapterPosition()).getPostId(), likeIcon);
User userObject = usersPosts.get(getAdapterPosition()).getUser();
if (view.getId() == R.id.imageView13) {
if (likeIcon.getTag().equals(IMAGE_NOT_LIKED))
ob1.likePostAndSaveIntoDatabase();
else
ob1.unLikePost();
} else if (view.getId() == R.id.imageView5) {
ViewPostBottomSheet bottomSheet = new ViewPostBottomSheet(HOME_POSTS_TYPE);
bottomSheet.setTargetFragment(((FragmentActivity) (context)).getSupportFragmentManager()
.findFragmentByTag(MAIN_ACTIVITY_FRAGMENT), 100);
bottomSheet.show(((FragmentActivity) context).getSupportFragmentManager(), "ViewProfileBottomSheet");
} else if (view.getId() == R.id.textView46) {
ViewProfileFragment viewProfileFragment = new ViewProfileFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(FROM_HOME_FRAGMENT, userObject);
viewProfileFragment.setArguments(bundle);
((FragmentActivity) context).getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentHolder, viewProfileFragment).addToBackStack(MAIN_ACTIVITY_FRAGMENT).commit();
}
//Comments Activity
else if (view.getId() == R.id.imageView14 || view.getId() == R.id.linearLayout26)
startCommentActivity(userObject, getAdapterPosition());
else if (view.getId() == R.id.imageView15)
openShareFragment(getAdapterPosition());
}
}
private void startCommentActivity(User userObject, int adapterPosition) {
UsersPosts userPost = usersPosts.get(adapterPosition);
Intent intent = new Intent(context, CommentsActivity.class);
intent.putExtra(Constants.USER_OBJECT, userObject);
intent.putExtra(Constants.USER_POST_OBJECT, userPost);
context.startActivity(intent);
}
private void openShareFragment(int adapterPosition) {
ShareBottomSheet bottomSheet = new ShareBottomSheet(context, usersPosts.get(adapterPosition));
bottomSheet.show(((FragmentActivity) (context)).getSupportFragmentManager(), "SHARE_BOTTOM_SHEET");
}
#Override
public void onViewAttachedToWindow(#NonNull final myViewHolderClass holder) {
super.onViewAttachedToWindow(holder);
if (holder.mainVideoLayout.getVisibility() == View.VISIBLE) {
holder.videoLoadingLayout.setVisibility(View.VISIBLE);
} else
holder.playIcon.setVisibility(View.GONE);
}
#Override
public void onViewDetachedFromWindow(#NonNull myViewHolderClass holder) {
super.onViewDetachedFromWindow(holder);
if (holder.videoView.isPlaying()) {
holder.videoView.pause();
holder.playIcon.setVisibility(View.GONE);
}
}
}
here is my home fragment where I want all the posts to be displyed
public class HomeFragment extends Fragment {
public static final String TAG = "HOME_FRAGMENT";
View view;
Toolbar toolbar;
ProgressBar progressBar;
PostsAdapter postsAdapter;
RecyclerView recyclerView;
LinearLayout noPostLayout;
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
LinearLayoutManager linearLayoutManager;
TextView all;
List<String> userFollowingList = new ArrayList<>();
ArrayList<UsersPosts> postsArrayList = new ArrayList<>();
float visiblePercent = 40;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
toolbar = view.findViewById(R.id.toolbar5);
noPostLayout = view.findViewById(R.id.linearLayout13);
progressBar = view.findViewById(R.id.progressBar4);
all = view.findViewById(R.id.all);
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
//Setting Up RecyclerView
linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
postsAdapter = new PostsAdapter(getContext(), postsArrayList, linearLayoutManager);
recyclerView.setAdapter(postsAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
playVideo(newState);
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
toolbar.setOnMenuItemClickListener(item -> {
if (item.getItemId() == R.id.search_icon) {
startActivity(new Intent(getActivity(), SearchActivity.class));
Objects.requireNonNull(getActivity()).overridePendingTransition(0, 0);
} else {
Intent intent = new Intent(getActivity(), MainChatActivity.class);
startActivity(intent);
}
return true;
});
checkFollowings();
}
return view;
}
public void checkFollowings() {
final DatabaseReference followingList = firebaseDatabase.getReference(getString(R.string.DB_FOLLOW)).child(firebaseUser.getUid())
.child(getString(R.string.USER_FOLLOWING));
followingList.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
userFollowingList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
userFollowingList.add(dataSnapshot.getKey());
}
//this will get the post of the users that the main user is following
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
private void readPosts() {
DatabaseReference mRef = firebaseDatabase.getReference(getString(R.string.DB_POST));
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
postsArrayList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
UsersPosts usersPosts = dataSnapshot.getValue(UsersPosts.class);
assert usersPosts != null;
for (String id : userFollowingList) {
postsArrayList.add(usersPosts);
/* if (usersPosts.getUserId().equals(id)) {
postsArrayList.add(usersPosts);
}*/
}
}
if (postsArrayList.size() == 0) {
recyclerView.setVisibility(View.GONE);
noPostLayout.setVisibility(View.VISIBLE);
} else {
noPostLayout.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
postsAdapter.notifyDataSetChanged();
}
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
#Override
public void onDestroyView() {
Log.d(TAG, "onDestroyView: ");
if (view.getParent() != null) {
((ViewGroup) view.getParent()).removeView(view);
}
super.onDestroyView();
}
}
Posting this as an answer for better code formatting. I believe you should simply add the posts like this in HomeFragment.readPosts():
...
public void onDataChange(#NonNull DataSnapshot snapshot) {
postsArrayList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
UsersPosts usersPosts = dataSnapshot.getValue(UsersPosts.class);
postsArrayList.add(usersPosts);
}
...
}

how to get data on all child in firebase realtime database android studio

This is my firebase structure
databaseSupp.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
suppList.clear();
for (DataSnapshot suppSnapshot : dataSnapshot.child("Task").getChildren()) {
//Log.d("fbBee", dataSnapshot.getRef().child("Task").child("9223450").child("Firebase").toString());
Log.d("fbBee", suppSnapshot.getValue().toString());
Log.d("fbGet",suppSnapshot.child("Firebase").getValue().toString());
Supp supp = suppSnapshot.child("Firebase").getValue(Supp.class);
suppList.add(supp);
}
SuppList adapter = new SuppList(MainActivity2.this, suppList);
mListViewSupp.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This is my code, but this code just show child Firebase. I want read and show data from child Firebase, but I need flag on child Reply for reference in my fragmens. please help for code.
Try something like that:
final DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("Task/");
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot taskNo : dataSnapshot.getChildren()) {
// now you in (9223450)
Object firebaseObj = taskNo.child("Firebase").getValue(FirebaseObj.class); //class with params set/get methods
Object replayObj = taskNo.child("Replay").getValue(ReplayObj.class); //class with params set/get methods
// ALTERNATIVE
/*
for (DataSnapshot child : taskNo.getChildren()) {
if(child.getKey().equals("Firebase")) {
String address = child.child("Address").getValue(String.class);
String customer = child.child("Customer").getValue(String.class);
// ...
} else if (child.getKey().equals("Replay")) {
// replay
// ...
}
}
*/
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
Like This
public class SuppList extends ArrayAdapter {
private Activity context;
private List<Supp> suppList;
public SuppList (Activity context, List<Supp> suppList){
super(context, R.layout.list_layout_new, suppList);
this.context = context;
this.suppList = suppList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout_new, null, true);
TextView textViewSo = (TextView) listViewItem.findViewById(R.id.textViewSo);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
TextView textViewAddress = (TextView) listViewItem.findViewById(R.id.textViewAddress);
Supp supp = suppList.get(position);
textViewSo.setText(supp.getSuppId());
//Log.e("SuppTest", supp.getSuppId());
textViewName.setText(supp.getSuppName());
textViewAddress.setText(supp.getSuppAddress());
return listViewItem;
}
}

Remove Duplicate Item name in ArrayList

Please help me. I want to show the username only once from firebase. Although the user have multiple record in the firebase, I just want to view the name of user who make order. The user can make multiple order, but I just want to show their name once.
I tried many ways but can't succeed. Someone who know about this? Thank you very much.
public void onCreate(Bundle savedInstanceState) {
UID = this.getArguments().getString("UID");
mDatabase = FirebaseDatabase.getInstance().getReference();
mStorage = FirebaseStorage.getInstance();
mItems = new ArrayList<>();
wordDulicate = new ArrayList<>();
tempList = new ArrayList<>();
if(UID != null){
mItemsKey = new ArrayList<>();
mOrderedItemRef = mDatabase.child("OrderedItem");
Log.d(TAG, " mOrderedItemRef:" + mOrderedItemRef);
mOrderedItemVEL = mOrderedItemRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mItems.clear();
mItemsKey.clear();
wordDulicate.clear();
Log.d(TAG, "onDataChange");
for (DataSnapshot d : dataSnapshot.getChildren()) {
OrderedItem orderedItem = d.getValue(OrderedItem.class);
Log.d(TAG, "orderedItem:" + orderedItem.getUserName());
mItems.add(orderedItem);
mItemsKey.add(d.getKey());
}
updateUI();
}
#Override
public void onCancelled (DatabaseError databaseError){
Log.d(TAG, "get item databaseError: "+databaseError);
}
});
}
else{
Log.d(TAG, "UID: "+UID);
}
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy(){
super.onDestroy();
// if (mItemRef != null) mItemRef.removeEventListener(mItemVEL);
}
#Override
public void onDetach(){
super.onDetach();
// if (mItemRef != null) mItemRef.removeEventListener(mItemVEL);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_admin_list_user_order, container, false);
mItemRecyclerView = (RecyclerView) view.findViewById(R.id.admin_order_recycler_view);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mItemRecyclerView.getContext(), new LinearLayoutManager(getActivity()).getOrientation());
mItemRecyclerView.addItemDecoration(dividerItemDecoration);
mItemRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
private void updateUI(){
Log.d(TAG, "Enter updateUI(); mItems: " + mItems);
mAdapter = new ItemAdapter(mItems);
mItemRecyclerView.setAdapter(mAdapter);
}
private class ItemHolder extends RecyclerView.ViewHolder{
OrderedItem mItems;
TextView mNameTextView;
ItemHolder(final View itemView){
super(itemView);
mNameTextView = (TextView) itemView.findViewById(R.id.textview_username);
/* if (UID != null) {
itemView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("LongLogTag")
#Override
public void onClick(View view) {
Log.d(TAG, "UID != null");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setMessage("Delete This Item?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteItem(mItems);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}*/
}
void bindData(OrderedItem s){
mItems = s;
mNameTextView.setText(s.getUserName());
}
}
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder>{
private ArrayList<OrderedItem> mItems;
ItemAdapter(ArrayList<OrderedItem> Items){
mItems = Items;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.admin_listed_user_order,parent,false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
OrderedItem s = mItems.get(position);
holder.bindData(s);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
}
Since you rely on a key and a value, why not use a map instead? Maps have a key and a value, and you can check whether or not an item with a key is present by getting the key, instead of having to iterate through the list and find duplicates.
First you need to initialize it:
Map<String, ArrayList<OrderedItem>> items = new HashMap<>();
The value is an ArrayList to keep any existing data
then put the items:
for (DataSnapshot d : dataSnapshot.getChildren()) {
OrderedItem orderedItem = d.getValue(OrderedItem.class);
Log.d(TAG, "orderedItem:" + orderedItem.getUserName());
items.putIfAbsent(d.getKey(), new ArrayList<>());//create a list if it doesn't exist
items.get(d.geyKey()).add(orderedItem);//add the item
}
and clearing with a map is the same as with lists

How to iterate a node in Firebase database?

I've a simple database in Firebase like this:
The following code currently reads a resource fill and render each item read to a RecyclerView.
public class kos_putra extends Fragment {
ArrayList<Kost> mList = new ArrayList<>();
KostAdapter mAdapter;
DatabaseReference mFirebaseDatabase;
FirebaseDatabase mFirebaseInstance;
public kos_putra() {
// 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.kos_putra, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
mAdapter = new KostAdapter(mList);
recyclerView.setAdapter(mAdapter);
fillData();
return view;
}
private void fillData() {
Resources resources = getResources();
String[] arJudul = resources.getStringArray(R.array.places);
String[] arDeskripsi = resources.getStringArray(R.array.place_desc);
String[] arLokasi = resources.getStringArray(R.array.place_locations);
TypedArray a = resources.obtainTypedArray(R.array.places_picture);
Drawable[] arFoto = new Drawable[a.length()];
for (int i = 0; i < arFoto.length; i++) {
BitmapDrawable bd = (BitmapDrawable) a.getDrawable(i);
RoundedBitmapDrawable rbd =
RoundedBitmapDrawableFactory.create(getResources(), bd.getBitmap());
rbd.setCircular(true);
arFoto[i] = rbd;
}
a.recycle();
for (int i = 0; i < arJudul.length; i++) {
mList.add(new Kost(arJudul[i], arDeskripsi[i], arLokasi[i], arFoto[i]));
}
mAdapter.notifyDataSetChanged();
}
private void fetchDataFromFirebase(){
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("kos_putra");
}
}
Now instead of reading from a file, I want to read from Firebase instead. How do I iterate each node under kos_putra? In the picture below, there are 4 objects. Logically, I'm thinking of getting the data count first, then do a for-loop. Still not clear how to do it, though.
To iterate in each node, do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("kos_putra");
ref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
for(DataSnapshot data: dataSnapshot.getChildren()){
String deskripsi=data.child("deskripsi").getValue().toString();
String nama=data.child("nama").getValue().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Here your datasnapshot is on kos_putra, add a listener on that location will iterate on all nodes(1,2,3,4) and with the for loop it will get the values that are inside all nodes also.
myRef.child("users").child(firebaseAuth.uid.toString()).addValueEventListener(object:ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
try {
var td=snapshot.value as HashMap<String,Any>
for(key in td.keys){
var userInfo=td[key] as String
if(key.equals("imageUrl")){
Picasso.get().load(userInfo).into(myView.imageProfilePhoto);
}else if(key.equals("name")){
myView.username.setText(userInfo)
}
}
}catch (ex:Exception){}
}
override fun onCancelled(error: DatabaseError) {
}
})

Categories

Resources