I wanted to see all users post using a recycler view - java

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

Related

Whenever I add new Data to FireStore DataBase and display it to recyclerView , it only shows the newly added data. Here is my Code :

The recycler view only shows the recent add i.e the single element which is newly added, and the rest of the activity is blank, Also whenever I switch fragments and visit again the main fragment it shows all data?
Place to display data and set Adapter:
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private List<BlogPost> blogList;
private FirebaseFirestore firestore;
private FirebaseDatabase database;
private DatabaseReference reference;
private BlogPostAdapter adapter;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
blogList = new ArrayList<>();
firestore = FirebaseFirestore.getInstance();
recyclerView = (RecyclerView)view.findViewById(R.id.post_list_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
EventChangeListener();
adapter = new BlogPostAdapter(blogList);
recyclerView.setAdapter(adapter);
return view;
}
public void EventChangeListener() {
Query firstQuery = firestore.collection("Posts").orderBy("TimeStamp",Query.Direction.ASCENDING);
firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if(error!=null)
{
Log.e("Firestore Error",error.getMessage());
return;
}
blogList.clear();
for(DocumentChange doc : value.getDocumentChanges())
{
if(doc.getType()== DocumentChange.Type.ADDED)
{
String blogPostId = doc.getDocument().getId();
QueryDocumentSnapshot post = doc.getDocument();
BlogPost blogPost = new BlogPost();
Map<String, Object> s = post.getData();
int[] likeCnt = {0};
blogPost.setPost_txt((String) s.get("Post_Content"));
DocumentSnapshot.ServerTimestampBehavior behavior = ESTIMATE;
blogPost.setTimestamp(post.getDate("TimeStamp", behavior));
blogPost.setUser_id((String) s.get("User"));
blogList.add(0,blogPost.withId(blogPostId));
}
}
adapter.notifyDataSetChanged();
}
});
}
**/*Adapter Code*/**
public class BlogPostAdapter extends RecyclerView.Adapter<BlogPostAdapter.ViewHolder> {
private List<BlogPost> blog_lists;
private FirebaseFirestore firestore;
private FirebaseAuth mAuth;
private Context context;
public BlogPostAdapter(List<BlogPost> lc)
{
this.blog_lists = lc;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
mAuth = FirebaseAuth.getInstance();
firestore = FirebaseFirestore.getInstance();
context = parent.getContext();
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_post_view,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, #SuppressLint("RecyclerView") int position) {
String blogPostId = blog_lists.get(position).blogPostId;
String sc = blog_lists.get(position).getPost_txt();
holder.postContent.setText(sc);
String currentUserId = mAuth.getCurrentUser().getUid();
long millisecond = blog_lists.get(position).getTimestamp().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d,yyyy");
String dateString = simpleDateFormat.format(millisecond);
holder.date.setText(dateString);
firestore.collection("Posts/"+blogPostId+"/Likes").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if(!value.isEmpty())
{
int count = value.size();
holder.updateLikes(count);
}
else {
holder.updateLikes(0);
}
}
});
firestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(new EventListener<DocumentSnapshot>() {
#SuppressLint("UseCompatLoadingForDrawables")
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
if (value.exists()) {
holder.likeBtn.setImageDrawable(context.getDrawable(R.drawable.action_liked));
} else {
holder.likeBtn.setImageDrawable(context.getDrawable(R.drawable.action_likebutton));
}
}
});
holder.likeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firestore.collection("Posts/"+blogPostId+"/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(!task.getResult().exists()){
Map<String,Object> mp = new HashMap<>();
mp.put("TimeStamp", FieldValue.serverTimestamp());
firestore.collection("Posts/"+blogPostId+"/Likes").document(currentUserId).set(mp);
}
else
{
firestore.collection("Posts/"+blogPostId+"/Likes")
.document(currentUserId).delete();
}
}
});
}
});
}
#Override
public int getItemCount() {
return blog_lists.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView postContent,date,likeCnt;
private ImageView likeBtn;
public ViewHolder(#NonNull View itemView) {
super(itemView);
postContent = (TextView) itemView.findViewById(R.id.post_content);
date = (TextView) itemView.findViewById(R.id.date);
likeBtn = (ImageView) itemView.findViewById(R.id.like_btn);
likeCnt = (TextView) itemView.findViewById(R.id.likes_cnt);
}
public void updateLikes(int count)
{
likeCnt.setText(count+" Likes");
}
}
}
**// Model Class //***
public class BlogPost extends BlogPostId {
public String user_id,post_txt;
public Date TimeStamp;
int like_count;
public BlogPost(String post_txt)
{
this.post_txt = post_txt;
}
public BlogPost()
{
}
public BlogPost(String user_id, String post_txt,Date timestamp) {
this.user_id = user_id;
this.post_txt = post_txt;
this.TimeStamp = timestamp;
}
public BlogPost(String user_id, String post_txt, Date timeStamp, int like_count) {
this.user_id = user_id;
this.post_txt = post_txt;
TimeStamp = timeStamp;
this.like_count = like_count;
}
public void setLike_count(int like_count) {
this.like_count = like_count;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id)
{
this.user_id = user_id;
}
public String getPost_txt() {
return post_txt;
}
public void setPost_txt(String post_txt) {
this.post_txt = post_txt;
}
public Date getTimestamp() {
return TimeStamp;
}
public void setTimestamp(Date timestamp) {
this.TimeStamp = timestamp;
}
public int getLike_count() {
return like_count;
}
}
**// Main Activity //**
public class MainActivity extends AppCompatActivity {
private androidx.appcompat.widget.Toolbar mainToolbar;
private ImageView addPost_btn;
private BottomNavigationView main_bottom_nav_view;
private FirebaseAuth mAuth;
private HomeFragment homeFragment;
private NotificationFragment notificationFragment;
private AccountFragment accountFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkAvailable())
{
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "Connection Unavailable", Toast.LENGTH_SHORT).show();
}
mAuth = FirebaseAuth.getInstance();
//Bottom navigation bar
main_bottom_nav_view = findViewById(R.id.mainBottomNav);
//Fragment
homeFragment = new HomeFragment();
notificationFragment = new NotificationFragment();
accountFragment = new AccountFragment();
//Post Button
addPost_btn = (ImageView) findViewById(R.id.addPostBtn);
replaceFragment(homeFragment);
addPost_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent post_Intent = new Intent(MainActivity.this,NewPostActivity.class);
startActivity(post_Intent);
}
});
main_bottom_nav_view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId())
{
case R.id.bottom_home:
replaceFragment(homeFragment);
return true;
case R.id.bottom_post:
replaceFragment(notificationFragment);
return true;
case R.id.bottom_acc:
replaceFragment(accountFragment);
return true;
default:
return false;
}
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currUser = FirebaseAuth.getInstance().getCurrentUser();
if(currUser==null)
{
sendToLogin();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
private void sendToLogin() {
Intent login_Intent = new Intent(MainActivity.this,Login_Activity.class);
startActivity(login_Intent);
finish();
}
private void replaceFragment(Fragment newFragment)
{
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,newFragment);
fragmentTransaction.commit();
}
private boolean isNetworkAvailable() {
try{
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if(manager!=null)
{
networkInfo = manager.getActiveNetworkInfo();
}
return networkInfo!=null && networkInfo.isConnected();
}
catch (NullPointerException e)
{
return false;
}
}
}
**// Adding New Data to Firebase FireStore**
public class NewPostActivity extends AppCompatActivity {
private EditText post_txt;
private ImageView post_btn;
private ProgressBar new_post_progress;
private StorageReference storageReference;
private FirebaseFirestore firestore;
private FirebaseAuth firebaseAuth;
private String currUser;
private Uri post_txtUri=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_post);
post_txt = (EditText) findViewById(R.id.post_txt);
post_btn = (ImageView) findViewById(R.id.post_btn);
firebaseAuth = FirebaseAuth.getInstance();
currUser = firebaseAuth.getCurrentUser().getEmail();
new_post_progress = (ProgressBar) findViewById(R.id.new_post_progress);
storageReference = FirebaseStorage.getInstance().getReference().child("Post_Contents");
firestore = FirebaseFirestore.getInstance();
post_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = post_txt.getText().toString();
if(!TextUtils.isEmpty(text))
{
new_post_progress.setVisibility(View.VISIBLE);
String randomName = FieldValue.serverTimestamp().toString();
Map<String,Object> postMap = new HashMap<>();
postMap.put("Post_Content",text);
postMap.put("User",currUser);
postMap.put("TimeStamp",FieldValue.serverTimestamp());
firestore.collection("Posts").add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
new_post_progress.setVisibility(View.INVISIBLE);
if(task.isSuccessful())
{
Toast.makeText(NewPostActivity.this,"Posted Successfully",Toast.LENGTH_SHORT).show();
Intent mainPage = new Intent(NewPostActivity.this,MainActivity.class);
startActivity(mainPage);
finish();
}
else
{
Toast.makeText(NewPostActivity.this,"Error Occurred",Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
Toast.makeText(NewPostActivity.this,"Error in posting",Toast.LENGTH_SHORT).show();
}
// firestore.collection("Posts").document().update("TimeStamp",FieldValue.serverTimestamp());
}
});
}
}
I use a NewPostActivity to post the data in firebase Firestore by creating a collections and retrieving the data in recycler view format as usual, but whenever I retrieve data from firebase and add it to arraylist and display in recyclerView it only shows the newly added element at first and then when I switch to another fragment and come back to homeFragment it shows all the post neatly. I tried finding solutions on youtube but couldn't find any.

Populate details activity with Firebase Real Time Database after click on RecyclerView

i want to click in my recyclerview and open a new activity to show the datails. Ultil now i
have accomplished to open the activity and show the values "interno" and "siniiga" with the next intent. how can i get "madre and padre" values from firebase? applying the method to add father and mother, then I will use it for the rest of the values ​​that the xml shows. excuse my horrible code. if someone know a different method, let me know
attached code and images.
Main Activity
RecyclerView rv;
List<cow> vacas;
adapter adapter;
ImageButton mbuttoninf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv = (RecyclerView) findViewById(R.id.recyclerViewGirdView);
rv.setLayoutManager(new LinearLayoutManager(this));
vacas = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
adapter = new adapter(vacas);
rv.setAdapter(adapter);
database.getReference("Vacas").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
vacas.removeAll(vacas);
for (DataSnapshot snapshot1 :
snapshot.getChildren()) {
cow vaca = snapshot1.getValue(cow.class);
vacas.add(vaca);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
cow
String interno;
String siniiga;
String ulr;
String madre;
String padre;
public cow() {
}
public cow(String interno, String siniiga, String ulr, String madre, String padre) {
this.interno = interno;
this.siniiga = siniiga;
this.ulr = ulr;
this.madre = madre;
this.padre = padre;
}
public String getInterno() {
return interno;
}
public void setInterno(String interno) {
this.interno = interno;
}
public String getSiniiga() {
return siniiga;
}
public void setSiniiga(String siniiga) {
this.siniiga = siniiga;
}
public String getUlr() {
return ulr;
}
public void setUlr(String ulr) {
this.ulr = ulr;
}
public String getMadre() {
return madre;
}
public void setMadre(String madre) {
this.madre = madre;
}
public String getPadre() {
return padre;
}
public void setPadre(String padre) {
this.padre = padre;
}
}
Adapter
List<cow> vacas;
Context context;
public adapter(List<cow> vacas) {
this.vacas = vacas;
}
#NonNull
#Override
public cowviewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vaca,parent,false);
cowviewHolder holder = new cowviewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final cowviewHolder holder, final int position) {
final cow vacaslist = vacas.get(position);
holder.textViewinterno.setText(String.valueOf(vacaslist.interno));
holder.textViewsiniiga.setText(String.valueOf(vacaslist.siniiga));
Glide.with(holder.imageviewrec.getContext()).load(vacaslist.getUlr()).into(holder.imageviewrec);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(v.getContext(),detailactivity.class);
intent.putExtra("keyint", vacaslist.getInterno());
intent.putExtra("keysin", vacaslist.getSiniiga());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return vacas.size();
}
public static class cowviewHolder extends RecyclerView.ViewHolder {
TextView textViewinterno, textViewsiniiga, tvmadre, tvpadre;
ImageView imageviewrec;
public cowviewHolder(#NonNull View itemView) {
super(itemView);
textViewinterno = itemView.findViewById(R.id.interno);
textViewsiniiga = itemView.findViewById(R.id.siniiga);
imageviewrec = itemView.findViewById(R.id.imgrec);
tvmadre = itemView.findViewById(R.id.tvmadre);
tvpadre = itemView.findViewById(R.id.tvpadre);
}
}
detailsactivity
TextView textView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.informationfire);
TextView tvinterno = (TextView) findViewById(R.id.tvinterno);
TextView tvsiniiga = (TextView) findViewById(R.id.tvsiniiga);
String vinterno = "";
String vsiniiga = "";
Bundle extras = getIntent().getExtras();
if (extras !=null);
vinterno = extras.getString("keyint");
vsiniiga = extras.getString("keysin");
tvinterno.setText(vinterno);
tvsiniiga.setText(vsiniiga);
}
}
firebase
enter image description here
and the xml for details
enter image description here
when you are getting data from firebase you saving that data in a Object and then add that object to list, so your list contains objects , so you can pass through the intents same way as you are doing others.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(v.getContext(),detailactivity.class);
intent.putExtra("keyint", vacaslist.getInterno());
intent.putExtra("keysin", vacaslist.getSiniiga());
intent.putExtra("madre", vacaslist.getMadre());
intent.putExtra("padre", vacaslist.getPadre());
v.getContext().startActivity(intent);
}
});

Data from Firebase is not displayed in the RecyclerView that is in the fragment

There is a problem with the data displayed in the recyclerview when I run my program
it looks like this:
.
For the data that is displayed I use firebase like this the
data structure:
When I want to display data in recyclerview in a fragment, but the data doesn't appear. I use Firebase as database
NotaAdapter.java
public class NotaAdapter extends RecyclerView.Adapter<NotaAdapter.MyViewHolder> {
Context context;
ArrayList<ListNota> listnota;
public NotaAdapter (Context c,ArrayList<ListNota> p) {
this.context = c;
this.listnota = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
return new MyViewHolder(LayoutInflater.from(context)
.inflate(R.layout.item_nota, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.no_nota.setText(listnota.get(i).getId_nota());
myViewHolder.total_harga.setText(String.valueOf(listnota.get(i).getTotal_seluruh()));
final String getnoNOta = listnota.get(i).getId_nota();
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoDetailNota = new Intent(context, DetailNotaAct.class);
gotoDetailNota.putExtra("no_nota", getnoNOta);
context.startActivity(gotoDetailNota);
}
});
}
#Override
public int getItemCount() {
return listnota.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView no_nota, total_harga;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
no_nota = itemView.findViewById(R.id.xid_nota);
total_harga = itemView.findViewById(R.id.xtotal_seluruh);
}
}
}
ListNota.java
public class ListNota {
private String id_nota;
private Integer total_seluruh;
public ListNota() {
}
public ListNota(String id_nota, Integer total_seluruh) {
this.id_nota = id_nota;
this.total_seluruh = total_seluruh;
}
public String getId_nota() {
return id_nota;
}
public void setId_nota(String id_nota) {
this.id_nota = id_nota;
}
public Integer getTotal_seluruh() {
return total_seluruh;
}
public void setTotal_seluruh(Integer total_seluruh) {
this.total_seluruh = total_seluruh;
}
}
HistoryFragment.java
public class HistoryFragment extends Fragment {
TextView txt_history, txt_toko, txt_report, txt_nama_toko, txt_jenis_toko;
LinearLayout btn_buat_nota;
DatabaseReference databaseUser, databaseToko, databaseNota;
String USERNAME_KEY = "usernamekey";
String username_key = "";
String username_key_new = "";
String id_Toko = "";
ProgressDialog progress;
RecyclerView nota_place;
ArrayList<ListNota> list;
NotaAdapter notaAdapter;
private View Notaview;
public HistoryFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Notaview = inflater.inflate(R.layout.fragment_history, container, false);
txt_nama_toko = (TextView) Notaview.findViewById(R.id.txt_nama_toko);
txt_jenis_toko = (TextView) Notaview.findViewById(R.id.txt_jenis_toko);
txt_history = (TextView) Notaview.findViewById(R.id.txt_history);
txt_toko = (TextView) Notaview.findViewById(R.id.txt_toko);
txt_report = (TextView) Notaview.findViewById(R.id.txt_report);
btn_buat_nota = (LinearLayout) Notaview.findViewById(R.id.btn_buat_nota);
progress = new ProgressDialog(getActivity());
progress.setTitle("Loading");
progress.setMessage("Memuat Data");
progress.setCancelable(false);
progress.show();
getUsernameLocal();
databaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(username_key_new);
databaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
id_Toko = dataSnapshot.child("id_toko").getValue().toString();
databaseToko = FirebaseDatabase.getInstance().getReference().child("Toko").child(id_Toko);
databaseToko.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
txt_nama_toko.setText(dataSnapshot.child("nama_toko").getValue().toString());
//cek apakah child jenis toko ada
if (dataSnapshot.hasChild("jenis_toko")){
txt_jenis_toko.setText(dataSnapshot.child(" jenis_toko").getValue().toString());
}else{
txt_jenis_toko.setText("Jenis toko belum disetting");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btn_buat_nota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String id_nota = generateRandomString(16);
Intent gotoBuatNota = new Intent(getActivity(), BuatNotaAct.class);
gotoBuatNota.putExtra("id_nota", id_nota);
startActivity(gotoBuatNota);
}
});
nota_place = (RecyclerView) Notaview.findViewById(R.id.nota_place);
notaAdapter = new NotaAdapter(getContext(), list);
nota_place.setAdapter(notaAdapter);
nota_place.setLayoutManager(new LinearLayoutManager(getActivity()));
return Notaview;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<ListNota>();
loaddata();
}
private void loaddata(){
databaseNota = FirebaseDatabase.getInstance().getReference().child("Nota").child(id_Toko);
databaseNota.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
ListNota p = dataSnapshot1.getValue(ListNota.class);
list.add(p);
}
progress.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public String generateRandomString(int length){
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
for(int i = 0; i < length; i++){
char c = chars[random.nextInt(chars.length)];
stringBuilder.append(c);
}
return stringBuilder.toString();
}
public void getUsernameLocal(){
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(USERNAME_KEY, MODE_PRIVATE);
username_key_new = sharedPreferences.getString(username_key,"");
}
}
you are reading it from the wrong node, you are passing reference that you want to read data from the node Named "users".
Your Database reference should look like this
databaseUser = FirebaseDatabase.getInstance().getReference("Nota").child("Toko_Kita20082020371").child(username_key_new);
Also make sure your list should have all the variables that a node has.
For example a node has
name,id,price,description;
then same varibles should be declared in your list to successfully ready dta from the firebase.

ListView Duplicating Data

Have an android application that on one of the pages has a ListView. The ListView has an array with 5 objects in it that is passed into the list adapter to be displayed. On the list view it shows 5 items but the bottom one is shown as a duplicate. However when you click this item it will show the right data that isn't duplicated on another page. Below see the code and screenshots.
MyJobsFragment.java
private void bidOnList() throws ParseException
{
final ArrayList<String> jobsListArray = new ArrayList<>();
// Iterate through entire bids table
for (DataSnapshot ds : getBidListChildren())
{
// Iterate through the actual bids information
Iterable<DataSnapshot> bidsSnapShot = ds.getChildren();
for (DataSnapshot ds1 : bidsSnapShot)
{
// if the User Id equals the current user added to a list
if (getBidInformation(ds1).getUserID().equals(auth.getCurrentUser().getUid()))
{
boolean active = ds1.child("active").getValue(boolean.class);
if (active)
{
jobsListArray.add(ds.getKey());
}
}
}
}
// Go through the jobs table
for (DataSnapshot ds3 : getJobListChildren())
{
/*
If the job is in the jobsListArray previously and the status is Pending
Add to the jobsList
*/
if (jobsListArray.contains(ds3.getKey()) && getJobInformation(ds3).getJobStatus().equals("Pending"))
{
Date sdf = new SimpleDateFormat("dd/MM/yyyy").parse(genericMethods.getJobInformation(ds3).getCollectionDate());
if (new Date().before(sdf))
{
jobListKey.add(ds3.getKey());
jobList.add(getJobInformation(ds3));
}
}
}
// Display information in ListView
mAdapterBidOn = new MyCustomAdapterForTabViews(getActivity(), isAdded(), host, getLayoutInflater(), getFragmentManager());
mAdapterBidOn.addKeyArray(jobListKey);
mAdapterBidOn.addArray(jobList);
jobListViewBidOn.setAdapter(mAdapterBidOn);
// Press on the object and go view all the Job Information and Bids
jobListViewBidOn.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
BidOnJobsFragment bidOnJobsFragment = new BidOnJobsFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("Job", mAdapterBidOn.mData.get(position));
bundle.putSerializable("JobId", mAdapterBidOn.mDataKeys.get(position));
bidOnJobsFragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.content, bidOnJobsFragment).addToBackStack("tag").commit();
}
});
}
The above method adds all the relevant data into an array list and adds it into the adapter.
Custom Adapter
public class MyCustomAdapterForTabViews extends BaseAdapter
{
public ArrayList<JobInformation> mData = new ArrayList<>();
public ArrayList<JobInformation> mDataOrig = new ArrayList<>();
public ArrayList<String> mDataKeys = new ArrayList<>();
private TabHost host;
public LayoutInflater mInflater;
private FragmentActivity fragmentActivity;
private LayoutInflater layoutInflater;
private FragmentManager fragmentManager;
public MyCustomAdapterForTabViews(FragmentActivity fragmentActivity, boolean isAdded, TabHost host, LayoutInflater layoutInflater, FragmentManager fragmentManager)
{
if (isAdded)
{
this.fragmentActivity = fragmentActivity;
this.fragmentManager = fragmentManager;
this.layoutInflater = layoutInflater;
mInflater = (LayoutInflater) fragmentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
this.host = host;
}
public void addItem(final JobInformation item)
{
mData.add(item);
mDataOrig.add(item);
}
public void addArray(final ArrayList<JobInformation> j)
{
mData.clear();
mDataOrig.clear();
mData = j;
mDataOrig = j;
}
public void addKeyArray(final ArrayList<String> k)
{
mDataKeys.clear();
mDataKeys = k;
}
#Override
public int getCount()
{
return mData.size();
}
#Override
public Object getItem(int position)
{
return mData.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer)
{
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer)
{
}
#Override
public boolean areAllItemsEnabled()
{
return false;
}
#Override
public boolean isEmpty()
{
return false;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// Bid on holder
MyCustomAdapterForTabViews.GroupViewHolderBidOn holderBidOn;
// Accepted holder
final MyCustomAdapterForTabViews.GroupViewHolderAccepted holderAccepted;
// Completed holder
MyCustomAdapterForTabViews.GroupViewHolderCompleted holderCompleted;
if (convertView == null)
{
// Bid on
if (host.getCurrentTab() == 0)
{
convertView = mInflater.inflate(R.layout.job_info_bid_on, null);
holderBidOn = new MyCustomAdapterForTabViews.GroupViewHolderBidOn();
holderBidOn.textViewJobName = convertView.findViewById(R.id.textName);
holderBidOn.imageViewCross = convertView.findViewById(R.id.imageViewCross);
holderBidOn.imageViewEditPen = convertView.findViewById(R.id.imageViewEditPen);
holderBidOn.textViewJobDescription = convertView.findViewById(R.id.textDesc);
holderBidOn.textViewAddressFrom = convertView.findViewById(R.id.textAddressFrom);
holderBidOn.textViewAddressTo = convertView.findViewById(R.id.textAddressTo);
holderBidOn.textViewJobName.setText(mData.get(position).getAdvertName());
holderBidOn.textViewJobDescription.setText(mData.get(position).getAdvertDescription());
holderBidOn.textViewAddressFrom.setText(mData.get(position).getColL1() + ", " + mData.get(position).getColTown() + ", " + mData.get(position).getColPostcode());
holderBidOn.textViewAddressTo.setText(mData.get(position).getDelL1() + ", " + mData.get(position).getDelPostcode() + ", " + mData.get(position).getDelPostcode());
holderBidOn.imageViewCross.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
final DatabaseConnections databaseConnections = new DatabaseConnections();
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(fragmentActivity);
View mView = layoutInflater.inflate(R.layout.popup_creator, null);
alertDialog.setTitle("Delete Job");
alertDialog.setView(mView);
final AlertDialog dialog = alertDialog.create();
dialog.show();
TextView customText = mView.findViewById(R.id.textViewCustomText);
customText.setText("Are You Sure You Want To Delete " + mData.get(position).getAdvertName() + "?");
Button yesButton = mView.findViewById(R.id.yesButton);
Button noButton = mView.findViewById(R.id.noButton);
yesButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// My Adverts
if (mData.get(position).getPosterID().equals(databaseConnections.getCurrentUser()))
{
databaseConnections.getDatabaseReference().child("Jobs").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Jobs").child(mDataKeys.get(position))
.child("jobStatus").setValue("Inactive");
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).child(mData.get(position)
.getCourierID()).child("active").setValue(false);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
// My Jobs
else
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).child(databaseConnections.getCurrentUser()).child("active").setValue(false);
mData.remove(position);
mDataKeys.remove(position);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
notifyDataSetChanged();
dialog.dismiss();
}
});
noButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
dialog.dismiss();
}
});
}
});
DatabaseConnections databaseConnections = new DatabaseConnections();
// My Adverts
if (mData.get(position).getPosterID().equals(databaseConnections.getCurrentUser()))
{
holderBidOn.imageViewEditPen.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
GenericMethods genericMethods = new GenericMethods();
PostAnAdvertFragment postAnAdvertFragment = new PostAnAdvertFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("JobInfo", mData.get(position));
bundle.putSerializable("JobIdKey", mDataKeys.get(position));
postAnAdvertFragment.setArguments(bundle);
genericMethods.beginTransactionToFragment(fragmentManager, postAnAdvertFragment);
}
});
}
// My Jobs
else
{
holderBidOn.imageViewEditPen.setVisibility(View.GONE);
}
convertView.setTag(holderBidOn);
}
// Accepted
else if (host.getCurrentTab() == 1)
{
convertView = mInflater.inflate(R.layout.job_info_accepted, null);
holderAccepted = new MyCustomAdapterForTabViews.GroupViewHolderAccepted();
holderAccepted.textViewJobName = convertView.findViewById(R.id.textName);
holderAccepted.textViewDescription = convertView.findViewById(R.id.textDesc);
holderAccepted.textViewAddressFrom = convertView.findViewById(R.id.textAddressFrom);
holderAccepted.textViewAddressTo = convertView.findViewById(R.id.textAddressTo);
holderAccepted.textViewBid = convertView.findViewById(R.id.textBid);
holderAccepted.textViewJobName.setText(mData.get(position).getAdvertName());
holderAccepted.textViewDescription.setText(mData.get(position).getAdvertDescription());
holderAccepted.textViewAddressFrom.setText(mData.get(position).getColL1() + ", " + mData.get(position).getColTown() + ", " + mData.get(position).getColPostcode());
holderAccepted.textViewAddressTo.setText(mData.get(position).getDelL1() + ", " + mData.get(position).getDelPostcode() + ", " + mData.get(position).getDelPostcode());
DatabaseConnections databaseConnections = new DatabaseConnections();
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).child(mData.get(position).getCourierID()).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
String acceptedBid = dataSnapshot.child("userBid").getValue(String.class);
holderAccepted.textViewBid.setText("£" + acceptedBid);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
convertView.setTag(holderAccepted);
}
// Completed
else if (host.getCurrentTab() == 2)
{
convertView = mInflater.inflate(R.layout.job_info_list_completed, null);
holderCompleted = new MyCustomAdapterForTabViews.GroupViewHolderCompleted();
holderCompleted.textViewJobName = convertView.findViewById(R.id.textName);
holderCompleted.imageViewCross = convertView.findViewById(R.id.imageViewCross);
holderCompleted.textViewJobName.setText(mData.get(position).getAdvertName());
holderCompleted.imageViewCross.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
final DatabaseConnections databaseConnections = new DatabaseConnections();
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(fragmentActivity);
View mView = layoutInflater.inflate(R.layout.popup_creator, null);
alertDialog.setTitle("Delete Job");
alertDialog.setView(mView);
final AlertDialog dialog = alertDialog.create();
dialog.show();
TextView customText = mView.findViewById(R.id.textViewCustomText);
customText.setText("Are You Sure You Want To Delete " + mData.get(position).getAdvertName() + "?");
Button yesButton = mView.findViewById(R.id.yesButton);
Button noButton = mView.findViewById(R.id.noButton);
yesButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// My Adverts
if (mData.get(position).getPosterID().equals(databaseConnections.getCurrentUser()))
{
databaseConnections.getDatabaseReference().child("Jobs").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Jobs").child(mDataKeys.get(position))
.child("jobStatus").setValue("Inactive");
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
// My Jobs
else
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).child(databaseConnections.getCurrentUser()).child("active").setValue(false);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
notifyDataSetChanged();
dialog.dismiss();
}
});
noButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
dialog.dismiss();
}
});
}
});
convertView.setTag(holderCompleted);
}
} else
{
if (host.getCurrentTab() == 0)
{
holderBidOn = (MyCustomAdapterForTabViews.GroupViewHolderBidOn) convertView.getTag();
} else if (host.getCurrentTab() == 1)
{
holderAccepted = (MyCustomAdapterForTabViews.GroupViewHolderAccepted) convertView.getTag();
} else if (host.getCurrentTab() == 2)
{
holderCompleted = (MyCustomAdapterForTabViews.GroupViewHolderCompleted) convertView.getTag();
}
}
return convertView;
}
public class GroupViewHolderBidOn
{
public TextView textViewJobName;
public TextView textViewJobDescription;
public TextView textViewAddressFrom;
public TextView textViewAddressTo;
public ImageView imageViewCross;
public ImageView imageViewEditPen;
}
public class GroupViewHolderAccepted
{
public TextView textViewJobName;
public TextView textViewDescription;
public TextView textViewAddressFrom;
public TextView textViewAddressTo;
public TextView textViewBid;
}
public class GroupViewHolderCompleted
{
public TextView textViewJobName;
public ImageView imageViewCross;
}
public void filter(String charText)
{
ArrayList<JobInformation> jobs = new ArrayList<>();
ArrayList<JobInformation> jA = new ArrayList<>();
charText = charText.toLowerCase(Locale.getDefault());
if (charText.length() == 0)
{
mData = mDataOrig;
} else
{
for (JobInformation j : mDataOrig)
{
if (j.getWholeString().toLowerCase(Locale.getDefault()).contains(charText))
{
jobs.add(j);
jA.add(j);
} else
{
jA.add(j);
}
}
mData.clear();
mData = jobs;
mDataOrig = jA;
}
notifyDataSetChanged();
}
}
My Bids 1
My Bids 2
When you click the bottom Panasonic TV
More code can be provided if needed.
EDIT
Code runs as intended until it hits the 4th element in the array, once that point is hit, it goes off into base java classes that I'm guessing are for the adapter. It is as if its ignoring the last two and recycling the views.
#Override
public long getItemId(int position)
{
return 0;
}
i think problem is in your above adapter method. change this to below :
#Override
public long getItemId(int position)
{
return position;
}

Error in recyclerView

Can anyone check if there are errors in it. here my code, If there is any error in the code please tell me? I don't know how to fix the code Search.java.
in my RecyclerItemClickListener.java
public interface RecyclerItemClickListener {
void onItemClick(int position);
}
My Adapter HierAdapter.java
public class HireAdapter extends RecyclerView.Adapter<HireAdapter.ViewHolder>{
private ArrayList<HireItem> TeacherItemList;
private Context context;
private RecyclerItemClickListener itemClickListener;
public HireAdapter(Context c, ArrayList<HireItem> teacherItemList, RecyclerItemClickListener listener) {
TeacherItemList = teacherItemList;
context = c;
itemClickListener = listener;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public final TextView nameText, subjectText,levelText ,cityText;
public ViewHolder(View itemView) {
super(itemView);
nameText = (TextView)itemView.findViewById(R.id.result_name);
subjectText = (TextView)itemView.findViewById(R.id.result_subject);
levelText = (TextView)itemView.findViewById(R.id.result_level);
cityText = (TextView)itemView.findViewById(R.id.result_city);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return TeacherItemList.size();
}}
Here Search.java, I wrote notes at each error. Because I did not know how to correct some codes to work with HireAdapter and RecyclerItemClickListener, can anyone solve the error?
public class Search extends Fragment implements RecyclerItemClickListener {
private Context context;
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private List<HireItem> hireItem = new ArrayList<>();
HireAdapter mAdapter;
ImageView bt_search;
ProgressDialog progressDialog;
Spinner spinner_sort;
String key = "req_skill1";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_search,container,false);
//Getting FireBase Instance
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference("teachers");
//Getting id of Views
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_places);
recyclerView.setAdapter(mAdapter);
//
bt_search = (ImageView)view.findViewById(R.id.bt_search);
spinner_sort = (Spinner)view.findViewById(R.id.spinner_sort);
setupSpinner();
List<HireItem> hireItem = new ArrayList<>();
mAdapter = new HireAdapter(getContext(),R.layout.list_item_teachers,hireItem); // error at (getContext(),R.layout.list_item_teachers,hireItem)
bt_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mAdapter != null){
mAdapter.clear(); // error at .clear();
}
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Searching Teachers");
progressDialog.show();
FirebaseDatabase.getInstance().getReference("teachers").orderByChild("subject").startAt(key).endAt(key + "~")
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Teachers child = dataSnapshot.getValue(Teachers.class);
HireItem hireItem = new HireItem(child.teaname, child.city, child.subject, child.level, child.sex,child.mobile, child.qualification, child.skill1, child.experince, child.salary,child.age);
mAdapter.add(hireItem); // error at .add
progressDialog.dismiss();
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
else{
recyclerView.setAdapter(mAdapter); // error at recyclerView
}
}
});
return view;
}
private void setupSpinner(){
ArrayAdapter adapter = ArrayAdapter.createFromResource(getContext(),R.array.array_teacher_sort,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_sort.setAdapter(adapter);
spinner_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
key = (String)adapterView.getItemAtPosition(i);
if(key.equals(getString(R.string.sort_A))){
key = "Math";
}else if(key.equals(getString(R.string.sort_AA))){
key = "computer";
}
else if(key.equals(getString(R.string.sort_AB))){
key = "Biology";
}
else if(key.equals(getString(R.string.sort_AD))){
key = "Physics";
}
else if(key.equals(getString(R.string.sort_AXX))){
key = "Holy Quran";
}
else if(key.equals(getString(R.string.sort_AZ))){
key = "Chysics";
}
else if(key.equals(getString(R.string.sort_AS))){
key = "English";
}
else if(key.equals(getString(R.string.sort_AQ))){
key = "Arabic";
}
else if(key.equals(getString(R.string.sort_ADD))){
key = "Science";
}
else if(key.equals(getString(R.string.sort_AE))){
key = "History";
}
else if(key.equals(getString(R.string.sort_AW))){
key = "Geograpghy";
}
else if(key.equals(getString(R.string.sort_AR))){
key = "Art education";
}
else if(key.equals(getString(R.string.sort_AT))){
key = "Family education";
}
else if(key.equals(getString(R.string.sort_aae))){
key = "Religion";
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onResume() {
super.onResume();
mAdapter.clear(); // error at .clear();
}
#Override
public void onItemClick(int position) {
} }
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
Here you are setting onClickListner on the same view twice. The Listener set in the onBindViewHolder will override the Listner set in the onCreateViewHolder method.

Categories

Resources