I have Firebase data organized in the below format. When I'm trying to fetch data using the below code, it just never enters onDataChange, even though I have data in Firebase at that path.
Please ignore the list part, in the log I am able to see right path of Firebase, i.e.:
conversation/8masp4NLZrYL4HpziIU7uUZjRd73/8masp4NLZrYL4HpziIU7uUZjRd73
DatabaseReference databaseReferenceAdapter = FirebaseDatabase.getInstance().getReference();
DatabaseReference conversation2Ref = databaseReferenceAdapter.child("conversation").child(currentUser).child(userListRef.get(position));
Log.d(TAG,"Data binding++++" + conversation2Ref.getRef().toString());
conversation2Ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG,"Data changed");
Conversation conversationInfo = dataSnapshot.getValue(Conversation.class);
mConversationList.add(position,conversationInfo);
Log.d(TAG,"Data changed");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG,"Data error");
}
});
To get those values, instead of using Conversation.cass, you can use the String.class like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("conversation").child("8masp4NLZrYL4HpziIU7uUZjRd73").child("8masp4NLZrYL4HpziIU7uUZjRd73");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message").getValue(String.class);
long notificationCount = dataSnapshot.child("notificationCount").getValue(Long.class);
long profileId = dataSnapshot.child("profileId").getValue(String.class);
String profileName = dataSnapshot.child("profileName").getValue(String.class);
long time = dataSnapshot.child("time").getValue(String.class);
String type = dataSnapshot.child("type").getValue(String.class);
Log.d("TAG", message);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
child(userListRef.get(position));
The above is wrong, according to the database you have random push() key under the userid. So, you have to retrieve the push key and add it to the child.
to retrieve the key:
String key=conversation2Ref.push().getKey()
then in query do:
child(key)
Related
I'am trying to store the query result in a String variable, but the result I'm getting is the string conversion of the query object.
tableDatabaseReference = FirebaseDatabase.getInstance().getReference("tables");
tableNameQuery = tableDatabaseReference.child("tableName").orderByChild(tableID).equalTo("123");
String tableName = tableNameQuery.toString();
Any suggestions?
EDIT:
Database structure:
Tables:
-------TableID:
--------------TableName:
--------------TableID:
To retrieve data from Firebase Realtime database , you have to add a valueEventListener to your database reference variable like this
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dataRef = database.getReference("YOUR_DATABASE_REF");
dataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// here you can get your data from this snapshot object
String data = dataSnapshot.getValue("CHILD_NAME_HERE").toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To get data once you can use singleValueEventListener
dataRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// here you can get your data from this snapshot object
String data = dataSnapshot.getValue("CHILD_NAME_HERE").toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Firebase operation is asynchronous, so you have to wait to complete the operation to get result. To access data outside of onDataChange you can use LiveData and observe it outside. When you get data inside onDataChange then notify LiveData by posting value. Check below:
private MutableLiveData<String> tableName = new MutableLiveData<>();
DatabaseReference tableDatabaseReference = FirebaseDatabase.getInstance().getReference("tables");
tableDatabaseReference
.child(tableID)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String data = dataSnapshot.child("tableName").getValue(String.class);
//Now post that value to LiveData
tableName.postValue(data);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Observe data here
tableName.observe(this, name -> {
// use name here
});
So, this is how my Firebase database looks like:
I am currently trying to read the value of UserInformation/Shift/zTZ0U1K8aGb6bP94YTUA50ZwIlx2/Shift in order to set the value of ShiftInformation/1514855312873/Team/zTZ0U1K8aGb6bP94YTUA50ZwIlx2 to null.
When I press a button "buttonMyShift", I need to read the value "1514855312873" because it was generated from System.getCurrentTimeMillis().
I have been trying to accomplish that by changing the value inside a "onDataChange" method, ut the app either crashes or deletes only UserInformation/Shift.
Here is my activity code:
if (view == buttonMyShift){
final FirebaseUser user = mAuth.getCurrentUser();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("UserInformation/Shift/").child(user.getUid()).child("Shift");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//Read the value of UserInformation/Shift/user.getUid()/Shift
SHIFT uShift = dataSnapshot.getValue(SHIFT.class);
//Setting the value of userShift to UserInformation/Shift/user.getUid()/Shift
String userShift = uShift.toString().trim();
//Setting the value of ShiftInformation/userShift/Team/user.getUid() to null
mReference = database.getReference("ShiftInformation").child(userShift).child("Team").child(user.getUid());
mReference.setValue(null);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
//set UserInformation/Shift/user.getUid to null
SHIFT nshift = new SHIFT(null);
databaseReference.setValue(nshift);
Toast.makeText(MainMenuActivity.this,"Adeus!",Toast.LENGTH_SHORT).show();
//leave the activity
Intent intent = new Intent(MainMenuActivity.this,BadgeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(intent);
}
Thanks For The Help!
To get the value of your Shift field, which is 1514855312873, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference shiftRef = rootRef.child("UserInformation").child("Shift").child(user.getUid()).child("Shift");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String shift = dataSnapshot.getValue(String.class);
Log.d("TAG", shift);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
shiftRef.addListenerForSingleValueEvent(eventListener);
The output will be:
1514855312873
Your DatabaseReference was correct but the problem in your code is that you are using getChildren() method when there is no need.
I am trying to get values from Firebase Database and set them to text view. My database has multiple child like in image. I want to get the Phone and Address values from it. How can I get them? I am new to Android and I have tried multiple answers here, but failed. Can anyone help me with this?
To get that data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String address = ds.child("Address").getValue(String.class);
String phone = ds.child("Phone").getValue(String.class);
Log.d("TAG", address + " / " + phone);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
And this is the code to get the address from a single user:
String uid = firebaseAuth.getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String address = dataSnapshot.child("Address").getValue(String.class);
Log.d("TAG", address);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)
By using this it fetch all the data from firebase:
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) {
}
});
I have tried all that .child .orderby and .equalTo but did'nt work
My Structure is Like:
My FireBase Structure
You also need a reference to the data, which isn't included in your code block. So something along the lines of (this should be before this):
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notepad-secure/notepad");
Firstly add a user_id key in your child data, it will look like below :
id:"",
note:"",
title:"",
user:""
user_id:"{id from which user have you uploaded data}"
And than you can call below function with specific user data like
below Note : "user_id" = id from which user have you uploaded data
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("notepad").orderByChild("id").equalTo("user_id");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "notepad" node with all children with id
for (DataSnapshot notepad: dataSnapshot.getChildren()) {
// do something with the individual "notepad_data"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To Fetch Particular values from the firebase,try this code
FirebaseDatabase database;
database.getReference().child("notepad-secure").orderByChild("id").equalTo(user).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
User userdet =childSnapshot.getValue(yourclass.class);
String note=userdet.note;
//Here you will get the string values what you want to fetch
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
First U have to differentiate.U have to implement Firebase Authentication the u can get Firebase UID of every USER.
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
Then store seperatly in new node.
i.e Take Firebase Database Instance and
databaserefernace.child("Data").Child("userID);
When your add a user data to Firebase database, you can add it using the specific uid provided by the FirebaseAuth object like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Assuming you that your database strucure look like this: Firebase root -> notepad-secure -> notepad, to retrieve data, you can use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = dataSnapshot.child("id").getValue(String.class);
String note = dataSnapshot.child("note").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String user = dataSnapshot.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + user);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
I am trying to display all child "name" located in my database tree. My Database tree I used the Map to do so:
GenericTypeIndicator<Map<String, Object>> m = new GenericTypeIndicator<Map<String, Object>>() {};
Map<String, Object> map = snapshot.getValue(m);
String username = (String) map.get("name");
displayName.setText(username);// Display the name
I am displaying all the data into a recyclerView. But for some reasons instead of getting all names(Eva, smith, princess), I am only one which is the lastest one created "princess" being displayed 3 times in my recyclerView layout(princess, princess, princess). Anyone has any idea what I am doing wrong?
Assuming that you have a node named users in which you have all those uid's, to get all those name, please use the code below. Is the easiest way to achieve this.
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userId = (String) dataSnapshot.getKey();
DatabaseReference userIdRef = FirebaseDatabase.getInstance().getReference().child("users").child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("name").getValue();
Log.d("TAG", name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userIdRef.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
Hope it helps.