How to retrieve particular data from firebase? - android

While retrieving the data I am using this code
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Firebasemodel firebasemodel = data.getValue(Firebasemodel.class);
firebasemodels.add(firebasemodel);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});`
This code snippet which returns the complete data of firebase database.
But I want to retrieve the complete data of particular users. How do I achieve it?
Thanks in advance

Try code below:
FirebaseDatabase.getInstance().getReference().child("notepad-secure/notepad").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
while (dataSnapshots.hasNext()) {
user = dataSnapshotChild.getValue(User.class);
users_list.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Error", "---" + databaseError.getMessage());
}
});
Model class:
public class User {
public String id;
public String note;
public String tittle;
public User() {
}
public User(String id, String note, String tittle) {
this.id= id;
this.note= note;
this.tittle= tittle;
}
}
And Declare
List<User> users_list;
User user;

Please use this code for getting all data:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String id = ds.child("id").getValue(String.class);
String note = ds.child("note").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String user = ds.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + users);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
And your output will be:
-Kono2LMSe... / sadsad / sadsad / NK46X......
If you want to retrieve only specific data, please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad").child("NK46...");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = ds.child("id").getValue(String.class);
String note = ds.child("note").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String user = ds.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + users);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
It will work for sure.

Related

Firebase User Chat Rating - Android

First of all, I'm a real beginner in Android and want to learn.
I want to rate a user who responded to my initiated message using firebase. So only once can the user who initiated the conversation
rate the other user, but only after the response ( first response, no matter what response, even if it is just "hi")
He can receive any amount of ratings (positive or negative) but from different users), in my case, I add/subtract 10 for every vote.
My Firebase DB structure looks like this:
Layout:
I have tried this way, but haven't succeeded:
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
messageRef = mRootRef.child("messages")
.child(mCurrentUserId)
.child(mChatUser);
chatRef = mRootRef.child("chat")
.child(mCurrentUserId)
.child(mChatUser);
final Query convQuery = chatRef;
convQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Conv conversation = dataSnapshot.getValue(Conv.class);
convVoted = conversation.isVoted();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Query messageCheckQuery = messageRef.orderByKey();
messageCheckQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
final String messageKey = dataSnapshot.getKey();
String messageTo = message.getTo();
voteBoolean = message.isVoted();
if (!messageTo.equals(mCurrentUserId)) {
ratingLayout.setVisibility(View.GONE);
} else {
if (!convVoted) {
ratingLayout.setVisibility(View.VISIBLE);
Query query = mRootRef.child("user_account_settings")
.orderByKey()
.equalTo(mChatUser);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot singleSnapshot = dataSnapshot.getChildren().iterator().next();
UserInfo userInfo = singleSnapshot.getValue(UserInfo.class);
voteNumberStr = userInfo.getMessage_rating();
Log.d("RATING", " Voted : " + convVoted + " | Rating Number : " + voteNumberStr);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mVoteUpBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
voteNumber = Integer.parseInt(voteNumberStr);
voteNumber = voteNumber + 10;
voteNumberStr = String.valueOf(voteNumber);
convVoted = true;
//voteBoolean = true;
mRootRef.child("messages")
.child(mCurrentUserId)
.child(mChatUser)
.child(messageKey)
.child("voted").setValue(true);
mRootRef.child("chat")
.child(mCurrentUserId)
.child(mChatUser)
.child("voted").setValue(true);
mRootRef.child("user_account_settings")
.child(mChatUser)
.child("message_rating").setValue(voteNumberStr);
Log.d("RATING", " clicked : " + convVoted + " | Rating Number : " + voteNumberStr);
ratingLayout.setVisibility(View.GONE);
}
});
mVoteDownBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
voteNumber = voteNumber - 10;
voteNumberStr = String.valueOf(voteNumber);
//voteBoolean = true;
convVoted = true;
mRootRef.child("messages")
.child(mCurrentUserId)
.child(mChatUser)
.child(messageKey)
.child("voted").setValue(true);
mRootRef.child("chat")
.child(mCurrentUserId)
.child(mChatUser)
.child("voted").setValue(true);
mRootRef.child("user_account_settings")
.child(mChatUser)
.child("message_rating").setValue(voteNumberStr);
Log.d("RATING", " clicked : " + convVoted + " | Rating Number : " + voteNumberStr);
ratingLayout.setVisibility(View.GONE);
}
});
} else
{
ratingLayout.setVisibility(View.GONE);
}
}
}
#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) {
}
});
}
ANY HELP WOULD BE MUCH APPRECIATED.
if i understood your problem i do this way, i perform the rating only on message click, i think is the best way.
remove the bottom rate.
eg

Retrieve parent and children of firebase field

I am trying to get a parent value of a field in Firebase database along with its children.
for clarification:
I want to loop through the Snapshot to find the user who want to login by his or her ID, after that I want to get the parent of that id (i.e. is the user female or male) after that I want to get the canton and name.
so what I am doing is:
database=FirebaseDatabase.getInstance();
rootRef = database.getReference();
users = rootRef.child("Users");
and then
users.orderByChild("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getValue().equals(curUser.getUid())) {
String gender = child.getKey().toString();
currentPolUser.setuGender(gender);
currentPolUser.setuName(child.child("Name").getValue().toString());
Log.d("FirebaseUsers", "SUCCESSSSSS: "+currentPolUser.getuName() + " " + currentPolUser.getuGender());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The problem is child.getValue() returns an object that can't be compared to the User id string.
Try this:
ref.child("Users").orderByChild("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String gender = child.getKey();
for(DataSnapshot finalChild : child.getChildren()){
if (finalChild.getKey().equals(curUser.getUid())) {
HashMap<String, Object> map = (HashMap<String, Object>) finalChild.getValue();
String name = (String) map.get("name");
currentPolUser.setuGender(gender);
currentPolUser.setuName(name);
Log.d("FirebaseUsers", "SUCCESSSSSS: "+currentPolUser.getuName() + " " + currentPolUser.getuGender());
Log.e("TTT", name);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How can I give access to certain objects in Firebase database based on id

I have this data structure:
The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.
I have tried different methods for showing only the animals that have id that is stored in the current user node.
Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".
Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.
myAnimalRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG1, "failed to read value: " + databaseError.toException());
}
});
How can get my code to filter out every animal that does not have their ID in the user node?
The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.
To achieve this, you need to query your database twice. Please use the following code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = usersRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String aid = ds.getKey();
DatabaseReference animalRef = rootRef.child("animals").child(aid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dSnapshot) {
int age = dSnapshot.child("age").getValue(Integer.class);
String name = dSnapshot.child("name").getValue(String.class);
String url = dSnapshot.child("url").getValue(String.class);
Log.d("TAG", age + " / " + name + " / " + url);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
animalRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
In which uid is the id of the logged-in user and aid is the id of the animal. Your output will be:
11 / dog1 / http...
12 / dog2 / http...
Hope you find this helpfull.!
Get Object in Your Model Class and Store that Object in List for Further user.!
You can get specific object as well simple using
mdatabaseRef.child("animals").orderByChild().equalTo("value")
and also you can add check on key by orderByKey()
private FirebaseAuth mAuth;
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseRef;
mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();
ArrayList<User> allUserList = new ArrayList<>();
Array<Animal> allAnimalList=new ArrayList<>();
mdatabaseRef.child("animals").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
Animal animal = childSnapshot.getValue(Animal.class);
allAnimalList.add(animal );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mdatabaseRef.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
User user = childSnapshot.getValue(User .class);
allUserList.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I ended up taking Alex Mamo's answer and tweak with a litte bit.
This is the code i'am using:
uid = currentUser.getUid();
mRootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference myUserRef = mRootRef.child("users").child(uid);
Log.d(TAG1, uid);
myUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
String aid = ds.getKey();
DatabaseReference myAnimalRef = mRootRef.child("animals");
Query query = myAnimalRef.orderByKey().equalTo(aid);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds2 : dataSnapshot.getChildren()){
AnimalCard value = ds2.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The main difference is that i'am using a query to filter out every Animal that does not have the aID that the currentUser have.

I have the following firebase database and i am not able to retrieve the details like name,address,no

The following is an image from firebase database and i am not able to retrieve the data.
MainActivity.java
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
FirebaseData pg=dataSnapshot.getValue(FirebaseData.class);
Log.d(TAG, "Value is: " + value);
Toast.makeText(MainActivity.this,value,Toast.LENGTH_SHORT).show();
}
FirebaseData.java class
public class FirebaseData {
public String name;
public String address;
public String pgid;
public String contact_no;
public FirebaseData() {
// Needed for Firebase
}
public FirebaseData(String address, String name, String contact_no) {
this.name = name;
this.address = address;
this.contact_no=contact_no;
}
To get the address, contact_no and the name from HSRLayout node please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference HSRLayoutRef = rootRef.child("cities").child("Bangalore").child("localities").child("HSRLayout");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String address = dataSnapshot.child("1").child("address").getValue(String.class);
String contact_no = dataSnapshot.child("1").child("contact_no").getValue(String.class);
String name = dataSnapshot.child("1").child("name").getValue(String.class);
Log.d("TAG", address + " / " + contact_no + " / " + name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
HSRLayoutRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
das / 15615446484 / HSR
If you want to get the data from multiple childs, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference HSRLayoutRef = rootRef.child("cities").child("Bangalore").child("localities").child("HSRLayout");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String address = ds.child("address").getValue(String.class);
String contact_no = ds.child("contact_no").getValue(String.class);
String name = ds.child("name").getValue(String.class);
Log.d("TAG", address + " / " + contact_no + " / " + name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
HSRLayoutRef.addListenerForSingleValueEvent(eventListener);
In Database check Rules and set
{ "rules": {
".read": true,
".write": true}}

Find out when does Query finish loading the latest added item

I have a function which write data into database
private void startCommenting() {
final String comment_val = meditComment.getText().toString().trim();
meditComment.setText("");
if (!TextUtils.isEmpty(comment_val)) {
mProgress.show();
final DatabaseReference newPost = mComment.child(post_key).push();
final String commentkey = newPost.getKey();
mUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String,Object> checkoutData=new HashMap<>();
checkoutData.put("time",ServerValue.TIMESTAMP);
newPost.setValue(checkoutData);
newPost.child("comment").setValue(comment_val);
newPost.child("uid").setValue(dataSnapshot.child("id").getValue());
newPost.child("blogpost").setValue(dataSnapshot.child("blogkey").getValue());
newPost.child("userimage").setValue(dataSnapshot.child("image").getValue());
newPost.child("username").setValue(dataSnapshot.child("name").getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
After this function was called, a Query was made to get the data which contains the right post_key in the child ("blogpost").
mpostComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startCommenting();
mQueryCurrentComment = mComment.child(post_key).orderByChild("blogpost").equalTo(post_key);
mQueryCurrentComment.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String currentuserid;
String lastuserid = "";
String currentcommentuid;
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
currentuserid = dsp.child("uid").getValue().toString();
Log.d(TAG, "user newid: " + currentuserid);
Log.d(TAG, "user oldid: " + lastuserid);
if (currentuserid.equals(lastuserid)) {
} else {
final DatabaseReference newCommentLike = mComment.child(currentuserid).push();
Map<String, Object> checkTime = new HashMap<>();
checkTime.put("time", ServerValue.TIMESTAMP);
newCommentLike.setValue(checkTime);
newCommentLike.child("location").setValue(location_key);
newCommentLike.child("category").setValue(category_key);
newCommentLike.child("pressed").setValue("false");
newCommentLike.child("message").setValue(" has also commented your post. ");
newCommentLike.child("blogpost").setValue(post_key);
newCommentLike.child(post_key).setValue(true);
}
lastuserid = currentuserid;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
However, the Query was triggered twice, one before the new item was added, another after new item was added, which looks like below:
How can I only perform the actions inside Query after the newest item was added and not twice? Any help is appreciated!

Categories

Resources