Okay so I am trying to pull from my database the email of a single user under the userID, and it retrieves null.
The userUID is authUID.
My Database structure
When I change the line to :
String value = dataSnapshot.child("email").getKey();
it retrieves the right key so I am standing on the right position of the database as far as I understand.
myDatabaseRef.child(userUID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try{
String value = dataSnapshot.child("email").getValue(String.class);
//String value = dataSnapshot.child("email").getKey(); gets email
Log.d("TAG", "onDataChange: " + value);
}
catch (Exception ex){
Log.d("PROBLEM",ex.toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
The error that I get:
2019-07-30 10:42:29.566 14673-14673/com.example.h210.housecommitteemanage D/TAG: onDataChange: null
Try this, below code will fetch emails of all the users :
FirebaseDatabase.getInstance().getReference("DataUsers").child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try{
Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
for (DataSnapshot aSnapshotIterable : snapshotIterable) {
String value = aSnapshotIterable.child("email").getValue(String.class);
Log.e(Constants.TAG, "Users email : " + value);
}
}catch (Exception ex){
Log.e("PROBLEM",ex.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
I have created an Android App By which user can register and login.When a user registration is successful a Name and value will created in my database for that User. Now I want to retrieve The Data For every User separately.
To retrieve the current user's data from this structure, you need two things:
to know the uid of the current user
to then read the data from the database
In code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance.getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long points = dataSnapshot.child("Points").getValue(Long.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Try this:
mDatabase.child("ezzeearn").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, String> map = (Map<String, String>) dataSnapshot.getValue();
String point = map.get("Points");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
for using iterator you can get the data for specific user
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
Try to use below method :
public void getAllUsersFromFirebase() {
DatabaseReference UserRef = FirebaseDatabase.getInstance().getReference().child("ezzeearn");
UserRef.keepSynced(true);
UserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
String resultString = (String)dataSnapshotChild.getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// for handling database error
}
});
}
I am using this method to retrieve data on Android, and it always returns null. Inside the ondatachange the listFinalBus is not null, but when the return comes, I get a null value.
Here is my code:
public List<Bus> findAllBus() {
// Read from the database
myRef.child("Bus").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {
Bus bus = userDataSnapshot.getValue(Bus.class);
Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());
listFinalBus.add(bus);
Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.d(TAG, "onDataChange: list firas return" + listFinalBus.size());
//return is null
return listFinalBus;
}
Your .addValueEventListener(listener) works async. So you will return your field fisrt which is null and after the call is done, your listener get called. But your field is already returned.
So to fix this, whether you write your own listener like:
interface MyCallback{
void onSuccess(List<Bus> bus)
}
and your code could be like:
public void findAllBus(MyCallback callback) {
// Read from the database
myRef.child("Bus").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {
Bus bus = userDataSnapshot.getValue(Bus.class);
Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());
listFinalBus.add(bus);
Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
}
callback.onSuccess(List<Bus> bus);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
So you can get your List no matter where you like.And just implements the Callback and pass it to your repository.
Or if you familiar with RxJava. You can pass an Observable which gonna like
public Observable<Bus> findAllBus(){
return Observable.create(new ObservableOnSubscribe<Bus>() {
#Override
public void subscribe(ObservableEmitter<Bus> e) throws Exception {
myRef.child("Bus").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {
Bus bus = userDataSnapshot.getValue(Bus.class);
Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());
e.onNext(bus);
Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
}
e.onComplete();
}
#Override
public void onCancelled(DatabaseError databaseError) {
e.onError(error);
}
}
});
}
My Firebase Database is look like as bellow:
I want to show an error message when email val is not available in firebase database.
And my code is
mRef.orderByChild("email").equalTo(val).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
textView.setText("Welcome " + user.name );
System.out.println(user.name + "\n" + user.email + "\n" + user.tell);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
textView.setText("Welcome " + user.name );
System.out.println(user.name + "\n" + user.email + "\n" + user.tell);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
A ChildEventListener can only detect the presence of a certain child node or when a child node is changed/removed. It cannot detect the absence of a child. To detect that there is no value, you need a ValueEventListener:
mRef.orderByChild("email").equalTo(val).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() == 0) {
System.out.println("No user with email "+val);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
throw firebaseError.toException(); // don't ignore onCancelled!
}
});
mQuery = databaseReference.limitToLast(1).orderByChild("email").equalTo(category);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, "onDataChange: "+dataSnapshot.toString());
GenericTypeIndicator<Map<String,UserModel>> t=new GenericTypeIndicator<Map<String,UserModel>>(){};
try{
Map<String,UserModel> userList=dataSnapshot.getValue(t);
}catch(Exception exception){
//Error UserInfo not present in firebase
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Error wile accessing database
}
});
How can I get that value while I know nothing about the push key?
+users
+9JZTuGUzc8bx7FLrwResWmp8L583
+anon:
+email:
+fid: <- i want to get this id without knowing push key (9JZTuGUzc8bx7FLrwResWmp8L583 )
+username:
Currently, I am trying with a null response:
FirebaseDatabase.getInstance().getReference().child("users").orderByChild("anon").equalTo(getIntent().getStringExtra(EXTRA_POST_USERNAME))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
if(dataSnapshot.exists()){
User user = dataSnapshot.getValue(User.class);
fidanon = user.fid;}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
final Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("anon").equalTo(getIntent().getStringExtra(EXTRA_POST_USERNAME));
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
final String fid = dataSnapshot.child("fid").getValue().toString();
Toast.makeText(getActivity(), fid, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Use this,will solve your problem.
I want to delete the data from Firebase before unauthorizing. The problem is that mFirebaseRef.unauth() works only if query is not empty. But I need it to work even if query is empty.
final Firebase pushNotificationRef = new Firebase(Constant.FIREBASE_URL_PUSHNOTIFICATIONS);
final Query queryRef = pushNotificationRef.orderByChild("deviceToken").equalTo(token);
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
Log.e("MyTag", dataSnapshot.getKey());
pushNotificationRef.child(dataSnapshot.getKey()).removeValue();
}
mFirebaseRef.unauth();
}
use this...
if (dataSnapshot.exists())
// user found
else
// user not found
demo example
Query query = dbstud.child("users").orderByChild("name").equalTo("XYZ");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Toast.makeText(getApplicationContext(), "id = " + snapshot.getKey(), Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(getApplicationContext(), "User Not found ", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});