I'm trying to get the children from my JSON separately and pass them through an intent. Here is how my JSON is formatted:
"allDeeJays" : {
"-LeP1DB6Onzh4-UiN_0E" : {
"acct" : "Aaron A",
"djName" : "uhgvvvbbb"
}
},
Using the DataSnapshot, I have been able to get the djName values, but I am not getting the acct values, with the following code:
#Override
protected void onBindViewHolder(#NonNull ResultsViewHolder holder, final int position, #NonNull final DataSnapshot snapshot) {
// Here you convert the DataSnapshot to whatever data your ViewHolder needs
String s = "";
for(DataSnapshot ds : snapshot.getChildren())
{
s = ds.getValue(String.class);
DjProfile model = new DjProfile(s);
model.setDjName(s);
holder.setDjProfile(model);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("allDeeJays");
String acct = "";
String name = "";
for(DataSnapshot ds : snapshot.getChildren())
{
name = ds.getValue(String.class);
acct = ds.getValue(String.class);
DjProfile model = new DjProfile(name);
model.setDjName(name);
}
Intent i = new Intent(getApplication(), AddSongRequest.class);
i.putExtra("DjName", name);
i.putExtra("UserAcct", acct);
startActivity(i);
}
});
}
};
Finally, my DjProfile class is defined as follows:
package com.example.android.heydj;
import com.google.firebase.database.Exclude;
import com.google.firebase.database.PropertyName;
public class DjProfile
{
String djName;
String key;
public DjProfile(String djName)
{
this.djName = djName;
}
public DjProfile(){}
public void setDjName(String djName)
{
this.djName = djName;
}
public String getdjName()
{
return djName;
}
}
Both variables are returning the same value, and when I run snapshot.getChildrenCount() it says that there are two children (which I assume are acct, and djName). Do I need to add additional getters and setters for the account name? Any help is greatly appreciated :)
Try like this and it's will return exact value for your keys
if(snapShot.getKey().equalsIgnoreCase("djName"))
name = ds.getValue(String.class);
if(snapShot.getKey().equalsIgnoreCase("acct"))
acct = ds.getValue(String.class);
or use
DjProfile model = snapShot.getValue(DjProfile.class);
instead of
for(DataSnapshot ds : snapshot.getChildren())
{
name = ds.getValue(String.class);
acct = ds.getValue(String.class);
DjProfile model = new DjProfile(name);
model.setDjName(name);
}
You can resolve this by adding below line -
DjProfile profile = ds.getValue(DjProfile.class);
You can now pass this profile into an Intent.
Related
I'm not getting the output from Firebase database. It's not returning anything. Here is my data structure.
I also tried getting value through query but it returned database error:
Cannot convert java.util.hashmap to String
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference().child("Member").push();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String value = ds.getValue(String.class);
Log.d("Tag", "Value is" + value);
}
}
JSON:
{
"Member" : {
"-LhKJVG1Tj2628sHPg4D" : {
"age" : "21",
"name" : "Gagan",
"nickname" : "Gaggi"`enter code here`
},
"-LhKKaNFnPrrh1bQNPfH" : {
"age" : "18",
"name" : "Jashan",
"nickname" : "Jassi"
}
}
}
You cannot call getValue with String.class because it does not meet the criteria of the method call.
From the documentation
public T getValue(Class valueType)
This method is used to marshall the data contained in this snapshot into a class of your choosing. The class must fit 2 simple constraints:
The class must have a default constructor that takes no arguments
The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized
An example class might look like:
class Message {
private String author;
private String text;
private Message() {}
public Message(String author, String text) {
this.author = author;
this.text = text;
}
public String getAuthor() {
return author;
}
public String getText() {
return text;
}
}
// Later
Message m = snapshot.getValue(Message.class);
You can use String class
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name= ds.child("name").getValue(String.class);
String age= ds.child("age").getValue(String.class);
//and similar for others
Log.d("TAG", email + " / " + name);
}
}
I need help in this code.
How can I fetch logged in user data from firebase database?
These are my codes:
public void getUserInfo(){
mFirebaseDatabase = FirebaseDatabase.getInstance();
mUserDatabase = mFirebaseDatabase.getReference("users");
FirebaseUser user = mAuth.getCurrentUser();
mUserDatabase.child(userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( com.google.firebase.database.DataSnapshot datasnapshot) {
for (DataSnapshot dataSnapshot : datasnapshot.getChildren()) {
User user1 = dataSnapshot.getValue(User.class);
String firstname = user1.getFirstName();
String secondname = user1.getSecondName();
String email = user1.getEmail();
String enrollment = user1.getEnrollnumber();
String branch = user1.getBranch();
String college = user1.getCollege();
First_name.setText(firstname);
Second_name.setText(secondname);
tx_Email.setText(email);
Enroll_number.setText(enrollment);
}
}
#Override
public void onCancelled(DatabaseError firebaseError) {
/*
* You may print the error message.
**/
}
});
}
Any help would be appreciated!
As far as I can see, you're attaching a listener to the data of a single user. That means that you don't need to loop over dataSnapshot.getChildren() in onDataChange.
So:
public void onDataChange( com.google.firebase.database.DataSnapshot snapshot) {
User user1 = snapshot.getValue(User.class);
String firstname = user1.getFirstName();
String secondname = user1.getSecondName();
String email = user1.getEmail();
String enrollment = user1.getEnrollnumber();
String branch = user1.getBranch();
String college = user1.getCollege();
First_name.setText(firstname);
Second_name.setText(secondname);
tx_Email.setText(email);
Enroll_number.setText(enrollment);
}
try this, in my case my database in firebase is called "Users", with and userID is the id of each user, using this userID i filter the data of each user example (name, email...etc)
You need to write a for to iterate all fields and after that get the position that you need, example position[0] = name, position[1] = email...etc
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference idRef = rootRef.child("Users").child(userID);
final List<String> lstItems= new ArrayList<String>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String values = (String) ds.getValue();
lstItems.add(values);
}
Log.d(TAG, "NAME: " + lstItems.get(0).toString());
Log.d(TAG, "EMAIL: " + lstItems.get(1).toString());
and to print them
email = lstItems.get(0).toString();
name = lstItems.get(1).toString();
I hope it helps you
So this is my bind model class:
public class UserBanknoteAmountBindModel {
public String id;
public String userId;
public String banknoteType;
public String banknoteAmount;
public UserBanknoteAmountBindModel(){
}
public String getBanknoteAmount() {
return banknoteAmount;
}
public String getBanknoteType() {
return banknoteType;
}
public String getUserId() {
return userId;
}
public void setBanknoteAmount(String banknoteAmount) {
this.banknoteAmount = banknoteAmount;
}
public void setBanknoteType(String banknoteType) {
this.banknoteType = banknoteType;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
(idk if acess modifiers matter in this case).
I am trying to parse my data:
for (DataSnapshot banknoteAmount:dataSnapshot.getChildren()){
UserBanknoteAmountBindModel userBanknoteAmountBindModel=dataSnapshot.getValue(UserBanknoteAmountBindModel.class);
Log.wtf("hgfh", banknoteAmount.getValue().toString());
}
I see that I am receiving my data because I can log it.
{banknoteAmount=3, banknoteType=20_dollar,
userId=112371098270685247195}
Anyway my data doesn't get inside my bind model. I read somewhere that I need not only to provide getters but also setters (that's why I put those setters PS: Is the thing for the setters true?).
Any ideas?
EDIT: Database Structure https://i.stack.imgur.com/o5Hgp.png
PS: The problem was that I was using the parameter from another function for the getValue (not the foorloop variable)
To get the values of banknoteAmount, banknoteType and userId, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
UserBanknoteAmountBindModel userBanknoteAmountBindModel = ds.getValue(UserBanknoteAmountBindModel.class);
String banknoteAmount = userBanknoteAmountBindModel.getBanknoteAmount();
String banknoteType = userBanknoteAmountBindModel.getBanknoteType();
String userId = userBanknoteAmountBindModel.getUserId();
Log.d("TAG", banknoteAmount + " / " + banknoteType + " / " + userId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userBanknoteAmountRef.addListenerForSingleValueEvent(valueEventListener);
The output will be:
3 / 20_dollar / 112371098270685247195
When you are using the following line of code:
banknoteAmount.getValue().toString()
You are actually printing the String representation of banknoteAmount.getValue() which has as a return value a Map object which contains those three values.
This is firebase database details
Here I want to search details using child without use parent key. According to this database, I want to get price and category using Name without using parent key ("kjhsfkgkrlhg"), ("get price, category where Name="super Creamcracker")
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference itemsRef = rootRef.child("Items");
Query query = itemsRef.orderByChild("Name").equalsTo("super Creamcracker");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String category = ds.child("Category").getValue(String.class);
long price = ds.child("Price").getValue(Long.class);
Log.d("TAG", category + " / " + price);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
So the ds contains a list of results. Even if there is only a single result, the ds will contain a list of one result. So the output will be:
200g / 200
First, you make database reference first
DatabaseReference itemRef = FirebaseDatabase.getInstance().getReference("Items");
then,
String itemName = "super Creamcracker";
Query query = itemRef.orderByChild("Name").startAt(itemName).endAt(itemName+ "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
//if you dont have class for item
String price = data.child("Price").getValue().toString();
String category = data.child("Category").getValue().toString();
//if you have class, lets say Item.java
Item item = data.getValue(Item.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have a class as seen Below:
public class GlobalHighScore {
String name;
int score;
public GlobalHighScore(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
And here I try to make a data receiving.
DatabaseReference scoresRef = firebaseDatabase.getReference("Highscores");
scoresRef.child("GlobalHighScore").orderByChild("score").limitToFirst(10);
scoresRef.addValueEventListener(new ValueEventListener() {
#Override public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> keys = dataSnapshot.getChildren();
int i = 0;
for (DataSnapshot key : keys) {
if(i == 10)
break;
orderName[i].setText(key.getValue().toString());
i++;
}
}
When I am doing this, key.getValue().toString() returns json formatted String but I want "name" and "score" seperately. Also, my data is not sorted eventhough I make it sorted.
scoresRef.child("GlobalHighScore").orderByChild("score").limitToFirst(10);
I think I having problem here.
Edit: When I order by "score", it gives data according to date.
Last form is
final TextView[] orderScore = {firstscore, secondscore, thirdscore, fourthscore, fifthscore, sixthscore, seventhscore, eightscore, ninthscore, tenthscore};
final TextView[] orderName = {firstname, secondname, thirdname, fourthname, fifthname, sixthname, seventhname, eightname, ninthname, tenthname};
DatabaseReference scoresRef = firebaseDatabase.getReference("Highscores").child("GlobalHighScore");
scoresRef.orderByChild("score").limitToFirst(10);
scoresRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot data : dataSnapshot.getChildren()) {
if(i == 10)
break;
String name = data.child("name").getValue().toString();
String score = data.child("score").getValue().toString();
orderName[i].setText(name);
orderScore[i].setText(score);
i++;
}
}
It gives no data record at all.
Try this:
DatabaseReference scoresRef = firebaseDatabase.getReference("Highscores").child("GlobalHighScore");
Query q=scoresRef.orderByChild("score").limitToFirst(10);
q.addValueEventListener(new ValueEventListener() {
#Override public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnapshot.getChildren()){
String name=datas.child("name").getValue().toString();
String score=datas.child("score").getValue().toString();
}
}
Since you want the name and the score alone you can do the above, to be able to retrieve them alone.
.orderByChild("score").limitToFirst(10);, using this you will get the first 10, nodes that have the child score.
limitToFirst(10) //to get the first 10 of a specific child
limitToLast(10) //to get the Last 10 of a specific child
When you are using the following line of code:
Iterable<DataSnapshot> keys = dataSnapshot.getChildren();
The childrens that you are getting when iterating are actual objects, not Strings. Using toString() method doesn't make any sense because you cannot cast an Object to a String and expect to get the values within it. That's why you are getting that "json formatted Strings". So what are you getting when iterating are actual maps. So to get the name and score you need to iterate through the map and use: map.get("name"); and map.get("score");.
You don't need to change the entire code, your code is fine. Just solve this minor issue.