Trying to get key from firebase, instead getting a weird path - java

I have a database structure like this:
"users": {
"school": {
userId (randomkey) {
"email": "email#emai.email"
"provider": "provider"
}
}
}
I'm using a recycler view where users can add each other to a group. I'm showing the email for the user in the recycler view and that works fine. But the problem is that I need to retrieve the userId key for the email that is clicked on and append that to a List that I then push to firebase. I'm doing all that with this code.
Adapter class
class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ItemClickListenerPeopleToAdd itemClickListenerPeopleToAdd;
public TextView emailLbl;
public RecyclerViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
emailLbl = (TextView) itemView.findViewById(R.id.emailLbl);
}
public void setItemClickListenerPeopleToAdd(ItemClickListenerPeopleToAdd itemClickListenerPeopleToAdd) {
this.itemClickListenerPeopleToAdd = itemClickListenerPeopleToAdd;
}
#Override
public void onClick(View v) {
itemClickListenerPeopleToAdd.onClick(v, getAdapterPosition());
}
}
public class PeopleToAddAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
private static final String TAG = "Working";
public ArrayList<String> peopleList = new ArrayList<String>();
private List<ModelProject> mModelList;
public PeopleToAddAdapter(List<ModelProject> modelList) {
mModelList = modelList;
}
private Context context;
private List<PeopleToAdd> mPeopleToAdd;
public List<PeopleToAdd> mList;
public PeopleToAddAdapter(Context con, List<PeopleToAdd> list) {
this.context = con;
this.mPeopleToAdd = list;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.people_to_add_listview, parent, false);
return new RecyclerViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
final PeopleToAdd listItem = mPeopleToAdd.get(position);
holder.emailLbl.setText(listItem.getEmail());
holder.setItemClickListenerPeopleToAdd(new ItemClickListenerPeopleToAdd() {
#Override
public void onClick(View view, int position) {
Toast.makeText(context, "Click" + listItem.getEmail(), Toast.LENGTH_SHORT).show();
peopleList.add(listItem.toString());
Log.d("value", String.valueOf(peopleList));
}
});
}
#Override
public int getItemCount() {
return mPeopleToAdd.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView emailLbl;
public MyViewHolder(View itemView) {
super(itemView);
emailLbl = (TextView) itemView.findViewById(R.id.emailLbl);
}
}
}
PeopleToAdd
public class PeopleToAdd {
private String email;
private String provider;
public PeopleToAdd(String email, String provider) {
this.email = email;
this.provider = provider;
}
public PeopleToAdd() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
}
Activity class
listItems = new ArrayList<>();
schoolList = new ArrayList<>();
adapter = new PeopleToAddAdapter(this, listItems);
recyclerView.setAdapter(adapter);
mGetSchool = mDatabase.getReference().child("users").child(mCurrentUserId).child("schoolName");
protected void onStart() {
super.onStart();
mGetSchool.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
childPath = dataSnapshot.getValue(String.class);
//peopleAddedTxtView.setText(childPath);
mPeopleToAdd = mDatabase.getReference().child("users").child(childPath);
mPeopleToAdd.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
PeopleToAdd peopleToAdd = dataSnapshot.getValue(PeopleToAdd.class);
listItems.add(peopleToAdd);
test = dataSnapshot.getKey();
Log.d(TAG, test);
peopleToAddAdapter = new PeopleToAddAdapter(SetProject.this, listItems);
recyclerView.setAdapter(peopleToAddAdapter);
peopleToAddAdapter.notifyDataSetChanged();
}
#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) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I'm somehow getting a strange path as the userID
example: "com.appName.Services.PeopleToAdd#ca8f01". How can I get the right userId (the random key generated by firebase). I have it in the "test" String in activity but how can I add that to the List when a user clicks on that user in the reyclerView. I hope you understand me. Thank you in advance.

A snapshot contains two main things: the key from where the data was loaded, and the value that was loaded. Right now your onChildAdded only uses the value, and throws the key away:
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
PeopleToAdd peopleToAdd = dataSnapshot.getValue(PeopleToAdd.class);
listItems.add(peopleToAdd);
test = dataSnapshot.getKey();
Log.d(TAG, test);
peopleToAddAdapter = new PeopleToAddAdapter(SetProject.this, listItems);
recyclerView.setAdapter(peopleToAddAdapter);
peopleToAddAdapter.notifyDataSetChanged();
}
And since you need the key later in your code, you can't retrieve it anymore. The value doesn't contain the key.
One solution is to add the key to you PeopleToAdd class. Based on the answer I gave to Is there a way to store Key in class which I cast from Firebase object?, that could look like this for you:
public class PeopleToAdd {
#Exclude
public String key;
private String email;
private String provider;
public PeopleToAdd(String email, String provider) {
this.email = email;
this.provider = provider;
}
public PeopleToAdd() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
}
And then modify your onChildAdded to set the key on the PeopleToAdd it instantiated from the value:
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
PeopleToAdd peopleToAdd = dataSnapshot.getValue(PeopleToAdd.class);
peopleToAdd.key = dataSnapshot.getKey();
listItems.add(peopleToAdd);
peopleToAddAdapter = new PeopleToAddAdapter(SetProject.this, listItems);
recyclerView.setAdapter(peopleToAddAdapter);
peopleToAddAdapter.notifyDataSetChanged();
}
Now you can get the key of the PeopleToAdd from its key field.

Related

How to get the list from a node and use that list in a recyclerView to get data from firebase

I have a app with chatrooms where I want to show the people in that chatroom.When someone joins the chatroom I set the value of their node to be true.Like this
Like you can see I also have the data of users underit.I want to use the list of members/documentid and use that list to get the data of only those people from the profiledata node.
My class
public class chatroommembers extends AppCompatActivity {
String documentid;
RecyclerView recyclerView;
DatabaseReference peopleref;
DatabaseReference membersref;
private List<User> list;
private MembersAdapter membersAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatroommembers);
Intent data = getIntent();
documentid = data.getStringExtra("documentid");
peopleref = FirebaseDatabase.getInstance().getReference().child("Users").child("profiledata");
membersref = FirebaseDatabase.getInstance().getReference().child("Chatrooms").child("members").child(documentid);
recyclerView = findViewById(R.id.membersRecycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
membersref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1:snapshot.getChildren()){
String uid = snapshot1.getKey();
DatabaseReference peoplesref = peopleref.child(uid);
}
membersAdapter = new MembersAdapter(list);
recyclerView.setAdapter(membersAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public static class User{
String fullname,imageUrl,Uid,Email,Buddies;
public String getFullname() {
return fullname;
}
public User(){
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getUid() {
return Uid;
}
public void setUid(String uid) {
Uid = uid;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getBuddies() {
return Buddies;
}
public void setBuddies(String buddies) {
Buddies = buddies;
}
public User(String fullname, String imageUrl, String uid, String email, String buddies) {
this.fullname = fullname;
this.imageUrl = imageUrl;
Uid = uid;
Email = email;
Buddies = buddies;
}
}
public class MembersAdapter extends RecyclerView.Adapter<MembersAdapter.MembersViewHolder>{
private List<User> list;
public MembersAdapter(List<User> list) {
this.list = list;
}
#NonNull
#Override
public MembersAdapter.MembersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.users_recycler_layout,parent,false);
return new MembersAdapter.MembersViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MembersAdapter.MembersViewHolder holder, int position) {
User ld = list.get(position);
holder.name.setText(ld.getFullname());
if (ld.getImageUrl().equals("noimage")){
Glide.with(getApplicationContext()).load(R.drawable.profile).into(holder.circleImageView);
}else{
Glide.with(getApplicationContext()).load(ld.getImageUrl()).into(holder.circleImageView);
}
}
#Override
public int getItemCount() {
return list.size();
}
public class MembersViewHolder extends RecyclerView.ViewHolder{
TextView name;
CircleImageView circleImageView;
public MembersViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.usersname);
circleImageView = itemView.findViewById(R.id.usersimage);
}
}
}
}
What you're describing is a fairly standard operation known as a client-side join. In Android it'd look something like this:
String chatroomId = "-MBISFO12u2tok9CeWwi";
DatabaseReference membersRef = FirebaseDatabase.getInstance().getReference("Chatrooms/members").child(chatroomId);
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users/profiledata")
membersRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot memberSnapshot: dataSnapshot.getChildren()) {
String uid = memberSnapshot.getKey();
DatabaseReference userRef = usersRef.child(uid);
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot userSnapshot) {
Log.i("USER", userSnapshot.child("Full name").getValue(String.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Updating specific firebase field using recyclerview button in android

I'm developing a voting app using Android Studio in Java that uses RecyclerView to list all candidates from the Firebase database. I'm able to list all candidates, but can't implement the vote button to only update a specific candidate's total votes.
The data is picked and displayed in a RecyclerView as follows:
Candidates information in RecyclerView:
I need each time a user clicks on the vote button, the database totalVotes field is updated with a +1.
MyAdapter code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList <Candidate> candidates;
private DatabaseReference mDatabase;
public MyAdapter (Context c, ArrayList<Candidate> p){
context = c;
candidates =p;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.cardview, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.name.setText(candidates.get(position).getFirstname());
holder.party.setText(candidates.get(position).getParty());
holder.category.setText(candidates.get(position).getCategory());
Picasso.get().load(candidates.get(position).getImageurl()).into(holder.profilepic);
holder.onClick(position);
}
#Override
public int getItemCount() {
return candidates.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView name, party, category;
ImageView profilepic;
Button vote;
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
party = (TextView) itemView.findViewById(R.id.party);
profilepic = (ImageView) itemView.findViewById(R.id.profilepic);
category = (TextView) itemView.findViewById(R.id.category);
vote = (Button) itemView.findViewById(R.id.vote);
}
public void onClick(int position){
vote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
}
AllCandidates class that handles the adapter:
private DatabaseReference reference;
private RecyclerView recyclerView;
private ArrayList<Candidate> list;
private ArrayList<CandidateIMage> listimage;
private MyAdapter adapter;
private DatabaseReference imagereference;
FirebaseStorage storage;
StorageReference storageReference;
private static final String TAG = "AllCandidates";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_candidates);
//reference= FirebaseDatabase.getInstance().getReference().child("candidates");
recyclerView = (RecyclerView) findViewById(R.id.myRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<Candidate>();
listimage = new ArrayList<CandidateIMage>();
reference = FirebaseDatabase.getInstance().getReference();
Query presidentquery = reference.child("candidates").orderByChild("category").equalTo("President");
presidentquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Candidate p = dataSnapshot1.getValue(Candidate.class);
//String userId = dataSnapshot1.getKey();
//System.out.println("User id to be passed is: "+userId);
list.add(p);
}
adapter = new MyAdapter(AllCandidates.this, list);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
};
}
I had tried to add this code to the vote.onclicklostener but it is not working:
public void onClick(final int position){
postRef = FirebaseDatabase.getInstance().getReference("candidates");
vote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Candidate p = mutableData.getValue(Candidate.class);
if (p == null) {
return Transaction.success(mutableData);
} else {
int fetched = p.getTotalVotes();
fetched = fetched + 1;
String userId = postRef.push().getKey();
// Set value and report transaction success
postRef.child(userId).child("totalVotes").setValue(fetched);
//mutableData.setValue(p);
return Transaction.success(mutableData);
}
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
});
}
My Candidate m0del looks like this:
#IgnoreExtraProperties
public class Candidate {
private String firstname;
private String lastname;
private String party;
private String category;
private String candidateemail;
private String imageurl;
public Integer totalVotes;
// Default constructor required for calls to
// DataSnapshot.getValue(Candidate.class)
public Candidate() {
}
public Candidate(String imageurl, String candidateemail, String firstname, String lastname, String party, String category, Integer totalVotes) {
this.candidateemail = candidateemail;
this.imageurl = imageurl;
this.firstname = firstname;
this.lastname = lastname;
this.party = party;
this.category = category;
this.totalVotes = totalVotes;
}
public String getCandidateemail() {
return candidateemail;
}
public void setCandidateemail(String candidateemail) {
this.candidateemail = candidateemail;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getParty() {
return party;
}
public void setParty(String party) {
this.party = party;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Integer getTotalVotes() {
return totalVotes;
}
public void setTotalVotes(Integer totalVotes) {
this.totalVotes = totalVotes;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
According to your comment:
When I click on the vote button, it creates a new record in the database, instead of updating the totaLVotes field of the specific voted for a candidate.
This is happening because you are using the transaction in the wrong way. When you are using the following lines of code:
String userId = postRef.push().getKey();
postRef.child(userId).child("totalVotes").setValue(fetched);
You are pushing in the database every time a new total since the call to the .push() generates a new random key each time is called. To update only the totalVotes property, please use the following method:
public static void updateTotalVotes(String operation) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference totalVotesRef = rootRef.child("candidates").child("-M35sglMi8onCgvEDzbm").child("totalVotes");
totalVotesRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer votes = mutableData.getValue(Integer.class);
if (votes == null) {
return Transaction.success(mutableData);
}
if (operation.equals("increaseTotalVotes")) {
mutableData.setValue(votes + 1);
} else if (operation.equals("decreaseTotalVotes")){
mutableData.setValue(votes - 1);
}
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
});
}
See, you have to set use a reference that points to the totalVotes property. Now kick it off with:
updateTotalVotes("increaseTotalVotes");
For more information please check the official documentation regarding saving data as transactions.

Data from Firebase did not show in RecyclerView

My RecyclerView not show any data from Firebase. I don't see any errors at logcat so I don't know why. I followed guide from youtube video. But still nothing. I'm using android 8.0 and API 27. Hope Somebody can help.
My Main Activity Code:
public class ViewProduct extends AppCompatActivity {
DatabaseReference ref;
ArrayList<Model> list;
private RecyclerView recyclerView;
private RecyclerView.Adapter viewHolder;
private RecyclerView.LayoutManager layoutManager;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_product) ;
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").
child("Products");
recyclerView = findViewById(R.id.stallproductRecyclerView);
//recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//SEARCH VIEW
searchView = findViewById(R.id.searchProductStall);
//ADAPTER
list = new ArrayList<>();
viewHolder = new ViewHolder(list);
recyclerView.setAdapter(viewHolder);
}
#Override
protected void onRestart() {
super.onRestart();
if (ref!=null)
{
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
//list = new ArrayList<>();
list.clear();
for(DataSnapshot ds : dataSnapshot.getChildren())
{
list.add(ds.getValue(Model.class));
}
//ViewHolder viewHolder = new ViewHolder(list);
//recyclerView.setAdapter(viewHolder);
viewHolder.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ViewProduct.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
if (searchView !=null)
{
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s)
{
return false;
}
#Override
public boolean onQueryTextChange(String s) {
search(s);
return true;
}
});
}
}
private void search(String str) {
ArrayList<Model> myList = new ArrayList<>();
for(Model object : list)
{
if(object.getProductName().toLowerCase().contains(str.toLowerCase()))
{
myList.add(object);
}
}
ViewHolder viewHolder = new ViewHolder(myList);
recyclerView.setAdapter(viewHolder);
}
}
My Adapter:
public class ViewHolder extends RecyclerView.Adapter<ViewHolder.MyViewHolder> {
ArrayList<Model> list;
public ViewHolder (ArrayList<Model> list)
{
this.list=list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_product, viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.productName.setText(list.get(i).getProductName());
myViewHolder.productCalorie.setText(list.get(i).getProductCalorie());
myViewHolder.StallId.setText(list.get(i).getStallId());
myViewHolder.productType.setText(list.get(i).getProductType());
myViewHolder.productServing.setText(list.get(i).getProductServing());
myViewHolder.statusProduct.setText(list.get(i).getStatusProduct());
}
#Override
public int getItemCount()
{
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView productName, productCalorie, StallId;
TextView productType, productServing, statusProduct;
ImageView productImageView;
public MyViewHolder (#NonNull View itemView){
super((itemView));
productName = itemView.findViewById(R.id.productTitle);
productCalorie = itemView.findViewById(R.id.productDescriptionCalorie);
StallId = itemView.findViewById(R.id.productDescriptionStallId);
productType = itemView.findViewById(R.id.productDescriptionType);
productServing=itemView.findViewById(R.id.productDescriptionServing);
statusProduct=itemView.findViewById(R.id.productDescriptionAvailibility);
//productImageView = itemView.findViewById(R.id.productImageView);
}
}
}
My Model :
package com.example.buddymealplannerstall.Child;
import android.view.Display;
public class Model {
//String productName, productImage, productCalorie, StallId, productType, productServing, statusProduct;
private String StallId;
private String productCalorie;
private String productImage;
private String productName;
private String productServing;
private String productType;
private String statusProduct;
public Model (String StallId,
String productCalorie,
String productImage,
String productName,
String productServing,
String productType,
String statusProduct){
this.StallId = StallId;
this.productCalorie = productCalorie;
this.productImage = productImage;
this.productName = productName;
this.productServing = productServing;
this.productType = productType;
this.statusProduct = statusProduct;
}
public Model(){
}
public String getStallId() {
return StallId;
}
public void setStallId(String stallId) {
StallId = stallId;
}
public String getProductCalorie() {
return productCalorie;
}
public void setProductCalorie(String productCalorie) {
this.productCalorie = productCalorie;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductServing() {
return productServing;
}
public void setProductServing(String productServing) {
this.productServing = productServing;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getStatusProduct() {
return statusProduct;
}
public void setStatusProduct(String statusProduct) {
this.statusProduct = statusProduct;
}
}
Screen Shot of my firebase and my apps.
firebase
my app
According to your comment:
yes, buddymealplanner is my project's name
Please note that there is no need to add the name of your project as a child in the reference. So please change the following line of code:
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").
child("Products");
Simply to:
ref = FirebaseDatabase.getInstance().getReference().child("Products");
I dont think you are populating your list, you are sending it empty. From what I can see, you only add items to the list when you are restarting the activity. Try either populating it before sendinig the list, or changing the onRestart() for an onStart() or an onResume().

i am trying to make a chat activity in which users can chat personally.but some how only a singe data is been retrieve from the database

I am trying to learn to create a chat Activity and trying to retrieve all the message from the firebase when I send the message then the message is been stored in the firebase but at the time to receiving on the single message is been received.i am unable to understand the problem my code
personalChat.java//onstart method
protected void onStart() {
super.onStart();
rootRef.child("Message").child(CurrentUserId).child(msgReciverId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
message cMessage = dataSnapshot.getValue(message.class);
messageList.add(cMessage);
messageAdapter.notifyDataSetChanged();
}
#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) {
}
});
}
message_adapter.java
public class message_adapter extends RecyclerView.Adapter<message_adapter.MessageViewHolder> {
private List<message> usermsgList;
private FirebaseAuth mAuth;
private DatabaseReference userref;
public message_adapter(List<message> usermsgList){
this.usermsgList = usermsgList;
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.coustommsglayout,parent,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder holder, int position) {
String msgsenderid = mAuth.getCurrentUser().getUid();
message Message = usermsgList.get(position);
String fromuserid = Message.getFfrom();
String fromMessageType = Message.getType();
userref = FirebaseDatabase.getInstance().getReference().child("User").child(fromuserid);
userref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("image")){
String reciverimage = dataSnapshot.child("image").getValue().toString();
//Picasso.get().load(reciverimage).into(holder.reciverProfileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (fromMessageType.equals("Text")){
holder.recivermsgtext.setVisibility(View.INVISIBLE);
holder.reciverProfileImage.setVisibility(View.INVISIBLE);
if (fromuserid.equals(msgsenderid)){
holder.sendermsgtext.setBackgroundResource(R.drawable.sendermsglayout);
holder.sendermsgtext.setText(Message.getMessage());
}else{
holder.sendermsgtext.setVisibility(View.INVISIBLE);
holder.recivermsgtext.setVisibility(View.VISIBLE);
holder.reciverProfileImage.setVisibility(View.VISIBLE);
holder.recivermsgtext.setBackgroundResource(R.drawable.recivermsglayout);
holder.recivermsgtext.setText(Message.getMessage());
}
}
}
#Override
public int getItemCount() {
return usermsgList.size();
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
public TextView sendermsgtext,recivermsgtext;
public CircleImageView reciverProfileImage;
public MessageViewHolder(#NonNull View itemView){
super(itemView);
sendermsgtext = (TextView) itemView.findViewById(R.id.sender);
recivermsgtext = (TextView) itemView.findViewById(R.id.reciver);
reciverProfileImage = (CircleImageView) itemView.findViewById(R.id.profile_msg_dp);
}
}
}
it should show all the msg available in the Message.child(currentuser).child(reciveruserid). but it only shows the first value. Please help me out with this problem
firebase Message node
Message
JsmvpdGLjLbg9mQ0TfmKForis5q2
PnYKrGiS7YUp9JdHNDMurOSbGBw1
-LoHAND5o_T8S2NRECAH
ffrom: "JsmvpdGLjLbg9mQ0TfmKForis5q2"
message: "hello"
type: "Text"
-LoJCo9T7IrkHxD5xlZR
ffrom: "JsmvpdGLjLbg9mQ0TfmKForis5q2"
message: "whtsup"
type: "Text"
-LoJE04JSfl3BPyU3r9T
ffrom: "JsmvpdGLjLbg9mQ0TfmKForis5q2"
message: "wtsup"
type: "Text"

Simultaneous Arraylists

Firebase
FirebaseRecyclerOptions<SQLiteHelper> options =
new FirebaseRecyclerOptions.Builder<SQLiteHelper>()
.setQuery(mFetchingMessages, SQLiteHelper.class)
.build();
final MainData mHelper = new MainData(this);
final Cursor csr = myDBHlpr.getAllQuestions3();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<SQLiteHelper, Chat.MessagesViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final Chat.MessagesViewHolder holder, final int position, #NonNull final SQLiteHelper model) {
final DatabaseReference mTimeReference = FirebaseDatabase.getInstance().getReference().child("Messages").child(MessageSenderId).child(MessageRecieverId);
Query messageQuery = mTimeReference.limitToLast(10);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
SQLiteHelper message = dataSnapshot.getValue(SQLiteHelper.class);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
messages.add(message);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
#Override
public Chat.MessagesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_activity_chat, parent, false);
return new Chat.MessagesViewHolder(view);
}
};
messageList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
SQLite
while (csr.moveToNext()) {
String mSender = csr.getString(csr.getColumnIndex(KEY_SENDER));
String mMessage = csr.getString(csr.getColumnIndex(KEY_MESSAGE));
long mTime = csr.getLong(csr.getColumnIndex(KEY_TIME));
String mSeen = csr.getString(csr.getColumnIndex(KEY_SEEN));
String mTimer = csr.getString(csr.getColumnIndex(KEY_TIMER));
String mType = csr.getString(csr.getColumnIndex(KEY_TYPE));
messages.add(new SQLiteHelper(mSender, mMessage, mType, mSeen, mTimer, mTime));
mAdapter.notifyDataSetChanged();
When i have both only the firebase data is shown and when i remove or comment the firebase part of code the sqlite part of code is shown in recyclerview. Can someone suggest me to make the firebase code show below the sqlite code somehow please?

Categories

Resources