I have an app that retrieves data from Firebase specifically from Firestore, the thing is the recycler view that shows the data is empty, even though it's working in another fragment with the same logic, I don't know where i am wrong or mistaken! And as i said the fragment is totally empty, besides if i added a TextView or Button it shows normally but the recycler view doesn't show up.
ps: when i copied the same code i changed the layout name and the recycler name to point to the other layout and recycler view of the fragment;
Here is the Fragment
FavoriteFragment.java: the fragment that handles the code.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_favorite, container, false);
recyclerView = view.findViewById(R.id.fav_recycler);
linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
mAuth = FirebaseAuth.getInstance();
FirebaseUser auth_user = mAuth.getCurrentUser();
db = FirebaseFirestore.getInstance();
//Fetch Users Info
Query query = db.collection("posts")
.orderBy("posttime", Query.Direction.DESCENDING); // order the query by date
FirestoreRecyclerOptions<Posts> response = new FirestoreRecyclerOptions.Builder<Posts>()
.setQuery(query, Posts.class)
.build();
adapter = new MainAdapter(response);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
return view;
}
fragment_favorite.xml: the layout of the fragment.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FavoriteFragment">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="15dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/fav_recycler"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="15dp"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</FrameLayout>
and
MainAdapter.java: The adapter of the Recycler view, also handles the code that makes an item (in this case a post) to be added or removed from the firestore
public class MainAdapter extends FirestoreRecyclerAdapter<Posts, MainAdapter.ViewHolder> {
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public MainAdapter(#NonNull FirestoreRecyclerOptions options) {
super(options);
}
private FirebaseFirestore db;
private DocumentReference documentReference;
private FirebaseAuth mAuth;
boolean isthere = false;
boolean isExist = false;
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull Posts post) {
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
documentReference = db.collection("users").document(mAuth.getUid());
holder.txtTitle.setText(post.getName());
holder.txtDesc.setText(post.getTitle() + "\n" +post.getDesc() + "\n" + post.getBloodtype() + "\n" + post.getCity() + "\n" + post.getNumber()+ "\n" + post.getDeadline());
Glide.with(holder.image.getContext()).load(post.getImage())
.into(holder.image);
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, post.getUserid() + "\n" + post.getName() + "\n" +post.getBloodtype() + "\n" + post.getCity(), Snackbar.LENGTH_LONG)
.setAnchorView(R.id.navigation) // Set SnackBar above the BottomNavigationView
.show();
}
});
Posts newPost = new Posts(post.getUserid(), post.getName(), post.getTitle(),post.getDesc(), post.getDeadline(), post.getNumber(),
post.getCity(), post.getBloodtype(), post.getImage(), post.getPosttime(), post.getPostid());
holder.fav.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
// Toast.makeText(buttonView.getContext(), "Added to favorite", Toast.LENGTH_SHORT).show();
if (isExist == false) {
db.collection("users").document(mAuth.getUid()).collection("favorites").document(post.getPostid())
.set(newPost)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(buttonView.getContext(), "Succeed \nBoolean: " + isExist, Toast.LENGTH_SHORT).show();
}
});
}
}
else {
// removefromfav(post.getPostid(), buttonView);
documentReference.collection("favorites").document(post.getPostid())
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
public void onSuccess(Void aVoid) {
// Toast.makeText(buttonView.getContext(), "Removed from favorite " + isExist, Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
});
documentReference.collection("favorites").document(post.getPostid())
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
isExist = task.getResult().exists();
if (isExist == true) {
holder.fav.setChecked(true);
}
}
}
});
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_item, parent, false);
return new ViewHolder(view);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public LinearLayout root;
public TextView txtTitle;
public TextView txtDesc;
public ImageView image;
public ToggleButton fav;
public ViewHolder(View itemView) {
super(itemView);
root = itemView.findViewById(R.id.list_root);
txtTitle = (TextView) itemView.findViewById(R.id.list_title);
txtDesc = (TextView) itemView.findViewById(R.id.list_desc);
image = (ImageView)itemView.findViewById(R.id.list_image);
fav = (ToggleButton)itemView.findViewById(R.id.favbutton);
}
}
}
EDIT:
I added the Posts class
Posts.java:
public class Posts {
private String userid;
private String name;
private String title;
private String desc;
private String deadline;
private String number;
private String city;
private String bloodtype;
private String image;
private String posttime;
private String postid;
public Posts(){
}
public Posts(String userid,String name, String title, String desc, String deadline,
String number, String city, String bloodtype, String image, String posttime, String postid){
this.userid = userid;
this.name = name;
this.title = title;
this.desc = desc;
this.deadline = deadline;
this.number = number;
this.city = city;
this.bloodtype = bloodtype;
this.image = image;
this.posttime = posttime;
this.postid = postid;
}
public String getUserid(){
return userid;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getDesc(){
return desc;
}
public String getDeadline(){
return deadline;
}
public String getNumber(){
return number;
}
public String getCity(){
return city;
}
public String getBloodtype(){
return bloodtype;
}
public String getImage(){
return image;
}
public String getPosttime(){
return posttime;
}
public String getPostid(){
return postid;
}
}
And a screenshot of posts in firestore bellow :
Well, i figure it out, i missed the onStart and onStop to start and stop listening for the adapter.
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
Related
Guys i'm trying to build App like Instagram. I'm struck to fetch the data from the Firebase database and storage. The recyclerView is showing nothing. Help me out in fixing that.
all the data are store in Firebase database.
Recyclerview Adapter page in the fragment page
ProgressBar proBar;
private FirebaseAuth.AuthStateListener authStateListener;
Context context;
String cuurentUser;
FirebaseAuth firebaseAuth;
FirebaseRecyclerAdapter adapter;
RecyclerView recyclerView;
List<Post> postingList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_reviews, container, false);
PostAdapter postAdapter = new PostAdapter(context, postingList);
recyclerView = view.findViewById(R.id.recycView);
proBar = view.findViewById(R.id.proBar);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(postAdapter);
postAdapter.notifyDataSetChanged();
firebaseAuth = FirebaseAuth.getInstance();
cuurentUser = firebaseAuth.getCurrentUser().getUid();
getDetails();
return view;
}
private void getDetails() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Query query = FirebaseDatabase.getInstance().getReference().child("Posts").child(cuurentUser);
FirebaseRecyclerOptions<Post> options = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(query, new SnapshotParser<Post>() {
#NonNull
#Override
public Post parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Post(snapshot.child("id").getValue().toString(),
snapshot.child("profileImg").getValue().toString(),
snapshot.child("username").getValue().toString(),
snapshot.child("postImg").getValue().toString(),
snapshot.child("description").getValue().toString(),
snapshot.child("time").getValue().toString(),
snapshot.child("date").getValue().toString(),
snapshot.child("title").getValue().toString()
);
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_item, parent, false);
//PostViewHolder viewHolder = new PostViewHolder(view);
return new PostViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final PostViewHolder holder, final int position, #NonNull final Post model) {
// String uid = getRef(position).getKey();
holder.uname.setText(model.getUsername());
holder.descrip.setText(model.getDescription());
holder.ptime.setText(model.getTime());
holder.pdate.setText(model.getDate());
holder.ptitle.setText(model.getTitle());
Glide.with(getContext()).load(model.getProfileImg()).into(holder.profImg);
Glide.with(getContext()).load(model.getPostImg()).into(holder.postImage);
holder.linear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
}
}, 2000);
}
#Override
public void onStart() {
super.onStart();
if(postingList != null)
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
TextView uname, fname, descrip, ptime, pdate, ptitle;
CircleImageView profImg;
ImageView postImage;
View mview;
LinearLayout linear;
public PostViewHolder(#NonNull View itemView) {
super(itemView);
mview = itemView;
linear = itemView.findViewById(R.id.linearRoot);
uname = itemView.findViewById(R.id.username);
fname = itemView.findViewById(R.id.fullname);
descrip = itemView.findViewById(R.id.description);
ptime = itemView.findViewById(R.id.ptime);
pdate = itemView.findViewById(R.id.pdate);
ptitle = itemView.findViewById(R.id.ptitle);
profImg = itemView.findViewById(R.id.profImg);
postImage = itemView.findViewById(R.id.postImg);
}
}
model page as Post.java
public class Post implements Parcelable {
public Post() {
}
private String uid;
private String postImg;
private String description;
private String username;
private String date;
private String time;
private String profileImg;
private String title;
public Post(String uid, String postImg, String description, String username, String date, String time, String profileImg, String title) {
this.uid = uid;
this.postImg = postImg;
this.description = description;
this.username = username;
this.date = date;
this.time = time;
this.profileImg = profileImg;
this.title = title;
}
protected Post(Parcel in) {
uid = in.readString();
postImg = in.readString();
description = in.readString();
username = in.readString();
date = in.readString();
time = in.readString();
profileImg = in.readString();
title = in.readString();
}
public static final Creator<Post> CREATOR = new Creator<Post>() {
#Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
#Override
public Post[] newArray(int size) {
return new Post[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getPostImg() {
return postImg;
}
public void setPostImg(String postImg) {
this.postImg = postImg;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getProfileImg() {
return profileImg;
}
public void setProfileImg(String profileImg) {
this.profileImg = profileImg;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(uid);
dest.writeString(postImg);
dest.writeString(description);
dest.writeString(username);
dest.writeString(date);
dest.writeString(time);
dest.writeString(profileImg);
dest.writeString(title);
}
}
xml page with recyclerView
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TabLayout.ReviewsFragment">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycView"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/proBar"/>
</FrameLayout>
Another xml page to show the details is post_item.xml
I have manage to get my document id in my AdminOfferFragment and I want to pass the value into the to EditOffer to update my data. I have tried using intent put extra to get my id in another activity but it still display null. So how can I pass my id after onClick in AdminOfferFragment to my EditOffer?
AdminOfferFragment
String id;
RecyclerView myRecycleView;
private FirestoreAdapter2 adapter;
FirebaseFirestore fStore;
private String email = "";
Button Btn;
Button Btn2;
FirebaseAuth fAuth;
String userId ="";
private Integer position = 0;
ArrayList<String> arraylist = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_admin_offer, container, false);
myRecycleView = v.findViewById(R.id.recyclerView);
Btn = v.findViewById(R.id.editBtn);
Btn2 = v.findViewById(R.id.deleteBtn);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
Btn2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
startActivity(new Intent(getActivity(),LoginUI.class));
}
});
Query query = fStore.collection("offer");
PagedList.Config config = new PagedList.Config.Builder().setInitialLoadSizeHint(10).setPageSize(3).build();
FirestorePagingOptions<OfferInfo> options = new FirestorePagingOptions.Builder<OfferInfo>().setLifecycleOwner(this)
.setQuery(query, config, new SnapshotParser<OfferInfo>() {
#NonNull
#Override
public OfferInfo parseSnapshot(#NonNull DocumentSnapshot snapshot) {
OfferInfo offerInfo = snapshot.toObject(OfferInfo.class);
String itemId = snapshot.getId();
offerInfo.setItem_id(itemId);
return offerInfo;
}
}).build();
adapter = new FirestoreAdapter2(options, this);
myRecycleView.setHasFixedSize(true);
myRecycleView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
myRecycleView.setAdapter(adapter);
return v;
}
#Override
public void onItemClick(DocumentSnapshot snapshot, int position) {
OfferInfo offerInfo = snapshot.toObject(OfferInfo.class);
Log.d("Item_CLICK", "Clicked the item : " + position + "and the ID:" + offerInfo.getName());
Log.d("Item_CLICK", "Clicked the item : " + position + "and the ID:" + snapshot.getId());
this.userId = snapshot.getId();
id = snapshot.getId();
String reward_name = offerInfo.getName();
String reward_description = offerInfo.getDescription();
String reward_point = Integer.toString(offerInfo.getPoint());
this.position = position;
Intent intent = new Intent(getActivity(), EditOffer.class);
intent.putExtra("ID", id);
intent.putExtra("REWARD_NAME", reward_name);
intent.putExtra("REWARD_DESCRIPTION", reward_description);
intent.putExtra("REWARD_POINT", reward_point);
startActivity(intent);
}
public String getOfferId(){
return id;
}
EditOffer
public class EditOffer extends AppCompatActivity {
EditText offer1, description1, point1;
Button editBtn;
FirebaseFirestore fStore;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_offer);
Intent intent = getIntent();
String reward_name = intent.getStringExtra("REWARD_NAME");
String reward_description = intent.getStringExtra("REWARD_DESCRIPTION");
String reward_point = intent.getStringExtra("REWARD_POINT");
offer1 = findViewById(R.id.Rewardinfo);
description1 = findViewById(R.id.description);
point1 = findViewById(R.id.point);
offer1.setText(reward_name);
description1.setText(reward_description);
point1.setText(reward_point);
id = intent.getStringExtra("ID");
editBtn = findViewById(R.id.Btn2);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Editable newname = offer1.getText();
Editable newdescription = description1.getText();
Editable newpoint = point1.getText();
updateDocument(newname, newdescription, newpoint, id);
}
});
}
private void updateDocument(Editable newname, Editable newdescription, Editable newpoint, String id) {
this.id = id;
DocumentReference documentReference = fStore.collection("offer").document(id);
documentReference.update("name", newname);
documentReference.update("description", newdescription);
documentReference.update("point", newpoint)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(EditOffer.this,"Document Updated",Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditOffer.this,e.getMessage(),Toast.LENGTH_LONG).show();
Log.d("Androidview", e.getMessage());
}
});
}
}
FirestoreAdapter2
public class FirestoreAdapter2 extends FirestorePagingAdapter<OfferInfo, FirestoreAdapter2.OfferViewHolder> {
private OnItemClickListener onItemClickListener;
public FirestoreAdapter2(#NonNull FirestorePagingOptions<OfferInfo> options, OnItemClickListener onItemClickListener) {
super(options);
this.onItemClickListener = (OnItemClickListener) onItemClickListener;
}
#Override
protected void onBindViewHolder(#NonNull OfferViewHolder holder, int position, #NonNull OfferInfo model) {
holder.list_email.setText(model.getName());
holder.list_fname.setText(model.getDescription());
holder.list_point.setText(Integer.toString(model.getPoint()));
}
#NonNull
#Override
public OfferViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.offer_item, parent, false);
return new OfferViewHolder(view);
}
public class OfferViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView list_email;
private TextView list_fname;
private TextView list_point;
public OfferViewHolder(#NonNull View itemview) {
super(itemview);
list_email = itemView.findViewById(R.id.textView);
list_fname = itemView.findViewById(R.id.textView2);
list_point = itemView.findViewById(R.id.textView3);
itemview.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(getItem(getAdapterPosition()), getAdapterPosition());
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot snapshot, int position);
}
}
OfferInfo
public class OfferInfo {
private String item_id;
private String name;
private String description;
private int point;
private OfferInfo(){}
private OfferInfo(String name, String description, String item_id, int point){
this.name = name;
this.description = description;
this.point = point;
this.item_id = item_id;
}
public String getName(){
return name;
}
public void setEmail(String name){
this.name = name;
}
public String getDescription(){
return description;
}
public void setFName(String description){
this.description = description;
}
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
}
In your new activity you don't initialize the firestoreref, so add this in the opened activity:
fStore = FirebaseFirestore.getInstance();
I'm making a messaging app for school, I'm trying to make the messages coming from the user align to the right and the messages from others align left.
I've been looking online to try and figure out how to do it, but I don't understand any of them well enough to apply them. I was hoping for some help with applying any option to my app.
SubjectGroupPage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject_group_page);
BottomNavigationView navView = findViewById(R.id.nav_view);
mTextMessage = findViewById(R.id.message);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
rvMessagesSubjectGroupPage.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, true));
final ArrayList<MessageObj> messages = new ArrayList<>();
ArrayList<MessageObj> messagesAdap = readMessages(rvMessagesSubjectGroupPage, messages);
MessageAdapter adapter = new MessageAdapter(messagesAdap);
rvMessagesSubjectGroupPage.setAdapter(adapter);
}
public ArrayList<MessageObj> readMessages(final RecyclerView rv, final ArrayList<MessageObj> messages) {
db.collection("messagesIT")
.orderBy("Timesent", Query.Direction.DESCENDING)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String message = document.getString("Message");
String senderName = document.getString("SenderName");
String sender = document.getString("Sender");
Timestamp timesent = document.getTimestamp("Timesent");
MessageObj mess;
mess = new MessageObj(message, sender, senderName, timesent);
messages.add(mess);
Log.d(TAG, "mmmmm: " + mess.getMessage());
Log.d(TAG, "sssss: " + mess.getSender());
Log.d(TAG, "ttttt:" + mess.getTimesent());
showToast("b");
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showToast("There has been an error, please try again later.");
Log.d(TAG, "Error: " + e);
}
});
return messages;
}
MessageAdapter.java
public class MessageAdapter extends
RecyclerView.Adapter<MessageAdapter.ViewHolder> {
private ArrayList<MessageObj> listdata;
private FirebaseAuth currentUser = FirebaseAuth.getInstance();
private boolean fromCurrentUser = true;
public static final String MyPREFERENCES = "MyPrefs";
private static String userObject = "";
private static final String TAG = "MessageAdapter.java";
public MessageAdapter(ArrayList<MessageObj> listdata) {
this.listdata = listdata;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView sender;
public TextView message;
public LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
this.sender = (TextView) itemView.findViewById(R.id.sender);
this.message = (TextView) itemView.findViewById(R.id.message);
linearLayout = (LinearLayout) itemView.findViewById(R.id.listLayout);
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MessageObj myListData = listdata.get(position);
holder.sender.setText(listdata.get(position).getSenderName());
holder.message.setText(listdata.get(position).getMessage());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "click on item: " + myListData.getSender(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem = layoutInflater.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
TextView sender;
TextView message;
LinearLayout linearLayout;
return viewHolder;
}
#Override
public int getItemCount() {
return listdata.size();
}
}
MessageObj.java
public class MessageObj {
private String message;
private String sender;
private String senderName;
private Timestamp timesent;
private boolean isCurrentUser;
public MessageObj() {}
public MessageObj(String message, String sender, String senderName, Timestamp timesent) {
this.message = message;
this.sender = sender;
this.senderName = senderName;
this.timesent = timesent;
}
public String getMessage() { return message; }
public String getSender() { return sender; }
public String getSenderName() { return senderName; }
public Timestamp getTimesent() { return timesent; }
I have an App which downloads data from Firebase and displays it in a RecyclerView and this works fine. What I want to do is show or hide an input element in the XML when certain conditions apply. The condition of 'yes' or 'no' is downloaded from Firebase.
It sort of works but only hides the TextView in the first item of the RecyclerView listing. How do I get it to apply to all the listed items? I will add the code and a screenshot.
Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menus);
setUpRecyclerView();
}
private void setUpRecyclerView() {
// get menu type from MenuSelectListActivity
selectedMenu = getIntent().getStringExtra("myMenuSelected");
//get Firestore db and use selected menu for listing
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference notebookRef = db.collection(selectedMenu);
FirestoreRecyclerOptions<NoteAdapter> options = new FirestoreRecyclerOptions.Builder<NoteAdapter>()
.setQuery(query, NoteAdapter.class)
.build();
adapter = new Note(options);
final RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
DocumentReference docRef = db.collection(“delivery status”).document(“****************”);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
String myDeliveryStatus = document.getString("deliverystatus");
// if delivery status yes then allow the order to be made
if (myDeliveryStatus.equals("yes")) {
// show quantity input TextView
TextView text_quantity = (TextView) findViewById(R.id.text_view_quantity);
//Toggle
if (text_quantity.getVisibility() == View.INVISIBLE)
text_quantity.setVisibility(View.VISIBLE);
else
text_quantity.setVisibility(View.VISIBLE);
adapter.setOnItemClickListener(new Note.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
String myTitle = ((TextView) recyclerView.findViewHolderForAdapterPosition(position).itemView.findViewById(R.id.text_view_title)).getText().toString();
String myPrice = ((TextView) recyclerView.findViewHolderForAdapterPosition(position).itemView.findViewById(R.id.text_view_price)).getText().toString();
String myNumberOrdered = ((TextView) recyclerView.findViewHolderForAdapterPosition(position).itemView.findViewById(R.id.text_view_quantity)).getText().toString();
***** do various calculations on the data downloaded from Firebase. Not relevant to this question so not included
}
// if no do nothing
else if (myDeliveryStatus.equals("no")) {
TextView text_quantity = (TextView) findViewById(R.id.text_view_quantity);
//Toggle to hide TextView
if (text_quantity.getVisibility() == View.VISIBLE)
text_quantity.setVisibility(View.INVISIBLE);
else
text_quantity.setVisibility(View.INVISIBLE);
}
} else {
// Log.d(TAG, "No such document");
}
} else {
// Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
Code for Adapter:
public class NoteAdapter {
private String title;
private String description;
private double price;
private int priority;
private int quantity;
private String status;
public NoteAdapter() {
//empty constructor needed
}
public NoteAdapter(String title, String description, double price, int priority, int quantity) {
this.title = title;
this.description = description;
this.price = price;
this.priority = priority;
this.quantity = quantity;
this.status = status;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
public int getPriority() {
return priority;
}
public int getQuantity() {
return quantity;
}
public String getStatus() {
return status;
}
}
Firstly you're doing some kind of mistake in Initializing the Recyclerview and Adapter. Which you are using as the adapter that's a just model or class.
Please have to look at this answer and change your code structure according to this Then You should do this step in BindViewHolder
adapter = new FirestoreRecyclerAdapter<NoteAdapter, ProductViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull holder productViewHolder, int position, #NonNull NoteAdapter productModel) {
//here you can check the Yes or No like this
if (poductModel.getStatus.equalsIgnoreCase("no")){
if (text_quantity.getVisibility() == View.VISIBLE)
text_quantity.setVisibility(View.INVISIBLE);
else
text_quantity.setVisibility(View.INVISIBLE);
}
}
#NonNull
#Override
public ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product, parent, false);
return new ProductViewHolder(view);
}
};
This is SearchActivity.java
public class SearchActivity extends AppCompatActivity
{
/*UI*/
private EditText mSearchText;
private Button mSearchBtn;
private Toolbar mSearchToolbar;
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private String value;
private TextWatcher tw;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mSearchText = (EditText)findViewById(R.id.activity_search_search_text);
mSearchBtn = (Button)findViewById(R.id.activity_search_search_btn);
mSearchToolbar = (Toolbar)findViewById(R.id.activity_search_toolbar);
setSupportActionBar(mSearchToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
mSearchBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
value = mSearchText.getText().toString();
Toast.makeText(SearchActivity.this, "value test 1: " + value, Toast.LENGTH_LONG).show();
searchText(value);
}
});
}
private void searchText(final String value)
{
Toast.makeText(SearchActivity.this, "value test 2: " + value, Toast.LENGTH_LONG).show();
mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager())
{
private final Fragment[] mFragments = new Fragment[]
{
new FragmentSearch(value)
};
#Override
public Fragment getItem(int position)
{
return mFragments[position];
}
#Override
public int getCount()
{
return mFragments.length;
}
};
mViewPager = (ViewPager) findViewById(R.id.activity_search_view_pager);
mViewPager.setAdapter(mPagerAdapter);
}
}
This is FragmentSearch.java
public class FragmentSearch extends MainFragment
{
public String value;
public FragmentSearch(String value)
{
this.value = value;
}
#Override
public Query getQuery(DatabaseReference databaseReference)
{
Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);
return postsQuery;
}
}
This is MainFragment.java
public abstract class MainFragment extends Fragment
{
private DatabaseReference mDatabase;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
private LinearLayoutManager mManager;
public MainFragment()
{
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
mRecycler = (RecyclerView)rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
Query postsQuery = getQuery(mDatabase);
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
PostViewHolder.class, postsQuery)
{
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position)
{
final DatabaseReference postRef = getRef(position);
final String postKey = postRef.getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Intent intent = new Intent(getActivity(), PostDetailActivity.class);
// intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
// startActivity(intent);
}
});
if(model.stars.containsKey(getUid()))
{
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
}
else
{
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
}
viewHolder.bindToPost(model, new View.OnClickListener()
{
#Override
public void onClick(View starView)
{
DatabaseReference globalPostRef = mDatabase.child("Post").child(postRef.getKey());
DatabaseReference userPostRef = mDatabase.child("UserPost").child(model.uid).child(postRef.getKey());
onStarClicked(globalPostRef);
onStarClicked(userPostRef);
}
});
}
};
mRecycler.setAdapter(mAdapter);
}
private void onStarClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.stars.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(getUid());
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
}
});
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mAdapter != null)
{
mAdapter.cleanup();
}
}
public String getUid()
{
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public abstract Query getQuery(DatabaseReference databaseReference);
}
This is PostViewHolder.java
public class PostViewHolder extends RecyclerView.ViewHolder
{
public TextView titleView;
public TextView authorView;
public ImageView starView;
public TextView numStarsView;
public TextView bodyView;
public PostViewHolder(View itemView)
{
super(itemView);
titleView = (TextView) itemView.findViewById(R.id.post_title);
authorView = (TextView) itemView.findViewById(R.id.post_author);
starView = (ImageView) itemView.findViewById(R.id.star);
numStarsView = (TextView) itemView.findViewById(R.id.post_num_stars);
bodyView = (TextView) itemView.findViewById(R.id.post_body);
}
public void bindToPost(Post post, View.OnClickListener starClickListener)
{
titleView.setText(post.title);
authorView.setText(post.author);
numStarsView.setText(String.valueOf(post.starCount));
bodyView.setText(post.body);
starView.setOnClickListener(starClickListener);
}
}
This is Post.java
#IgnoreExtraProperties
public class Post
{
public String uid;
public String author;
public String title;
public String body;
public int starCount = 0;
public String type;
public Map<String, Boolean> stars = new HashMap<>();
public Post()
{
}
public Post(String uid, String author, String title, String body, String type)
{
this.uid = uid;
this.author = author;
this.title = title;
this.body = body;
this.type = type;
}
#Exclude
public Map<String, Object> toMap()
{
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("author", author);
result.put("title", title);
result.put("body", body);
result.put("starCount", starCount);
result.put("stars", stars);
result.put("type", type);
return result;
}
}
Thank you so much for reading. I created a program to search title of the posts. When I type title in the EditText then press Search button, my toast1 test, toast2 test, and toast3 test give correct and same value and it successfully lists what I want with Query. But the problem is that when I type different text in EditText after deleting the previous text then press enter, toast3 test(in FragmentSearch.java) stays the same and does not change value. So, it just gives the previous result, not changed result. Can anyone assist me with this? Thank you!
The problem is that you only change the value on the FragmentSearch constructor. And this constructor is only called once, and not when you press Enter.
You should change your getQuery method to have this value as a parameter.
On your MainFragment.java:
public abstract Query getQuery(DatabaseReference databaseReference, String value);
On your FragmentSearch.java:
#Override
public Query getQuery(DatabaseReference databaseReference, String value)
{
this.value = value;
Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);
return postsQuery;
}