FirestoreRecyclerAdapter shows Nothing - android

I am using FirestoreRecyclerAdapter and faced with the problems.
I read Firestore database documents and retrieve them to the recyclerview but for some reason, does not show anything. I don't know why. Can anyone help me? I would really thankful if anyone could help me.
Thank you in advance!.
This is Adapter;
public MyFriendsAdapter(#NonNull FirestoreRecyclerOptions<ProfileModelClass> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MyFriendsViewholder holder, int position, #NonNull ProfileModelClass model)
{
holder.myNickname.setText(model.getNickname());
holder.myAge.setText(model.getAge());
holder.myGender.setText(model.getGender());
holder.myDistance.setText(model.getDistance());
holder.myUserDescription.setText(model.getUserDescription());
holder.myMarriage.setText(model.getMarriage());
holder.myAddress.setText(model.getAddress());
// String visit_user_id = getSnapshots().getSnapshot(position).getId();
// Intent chatIntent = new Intent(MainActivity.this, ChatActivity.class);
// chatIntent.putExtra("visit_user_id", visit_user_id);
// startActivity(chatIntent);
Glide.with(holder.myProfileImageView.getContext()).load(model.getProfileImage()).placeholder(R.drawable.profile).into(holder.myProfileImageView);
Glide.with(holder.myPictureOne.getContext()).load(model.getPictureOne()).placeholder(R.drawable.select_image).into(holder.myPictureOne);
Glide.with(holder.myPictureTwo.getContext()).load(model.getPictureTwo()).placeholder(R.drawable.select_image).into(holder.myPictureTwo);
/* holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String visit_user_id = getRef(position).getKey();
Intent profileIntent = new Intent(FindFriendsActivity.this, ProfileActivity.class);
profileIntent.putExtra("visit_user_id", visit_user_id);
startActivity(profileIntent);
}
}); */
}
#NonNull
#Override
public MyFriendsViewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_friends_list_layout,
parent, false);
return new MyFriendsViewholder(view);
}
class MyFriendsViewholder extends RecyclerView.ViewHolder
{
CircleImageView myProfileImageView;
TextView myNickname,myAge, myGender, myDistance, myUserDescription, myMarriage, myAddress,
myFriendsProfile, SendMessageButton;
ImageView myPictureOne, myPictureTwo;
public MyFriendsViewholder(#NonNull View itemView)
{
super(itemView);
myProfileImageView = itemView.findViewById(R.id.all_friends_profile_image_layout);
myNickname = itemView.findViewById(R.id.all_friends_nickname_layout);
myGender = itemView.findViewById(R.id.all_friends_gender_layout);
myAge = itemView.findViewById(R.id.all_friends_age_layout);
myDistance = itemView.findViewById(R.id.all_friends_distance_layout);
myUserDescription = itemView.findViewById(R.id.all_friends_description_layout);
myMarriage = itemView.findViewById(R.id.all_friends_marriage_layout);
myAddress = itemView.findViewById(R.id.all_friends_address_layout);
myPictureOne = itemView.findViewById(R.id.all_friends_post_image_first);
myPictureTwo = itemView.findViewById(R.id.all_friends_post_image_second);
myFriendsProfile = itemView.findViewById(R.id.all_friends_information_layout);
SendMessageButton = itemView.findViewById(R.id.all_friends_call_layout);
myFriendsProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent profileIntent = new Intent(v.getContext(), ProfileActivity.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(profileIntent);
}
});
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent messageIntent = new Intent(v.getContext(), ChatActivity.class);
messageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(messageIntent);
}
});
This is AllConditionFriendsActivity;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_condition_friends);
mToolbar = (Toolbar) findViewById(R.id.all_condition_age_salary_appbar_layout);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("친구찾기");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAgeSalaryRecyclerList= (RecyclerView) findViewById(R.id.all_condition_age_salary_list);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
queryFirstAgeSalaryFriends();
}
private void queryFirstAgeSalaryFriends()
{
firstAgeSalaryColRef
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task)
{
if (task.isSuccessful())
{
for (DocumentSnapshot documentSnapshot : task.getResult())
{
if ( documentSnapshot.exists())
{
String age = documentSnapshot.getString("age");
String salary = documentSnapshot.getString("salary");
String gender = documentSnapshot.getString("gender");
if (gender == "남자(//man)" && age == "19살(//age19)" && salary == "대학(원)생(//graduate student)")
{
showManFirstAgeSalaryFriendsList();
}
else if (gender == "여자(//woman)" && age == "19살(//age19)" && salary == "대학(원)생(//graduate student)")
{
showWomanFirstAgeSalaryFriendsList();
}
}
}
}
else
{
}
}
});
}
private void showWomanFirstAgeSalaryFriendsList()
{
Query womanSalaryQuery = db.collection("usersProfiles")
.whereEqualTo("gender", "남자(//man)")
.whereEqualTo("age", "19살(//age19)")
.whereEqualTo("salary", "대학(원)생(//graduate student)");
FirestoreRecyclerOptions<ProfileModelClass> options = new FirestoreRecyclerOptions.Builder<ProfileModelClass>()
.setQuery(womanSalaryQuery, ProfileModelClass.class)
.build();
adapter = new MyFriendsAdapter(options);
mAgeSalaryRecyclerList.setHasFixedSize(true);
mAgeSalaryRecyclerList.setLayoutManager(new LinearLayoutManager(this));
adapter.startListening();
mAgeSalaryRecyclerList.setAdapter(adapter);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
private void showManFirstAgeSalaryFriendsList()
{
Query manSalaryQuery = db.collection("usersProfiles")
.whereEqualTo("gender", "여자(//woman)")
.whereEqualTo("age", "19살(//age19)")
.whereEqualTo("salary", "대학(원)생(//graduate student)");
FirestoreRecyclerOptions<ProfileModelClass> options = new FirestoreRecyclerOptions.Builder<ProfileModelClass>()
.setQuery(manSalaryQuery, ProfileModelClass.class)
.build();
adapter = new MyFriendsAdapter(options);
mAgeSalaryRecyclerList.setHasFixedSize(true);
mAgeSalaryRecyclerList.setLayoutManager(new LinearLayoutManager(this));
adapter.startListening();
mAgeSalaryRecyclerList.setAdapter(adapter);
This is Model class;
private String address, age, marriage, gender, nickname, profileImage, userDescription, pictureOne, pictureTwo, distance;
public ProfileModelClass() {
}
public ProfileModelClass(String address, String age, String marriage, String gender, String nickname, String profileImage, String userDescription, String pictureOne, String pictureTwo, String distance) {
this.address = address;
this.age = age;
this.marriage = marriage;
this.gender = gender;
this.nickname = nickname;
this.profileImage = profileImage;
this.userDescription = userDescription;
this.pictureOne = pictureOne;
this.pictureTwo = pictureTwo;
this.distance = distance;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getMarriage() {
return marriage;
}
public void setMarriage(String marriage) {
this.marriage = marriage;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getProfileImage() {
return profileImage;
}
public void setProfileImage(String profileImage) {
this.profileImage = profileImage;
}
public String getUserDescription() {
return userDescription;
}
public void setUserDescription(String userDescription) {
this.userDescription = userDescription;
}
public String getPictureOne() {
return pictureOne;
}
public void setPictureOne(String pictureOne) {
this.pictureOne = pictureOne;
}
public String getPictureTwo() {
return pictureTwo;
}
public void setPictureTwo(String pictureTwo) {
this.pictureTwo = pictureTwo;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
}
Firestore DB;

Your code is querying:
db.collection("usersProfiles")
But in your screenshot, the collection is named GenderAgeSalary. If that is indeed the collection you want to query and show, it should be:
db.collection("GenderAgeSalary")...

Related

Firebase Chat Recycler View Left and Right View Not Working Android

Hi I want the chat message Align like this when I send message I want them on the right when I receive I want them on left like this in the image
but it looks like this even though I set to two different layouts for in and out but it appears in the same way
In ChatRoomActvity getItemViewType(int position) always return as MESSAGE_IN_VIEW_TYPE;
What am I missing here?
ChatRoomActvity.java
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mFirebaseDatabaseReference;
private FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>
mFirebaseAdapter;
public static final String MESSAGES_CHILD = "messages";
public static final String ANONYMOUS = "anonymous";
private static final String TAG = "ChatRoomAct";
private static final int REQUEST_IMAGE = 2;
private static final String LOADING_IMAGE_URL = "https://www.google.com/images/spin-32.gif";
private FloatingActionButton mSendButton;
private RecyclerView mMessageRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ProgressBar mProgressBar;
private EditText mMessageEditText;
private ImageView mAddMessageImageView;
private String mUsername;
private String mPhotoUrl;
private String mUserid;
private String mSenderUid;
//Emoji Function
private ImageView emojiButton;
private EmojiPopup emojiPopup;
private ViewGroup rootView;
private EmojiEditText editText;
private final int MESSAGE_IN_VIEW_TYPE = 1;
private final int MESSAGE_OUT_VIEW_TYPE = 2;
public static class MessageViewHolder extends RecyclerView.ViewHolder {
TextView mTime;
CircleImageView imgProfile;
TextView messageTextView;
ImageView messageImageView;
TextView messengerTextView;
CircleImageView messengerImageView;
TextView mLikesCount;
ImageView imgDropdown, imgLikes;
public MessageViewHolder(View v) {
super(v);
messengerTextView = (TextView) itemView.findViewById(R.id.message_user);
messageTextView = (TextView) itemView.findViewById(R.id.message_text);
mTime = (TextView) itemView.findViewById(R.id.message_time);
messengerImageView = (CircleImageView) itemView.findViewById(R.id.imgDps);
imgLikes = itemView.findViewById(R.id.imgLikes);
mLikesCount = (TextView)itemView.findViewById(R.id.message_Likes);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room_actvity);
// Initialize ProgressBar and RecyclerView.
mProgressBar = (ProgressBar) findViewById(R.id.loader);
mMessageRecyclerView = (RecyclerView) findViewById(R.id.list);
mLinearLayoutManager = new LinearLayoutManager(ChatRoomActvity.this);
mLinearLayoutManager.setStackFromEnd(true);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
mUserid = mFirebaseUser.getUid();
mUsername = ANONYMOUS;
if (mFirebaseUser == null) {
finish();
return;
} else {
mUsername = mFirebaseUser.getDisplayName();
if (mFirebaseUser.getPhotoUrl() != null) {
mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
}
}
displaychatmessages();
}
public void displaychatmessages() {
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
SnapshotParser<FriendlyMessage> parser = new SnapshotParser<FriendlyMessage>() {
#NonNull
#Override
public FriendlyMessage parseSnapshot(DataSnapshot snapshot) {
FriendlyMessage friendlyMessage = snapshot.getValue(FriendlyMessage.class);
if (friendlyMessage != null) {
friendlyMessage.setId(snapshot.getKey());
}
return friendlyMessage;
}
};
DatabaseReference messagesRef = mFirebaseDatabaseReference.child(MESSAGES_CHILD);
FirebaseRecyclerOptions<FriendlyMessage> options =
new FirebaseRecyclerOptions.Builder<FriendlyMessage>()
.setQuery(messagesRef, parser)
.build();
mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(options) {
#Override
public int getItemViewType(int position) {
if(getItem(position).getId().equals(mFirebaseAuth.getCurrentUser().getUid()))
{
return MESSAGE_OUT_VIEW_TYPE;
} else {
return MESSAGE_IN_VIEW_TYPE;
}
}
#Override
protected void onBindViewHolder(MessageViewHolder viewHolder, int position, FriendlyMessage friendlyMessage) {
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
if (friendlyMessage.getText() != null) {
viewHolder.messageTextView.setText(friendlyMessage.getText());
viewHolder.messageTextView.setVisibility(TextView.VISIBLE);
viewHolder.mTime.setText(DateFormat.format("dd MMM (h:mm a)", friendlyMessage.getMessageTime()));
viewHolder.mLikesCount.setText(String.valueOf(friendlyMessage.getMessageLikesCount()));
if (friendlyMessage.getMessageLikes() != null) {
if (friendlyMessage.getMessageLikes().containsValue(mUserid)) {
viewHolder.imgLikes.setImageResource(R.drawable.red_heart);
} else {
viewHolder.imgLikes.setImageResource(R.drawable.chat_heart);
}
}
}
viewHolder.messengerTextView.setText(friendlyMessage.getName());
if (friendlyMessage.getPhotoUrl() == null) {
viewHolder.messengerImageView.setImageDrawable(ContextCompat.getDrawable(ChatRoomActvity.this,
R.drawable.profile));
} else {
Glide.with(ChatRoomActvity.this)
.load(friendlyMessage.getPhotoUrl())
.into(viewHolder.messengerImageView);
}
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = null;
if(i==MESSAGE_IN_VIEW_TYPE){
view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.message_in, viewGroup, false);
}
else if(i==MESSAGE_OUT_VIEW_TYPE){
view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.message_out, viewGroup, false);
}
return new MessageViewHolder(view);
}
};
mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = mFirebaseAdapter.getItemCount();
int lastVisiblePosition =
mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the
// user is at the bottom of the list, scroll to the bottom
// of the list to show the newly added message.
if (lastVisiblePosition == -1 ||
(positionStart >= (friendlyMessageCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
mMessageRecyclerView.scrollToPosition(positionStart);
}
}
});
mMessageRecyclerView.setAdapter(mFirebaseAdapter);
mMessageEditText = (EditText) findViewById(R.id.input);
mMessageEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
mSendButton = (FloatingActionButton) findViewById(R.id.btnSend);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FriendlyMessage friendlyMessage = new
FriendlyMessage(mUserid,mMessageEditText.getText().toString(),null,
mUsername,
mPhotoUrl,
null /* no image */);
mFirebaseDatabaseReference.child(MESSAGES_CHILD)
.push().setValue(friendlyMessage);
mMessageEditText.setText("");
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAdapter.startListening();
}
#Override
protected void onPause() {
super.onPause();
mFirebaseAdapter.stopListening();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
if (requestCode == REQUEST_IMAGE) {
if (resultCode == RESULT_OK) {
if (data != null) {
final Uri uri = data.getData();
Log.d(TAG, "Uri: " + uri.toString());
FriendlyMessage tempMessage = new FriendlyMessage(null,null,null,mUsername, mPhotoUrl,
LOADING_IMAGE_URL);
mFirebaseDatabaseReference.child(MESSAGES_CHILD).push()
.setValue(tempMessage, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError,
DatabaseReference databaseReference) {
if (databaseError == null) {
String key = databaseReference.getKey();
StorageReference storageReference =
FirebaseStorage.getInstance()
.getReference(mFirebaseUser.getUid())
.child(key)
.child(uri.getLastPathSegment());
putImageInStorage(storageReference, uri, key);
} else {
Log.w(TAG, "Unable to write message to database.",
databaseError.toException());
}
}
private void putImageInStorage(StorageReference storageReference, Uri uri, String key) {
storageReference.putFile(uri).addOnCompleteListener(ChatRoomActvity.this,
new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
task.getResult().getMetadata().getReference().getDownloadUrl()
.addOnCompleteListener(ChatRoomActvity.this,
new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
FriendlyMessage friendlyMessage =
new FriendlyMessage(null,null,null, mUsername, mPhotoUrl,
task.getResult().toString());
mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
.setValue(friendlyMessage);
}
}
});
} else {
Log.w(TAG, "Image upload task was not successful.",
task.getException());
}
}
});
}
});
}
}
}
}
}
FriendlyMessage.java
public class FriendlyMessage {
private String id;
private String text;
private String name;
private String photoUrl;
private String imageUrl;
private long messageTime;
private long messageLikesCount;
private Map<String, Boolean> messageLikes = new HashMap<>();
public FriendlyMessage(){}
public FriendlyMessage(String id,String text,String name, String photoUrl, String imageUrl) {
this.id = id;
this.text = text;
this.name = name;
messageTime = new Date().getTime();
this.photoUrl = photoUrl;
this.imageUrl = imageUrl;
this.messageLikesCount = messageLikesCount;
this.messageLikes= messageLikes;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhotoUrl() {
return photoUrl;
}
public String getText() {
return text;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public long getMessageTime() {
return messageTime;
}
public void setMessageTime(long messageTime) {
this.messageTime = messageTime;
}
public long getMessageLikesCount() {
return messageLikesCount;
}
public void setMessageLikesCount(long messageLikesCount) {
this.messageLikesCount = messageLikesCount;
}
public Map<String, Boolean> getMessageLikes() {
return messageLikes;
}
public void setMessageLikes(Map<String, Boolean> messageLikes) {
this.messageLikes = messageLikes;
}
}
I can't without the images (for any reason, they are not in the post) but from what I see,
getItem(position).getId().equals(mFirebaseAuth.getCurrentUser().getUid())
and
FriendlyMessage.getId()
I'd say you're not taking the sender into account. ID is conventionally used as a message number, they usually do not point to a uid. Besides, your class already has a field called senderUid, so you should compare against that instead of id.
Optionally, try to log the line before the condition.
#Override
public int getItemViewType(int position) {
FriendlyMessage friendlyMessage = getItem(position);
boolean user = (friendlyMessage.getUserid().equals(mUserid));
if(user)
{
return MESSAGE_OUT_VIEW_TYPE;
} else {
return MESSAGE_IN_VIEW_TYPE;
}
}
I use boolean

How to pass id in snapshot to other activity android

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();

How to enable and disable button in accordance with the value firebase database

i'm setting up a new online shop application and want to make a condition if value "state" in firebase database is "Not Payments" enable the buttons MYConfirmPayments and MYShowOrderBtn. And if value "state" in firebase database is "Waiting Payments Confirm" disable button MYConfirmPayments.
public class MyOrdersActivity extends AppCompatActivity {
private RecyclerView myOrderList;
private Query myOrdersRef;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_orders);
myOrdersRef = FirebaseDatabase.getInstance().getReference()
.child("Orders")
.orderByKey().equalTo(Prevalent.currentOnlineUser.getPhone());
myOrderList = findViewById(R.id.myOrders_list);
myOrderList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart()
{
super.onStart();
FirebaseRecyclerOptions<UserOrders> options =
new FirebaseRecyclerOptions.Builder<UserOrders>()
.setQuery(myOrdersRef, UserOrders.class)
.build();
FirebaseRecyclerAdapter<UserOrders,MyOrdersActivity.UserOrdersViewHolder> adapter =
new FirebaseRecyclerAdapter<UserOrders, MyOrdersActivity.UserOrdersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyOrdersActivity.UserOrdersViewHolder holder, final int position, #NonNull final UserOrders model)
{
holder.MYuserName.setText("Nama : " + model.getName());
holder.MYuserPhoneNumber.setText("Nomor Telepon : " + model.getPhone());
holder.MYuserTotalprice.setText("Total Harga = Rp " + model.getTotalAmount());
holder.MYuserDateTime.setText("Dipesan Pada: " + model.getDate() + " " + model.getTime());
holder.MYusershippingAddress.setText("Alamat: " + model.getAddress() + ", " + model.getCity());
holder.MYorderstate.setText("Status: "+ model.getState());
holder.MYconfirmPayments.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view)
{
String uID = getRef(position).getKey();
Intent intent = new Intent(MyOrdersActivity.this, ConfirmPaymentsActivity.class);
intent.putExtra("uid", uID);
startActivity(intent);
}
});
holder.MYshowOrderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String uID = getRef(position).getKey();
Intent intent = new Intent(MyOrdersActivity.this, AdminUserProductsActivity.class);
intent.putExtra("uid", uID);
startActivity(intent);
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
CharSequence options[] = new CharSequence[]
{
"Ya",
"Tidak"
};
AlertDialog.Builder builder = new AlertDialog.Builder(MyOrdersActivity.this);
builder.setTitle("Sudah Menerima Barang ini ?");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
if (i == 0)
{
String uID = getRef(position).getKey();
RemoverOrder(uID);
}
else
{
finish();
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public MyOrdersActivity.UserOrdersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.orders_layout, parent, false);
return new MyOrdersActivity.UserOrdersViewHolder(view);
}
};
myOrderList.setAdapter(adapter);
adapter.startListening();
}
public static class UserOrdersViewHolder extends RecyclerView.ViewHolder
{
public TextView MYuserName, MYuserPhoneNumber, MYuserTotalprice, MYuserDateTime, MYusershippingAddress, MYorderstate;
public Button MYconfirmPayments, MYshowOrderBtn;
public UserOrdersViewHolder(View itemView)
{
super(itemView);
MYuserName = itemView.findViewById(R.id.myOrders_user_name);
MYuserPhoneNumber = itemView.findViewById(R.id.myOrders_phone_number);
MYuserTotalprice = itemView.findViewById(R.id.myOrders_total_price);
MYuserDateTime = itemView.findViewById(R.id.myOrders_date_time);
MYusershippingAddress = itemView.findViewById(R.id.myOrders_address_city);
MYorderstate = itemView.findViewById(R.id.myOrders_state);
MYconfirmPayments = itemView.findViewById(R.id.myConfirm_payments);
MYshowOrderBtn= itemView.findViewById(R.id.myShow_all_products);
}
}
private void RemoverOrder(String uID)
{
}
}
My UserOrders Class
public class UserOrders
{
private String name, phone, address, city, state, date, time, totalAmount;
public UserOrders()
{
}
public UserOrders(String name, String phone, String address, String city, String state, String date, String time, String totalAmount) {
this.name = name;
this.phone = phone;
this.address = address;
this.city = city;
this.state = state;
this.date = date;
this.time = time;
this.totalAmount = totalAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
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 getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(String totalAmount) {
this.totalAmount = totalAmount;
}
}
And this My Firebase Database Structured
You can use this code :
database = FirebaseDatabase.getInstance().getReference();
database.child("Orders").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {
UserOrders order = userDataSnapshot.getValue(UserOrders.class);
String state = order .getState();
if (state.equals("Not Payments")) {
MYConfirmPayments.setEnabled(true);
MYShowOrderBtn.setEnabled(true);
}else if (state.equals("Not Payments")){
MYConfirmPayments.setEnabled(false);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w("tag", "loadPost:onCancelled", databaseError.toException());
}
});

How do I access the children in my firebase database and display them in the activity according to the listview item selected

I have my app whwere i need to display the information regarding the item that is clicked on in the listview. However that is the data stored in my firebase database. The database looks like this:
Now i want to click on the listview item so that i can display the information corresponding to it in a different activity.
The code for the MainActivity where the listview and Firebase is stored is:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
public TicketAdapter adapter;
private final static int RC_SIGN_IN = 2;
public String mUsername;
public static String ComplaintID;
public static String StatusImg;
public static String TicketCat;
public static String SubCat;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference().child("Ticket");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = mFirebaseAuth.getCurrentUser();
if (user != null) {
onSignedInInitialized(user.getDisplayName());
} else {
onSignedOutCleanup();
startActivityForResult(
getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()))
.build(),
RC_SIGN_IN);
}
}
};
final ListView listView = (ListView)findViewById(R.id.lvTicket);
final ArrayList<Ticket> arrayOfTicket = new ArrayList<>();
adapter = new TicketAdapter(this, arrayOfTicket);
listView.setAdapter(adapter);
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Ticket ticket = (Ticket)dataSnapshot.getValue(Ticket.class);
adapter.add(ticket);
adapter.notifyDataSetChanged();
assert ticket != null;
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
final DatabaseReference TicketCategory = mDatabaseReference.child("Ticket").child("ticketCategory");
TicketCategory.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String TCategory = dataSnapshot.child("ticketCategory").getValue(String.class);
TicketCat = TCategory;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Ticket ticket = new Ticket();
Intent intent = new Intent(view.getContext(), ComplaintDetail.class);
startActivity(intent);
}
});
final Button button = (Button) findViewById(R.id.complaintbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, TicketCategory.class);
startActivity(intent);
}
}
);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.action_settings:
{
AuthUI.getInstance().signOut(this);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
private void detachDatabaseReadListener()
{
if(mChildEventListener != null)
{
mDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
#Override
protected void onResume()
{
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause()
{
super.onPause();
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
private void onSignedInInitialized(String username)
{
mUsername = username;
// attachDatabaseReadListener();
}
private void onSignedOutCleanup()
{
mUsername = null;
}
This is the code for the activity where i want to display the children:
public class ComplaintDetail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint_detail);
TextView tvComplaintID = (TextView)findViewById(R.id.complaintid);
TextView tvTicketCat = (TextView)findViewById(R.id.TicketHeading);
TextView tvSubCat = (TextView)findViewById(R.id.Subheading);
//tvComplaintID.setText(MainActivity.StatusImg);
tvTicketCat.setText( MainActivity.TicketCat);
// tvSubCat.setText(MainActivity.SubCat);
final Button butt = findViewById(R.id.review);
butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(ComplaintDetail.this, Review.class);
startActivity(intent);
}
});
final Button button = findViewById(R.id.close);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(ComplaintDetail.this, "This ticket is closed!!", Toast.LENGTH_SHORT).show();
}
});
}}
I want to display the children: ticketCategory, subcategory and status.
I will highly appreciate any help.
thank you!!
[EDIT]
public class Ticket {
String ticketCategory;
String name;
String complaintID;
String subcategory;
String priority;
String status;
private String comments;
private String cannedReply;
public Ticket(){}
public Ticket (String ticketCategory, String subcategory, String priority, String status, String comments, String cannedReply)
{
this.ticketCategory = ticketCategory;
// this.Name = Name;
this.subcategory = subcategory;
this.priority = priority;
this.status = status;
this.comments = comments;
this.cannedReply = cannedReply;
}
public void setTicketCategory(String ticketCategory) {
this.TicketCategory = ticketCategory;
}
public void setName(String name) {
this.Name = name;
}
public void setSubcategory(String subcategory) {
this.Subcategory = subcategory;
}
public void setPriority(String priority) {
this.priority = priority;
}*/
public void setStatus(String status) {
this.status = status;
}
public String getTicketCategory() {
return ticketCategory;
}
public String getSubcategory() {
return subcategory;
}
public String getPriority() {
return priority;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getCannedReply() {
return cannedReply;
}
public void setCannedReply(String cannedReply) {
this.cannedReply = cannedReply;
}
public String getStatus() {return status;}
public String getComplaintID() {
return complaintID;
}
public static ArrayList<Ticket> getTicket()
{
ArrayList<Ticket> tickets = new ArrayList<Ticket>();
return tickets;
}}
Just make your ticket class as serializable and pass it in bundel and parse in other activity like bellow
First change your Ticket class definition like bellow
public class Ticket implements Serializable {
Then after change your click code like bellow
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(view.getContext(), ComplaintDetail.class);
intent.putExtra("ticket", ticket);
startActivity(intent);
}
});
And finally parse and get your object in second activity like bellow
Ticket ticket= (Ticket) getIntent().getSerializableExtra("ticket");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(view.getContext(), ComplaintDetail.class);
intent.putExtra("ticket", ticket);
startActivity(intent);
}
});
The object i mentioned ticket in intent is the object u receive from fireabse and you need make a object parceable to be able to send it to another activity.So, make sure sure to make it parceable.
The below is the model class with implementing parceable interface:-
public class Ticket implements Parcelable {
private String ticketCategory;
private String name;
private String complaintID;
private String subcategory;
private String priority;
private String status;
private String comments;
private String cannedReply;
public Ticket() {
}
public Ticket(String ticketCategory, String subcategory, String priority, String status, String comments, String cannedReply) {
this.ticketCategory = ticketCategory;
// this.Name = Name;
this.subcategory = subcategory;
this.priority = priority;
this.status = status;
this.comments = comments;
this.cannedReply = cannedReply;
}
public String getTicketCategory() {
return ticketCategory;
}
public void setTicketCategory(String ticketCategory) {
this.ticketCategory = ticketCategory;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComplaintID() {
return complaintID;
}
public void setComplaintID(String complaintID) {
this.complaintID = complaintID;
}
public String getSubcategory() {
return subcategory;
}
public void setSubcategory(String subcategory) {
this.subcategory = subcategory;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getCannedReply() {
return cannedReply;
}
public void setCannedReply(String cannedReply) {
this.cannedReply = cannedReply;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.ticketCategory);
dest.writeString(this.name);
dest.writeString(this.complaintID);
dest.writeString(this.subcategory);
dest.writeString(this.priority);
dest.writeString(this.status);
dest.writeString(this.comments);
dest.writeString(this.cannedReply);
}
protected Ticket(Parcel in) {
this.ticketCategory = in.readString();
this.name = in.readString();
this.complaintID = in.readString();
this.subcategory = in.readString();
this.priority = in.readString();
this.status = in.readString();
this.comments = in.readString();
this.cannedReply = in.readString();
}
public static final Parcelable.Creator<Ticket> CREATOR = new Parcelable.Creator<Ticket>() {
#Override
public Ticket createFromParcel(Parcel source) {
return new Ticket(source);
}
#Override
public Ticket[] newArray(int size) {
return new Ticket[size];
}
};
}
So,I have the set and get methods and implemented the parceable i.e made the class parceable so that u can send the entire object.Now in other activity where you will be receiving,You can just use get methods like below
First get the intent through getIntent() in onCreate and declare the object Ticket.
ticket = getIntent().getParcelableExtra("Ticket");
And where you need the object there you can directly access it like below
ticket.getSubcategory();
ticket.getTicketCategory();
ticket.getStatus();
So,Thats it ask me if you didn't get any thing and if it is not working.

RecyclerView to Firebase database

I actually want cardView in my RecyclerView to retrieve data from firebase but it returns error. Please do help me to attach my RecyclerView to firebase and retrieve data from it.
Thanking you in advance.
Here is the mainActivity.java
mbloglist = findViewById(R.id.rv1);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
productAdapter adapter = new productAdapter(this);
mbloglist.setLayoutManager(layoutManager);
mbloglist.setAdapter(adapter);
Toast.makeText(getApplicationContext(),"Layout starting",Toast.LENGTH_SHORT).show();
database1 = FirebaseDatabase.getInstance();
myRef = database1.getReference("Users");
Toast.makeText(getApplicationContext(),"Database Done",Toast.LENGTH_SHORT).show();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e("pppp","onDataChange"+dataSnapshot.toString());
Toast.makeText(getApplicationContext(),"Done",Toast.LENGTH_SHORT).show();
for(DataSnapshot child : dataSnapshot.getChildren()){
ModelClass modelClass = child.getValue(ModelClass.class);
modelClassList.add(modelClass);
}
Toast.makeText(getApplicationContext(),"Done Done",Toast.LENGTH_SHORT).show();
adapter.addItems(modelClassList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("pppp","onCancelled");
}
});
}
Here is the Adapter which named ProductAdapter.java
public productAdapter(Context context) {
this.context = context;
this.productList = new ArrayList<>();
}
public void addItems(List<ModelClass> productList){
this.productList = productList;
this.notifyDataSetChanged();
}
#NonNull
#Override
public productViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new productViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false));
}
#Override
public void onBindViewHolder(#NonNull productViewHolder holder, int position) {
ModelClass modelClass = productList.get(position);
holder.shop_name.setText(modelClass.getStore_name());
holder.phone_number.setText(modelClass.getphone_number());
holder.v7b.setText(modelClass.getV7b());
holder.v7g.setText(modelClass.getV7g());
holder.y53b.setText(modelClass.getY53b());
holder.y53g.setText(modelClass.getY53g());
holder.v7pb.setText(modelClass.getV7pb());
holder.v7pg.setText(modelClass.getV7pg());
holder.y55sb.setText(modelClass.getY55sb());
holder.y55sg.setText(modelClass.getY55sb());
holder.i3b.setText(modelClass.getI3b());
holder.i3go.setText(modelClass.getI3go());
holder.i3gr.setText(modelClass.getI3gr());
holder.i3prob.setText(modelClass.getI3prob());
holder.i3progo.setText(modelClass.getI3progo());
holder.i3progr.setText(modelClass.getI3progr());
holder.i5b.setText(modelClass.getI5b());
holder.i5go.setText(modelClass.getI5go());
holder.i5gr.setText(modelClass.getI5gr());
holder.i5prob.setText(modelClass.getI5prob());
holder.i5progo.setText(modelClass.getI5progo());
holder.i5progr.setText(modelClass.getI5progr());
holder.i7b.setText(modelClass.getI7b());
holder.i7go.setText(modelClass.getI7go());
holder.i7gr.setText(modelClass.getI7gr());
holder.camonb.setText(modelClass.getCamonb());
holder.camongo.setText(modelClass.getCamongo());
holder.camonbl.setText(modelClass.getCamonbl());
}
#Override
public int getItemCount() {
return 0;
}
class productViewHolder extends RecyclerView.ViewHolder{
private TextView shop_name,phone_number,v7b,v7g,y53b,y53g,v7pb,v7pg,y55sb,y55sg,y69b,y69g,i3b,i3go,i3gr,i3prob,i3progo,i3progr,i5b,i5go,i5gr,i5prob,i5progo,i5progr,i7b,i7go,i7gr,camonb,camongo,camonbl;
public productViewHolder(View itemView){
super(itemView);
shop_name = itemView.findViewById(R.id.EditText2000);
phone_number=itemView.findViewById(R.id.EditText2001);
v7b=itemView.findViewById(R.id.EditText101);
v7g=itemView.findViewById(R.id.EditText102);
y53b=itemView.findViewById(R.id.EditText103);
y53g=itemView.findViewById(R.id.EditText104);
v7pb=itemView.findViewById(R.id.EditText105);
v7pg=itemView.findViewById(R.id.EditText106);
y55sb=itemView.findViewById(R.id.EditText107);
y55sg=itemView.findViewById(R.id.EditText108);
y69b=itemView.findViewById(R.id.EditText109);
y69g=itemView.findViewById(R.id.EditText110);
i3b=itemView.findViewById(R.id.EditText111);
i3go=itemView.findViewById(R.id.EditText112);
i3gr=itemView.findViewById(R.id.EditText113);
i3prob=itemView.findViewById(R.id.EditText114);
i3progo=itemView.findViewById(R.id.EditText115);
i3progr=itemView.findViewById(R.id.EditText116);
i5b=itemView.findViewById(R.id.EditText117);
i5go=itemView.findViewById(R.id.EditText118);
i5gr=itemView.findViewById(R.id.EditText119);
i5prob=itemView.findViewById(R.id.EditText120);
i5progo=itemView.findViewById(R.id.EditText121);
i5progr=itemView.findViewById(R.id.EditText122);
i7b=itemView.findViewById(R.id.EditText123);
i7go=itemView.findViewById(R.id.EditText124);
i7gr=itemView.findViewById(R.id.EditText125);
camonb=itemView.findViewById(R.id.EditText126);
camongo=itemView.findViewById(R.id.EditText127);
camonbl=itemView.findViewById(R.id.EditText128);
Here is the modelclass.java which attached to firebase
public class ModelClass {
String v7b;
String v7g;
String y53b;
String y53g;
String v7pb;
String v7pg;
String y55sb;
String y55sg;
String y69b;
String y69g;
String i3b;
String i3go;
String i3gr;
String i3prob;
String i3progo;
String i3progr;
String i5b;
String i5go;
String i5gr;
String i5prob;
String i5progo;
String i5progr;
String i7b;
String i7go;
String i7gr;
String camonb;
String camongo;
String camonbl;
String email;
String store_name;
String phone_number;
public ModelClass() {
}
public ModelClass(String v7b, String v7g, String y53b, String y53g, String v7pb, String v7pg, String y55sb, String y55sg, String y69b, String y69g, String i3b, String i3go, String i3gr, String i3prob, String i3progo, String i3progr, String i5b, String i5go, String i5gr, String i5prob, String i5progo, String i5progr, String i7b, String i7go, String i7gr, String camonb, String camongo, String camongr) {
this.v7b = v7b;
this.v7g = v7g;
this.y53b = y53b;
this.y53g = y53g;
this.v7pb = v7pb;
this.v7pg = v7pg;
this.y55sb = y55sb;
this.y55sg = y55sg;
this.y69b = y69b;
this.y69g = y69g;
this.i3b = i3b;
this.i3go = i3go;
this.i3gr = i3gr;
this.i3prob = i3prob;
this.i3progo = i3progo;
this.i3progr = i3progr;
this.i5b = i5b;
this.i5go = i5go;
this.i5gr = i5gr;
this.i5prob = i5prob;
this.i5progo = i5progo;
this.i5progr = i5progr;
this.i7b = i7b;
this.i7go = i7go;
this.i7gr = i7gr;
this.camonb = camonb;
this.camongo = camongo;
this.camonbl = camongr;
}
public ModelClass(String email, String store_name, String phone_number) {
this.email = email;
this.store_name = store_name;
this.phone_number = phone_number;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
String phone;
public String getV7b() {
return v7b;
}
public void setV7b(String v7b) {
this.v7b = v7b;
}
public String getV7g() {
return v7g;
}
public void setV7g(String v7g) {
this.v7g = v7g;
}
public String getY53b() {
return y53b;
}
public void setY53b(String y53b) {this.y53b = y53b;}
public String getY53g() {
return y53g;
}
public void setY53g(String y53g) {
this.y53g = y53g;
}
public String getV7pb() {
return v7pb;
}
public void setV7pb(String v7pb) {
this.v7pb = v7pb;
}
public String getV7pg() {
return v7pg;
}
public void setV7pg(String v7pg) {
this.v7pg = v7pg;
}
public String getY55sb() {
return y55sb;
}
public void setY55sb(String y55sb) {
this.y55sb = y55sb;
}
public String getY55sg() {
return y55sg;
}
public void setY55sg(String y55sg) {
this.y55sg = y55sg;
}
public String getY69b() {
return y69b;
}
public void setY69b(String y69b) {
this.y69b = y69b;
}
public String getY69g() {
return y69g;
}
public void setY69g(String y69g) {
this.y69g = y69g;
}
public String getI3b() {
return i3b;
}
public void setI3b(String i3b) {
this.i3b = i3b;
}
public String getI3go() {
return i3go;
}
public void setI3go(String i3go) {
this.i3go = i3go;
}
public String getI3gr() {
return i3gr;
}
public void setI3gr(String i3gr) {
this.i3gr = i3gr;
}
public String getI3prob() {
return i3prob;
}
public void setI3prob(String i3prob) {
this.i3prob = i3prob;
}
public String getI3progo() {
return i3progo;
}
public void setI3progo(String i3progo) {
this.i3progo = i3progo;
}
public String getI3progr() {
return i3progr;
}
public void setI3progr(String i3progr) {
this.i3progr = i3progr;
}
public String getI5b() {
return i5b;
}
public void setI5b(String i5b) {
this.i5b = i5b;
}
public String getI5go() {
return i5go;
}
public void setI5go(String i5go) {
this.i5go = i5go;
}
public String getI5gr() {
return i5gr;
}
public void setI5gr(String i5gr) {
this.i5gr = i5gr;
}
public String getI5prob() {
return i5prob;
}
public void setI5prob(String i5prob) {
this.i5prob = i5prob;
}
public String getI5progo() {
return i5progo;
}
public void setI5progo(String i5progo) {
this.i5progo = i5progo;
}
public String getI5progr() {
return i5progr;
}
public void setI5progr(String i5progr) {
this.i5progr = i5progr;
}
public String getI7b() {
return i7b;
}
public void setI7b(String i7b) {
this.i7b = i7b;
}
public String getI7go() {
return i7go;
}
public void setI7go(String i7go) {
this.i7go = i7go;
}
public String getI7gr() {
return i7gr;
}
public void setI7gr(String i7gr) {
this.i7gr = i7gr;
}
public String getCamonb() {
return camonb;
}
public void setCamonb(String camonb) {
this.camonb = camonb;
}
public String getCamongo() {
return camongo;
}
public void setCamongo(String camongo) {
this.camongo = camongo;
}
public String getCamonbl() {
return camonbl;
}
public void setCamongr(String camongr) {
this.camonbl = camongr;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStore_name() {
return store_name;
}
public void setStorename(String storename) {this.store_name = storename;}
public String getphone_number() {
return phone_number;
}
public void setphone_number(String phone_number) {
this.phone_number = phone_number;
}
}
Here is the Firebase Realtime Database Image
ModelClass class and your database doesn't have the same structure, because in your database you have a new node called "phone" inside each userID node.
You can try 3 approaches to solve this issue:
a.) Write data in your database just like ModelClass is, without "phone" node.
b.) Create a new class called "Phone" with same attributes you have inside "phone" node in the database, and make this new class part of ModelClass class.
c.) On myRef onDataChange method, inside for statement, check for each child key and fill ModelClass atributes one by one. When the child key is equal to "phone", start a new loop statement in "phone" children to fill these attributes.
Add the following code:
#Override
public int getItemCount() {
return productList.size();
}

Categories

Resources