how to get the name of parent A+ for this code? - java

I am unable to access this parent node using that code.
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this,"Login error", Toast.LENGTH_SHORT).show();
} else {
String user = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference();
final Query userQuery = mRef.orderByChild(user);
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
map.clear();
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren()) {
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key, value);
}
Intent intent = new Intent(LoginActivity.this, UserMapActivity.class);
intent.putExtra("bloodType",myParentNode);
startActivity(intent);
}
}
}
}
i want to get the highlighted parent from the underline child in every session

To get A+, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
Query query = usersRef.orderByChild(uid).equalTo(true);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Log.d(TAG, ds.getKey());
//Do what you need to do with your key
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The output in the logatcat will be:
A+

Related

On Android, how do you get the data from an email address in Firebase, then access the child, and from there you access the other Firebase data?

The following file explains better what I really mean. It's a screenshot of data sent from a dummy user in Firebase:
The code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
// ref.addValueEventListener(new ValueEventListener() {
ref.orderByChild("Email").equalTo("testing3#testing.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key = datas.getKey();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(key);
Toast.makeText(getApplicationContext(), key, Toast.LENGTH_LONG).show();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String name = dataSnapshot.child("Name").getValue().toString();
String state = dataSnapshot.child("State").getValue().toString();
String stateRegion = dataSnapshot.child("StateRegion").getValue().toString();
String telephone = String.valueOf(dataSnapshot.child("Telephone").getValue());
nameEditText.setText(name);
stateEditText.setText(state);
stateRegionEditText.setText(stateRegion);
telephoneEditText.setText(telephone);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
Please, can some person help?
More information about data stored in the Firebase:
Because I cannot see a more detailed database schema of yours, I assume that all those user objects are direct children under your Users node, and also assuming that you want to find the user that has the Email set to testing3#tesing.com, to display his particular details, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("Users");
Query queryUsersByEmail = usersRef.orderByChild("Email").equalTo("testing3#testing.com");
queryUsersByEmail.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String name = ds.child("Name").getValue(String.class);
Log.d("TAG", name);
String state = ds.child("State").getValue(String.class);
Log.d("TAG", state);
String stateRegion = ds.child("State Region").getValue(String.class);
Log.d("TAG", stateRegion);
String telephone = ds.child("Telephone").getValue(String.class);
Log.d("TAG", telephone);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
Paul SMith
Rio de Janeiro
Rio de Janeiro
(00)00000-0000

Firebase Realtime Database not displayed when retriving to textviews in Android

onCreate() method is never executed. I just want to take the below data to 4 TextViews. "Detail" is the model class.
No errors are shown when running the app.
view_temp is an activity.
this is firebase realtime db
this is the java class
`public class view_temp extends AppCompatActivity {
private view_temp viewTemp;
public Detail detail;
private TextView roomtemp, roomhuminity, bodypulse, bodytemp;
private DatabaseReference mDatabase;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_temp);
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
roomtemp = (TextView) findViewById(R.id.txt_room_temp);
roomhuminity = (TextView) findViewById(R.id.txt_huminity_temp);
bodypulse = (TextView) findViewById(R.id.txt_body_pulse);
bodytemp = (TextView) findViewById(R.id.txt_body_temp);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
detail = postSnapshot.getValue(Detail.class);
String rtemp = detail.getRoomtemp();
String rhumidity = detail.getRoomhumidity();
String bpulse = detail.getBodypulse();
String btemp = detail.getBodytemp();
roomtemp.setText(rtemp);
roomhuminity.setText(rhumidity);
bodypulse.setText(bpulse);
bodytemp.setText(btemp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
}
}`
There is no need to add the name of the project in the getReference() method. To get those names and the corresponding values correctly, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.getKey();
double value = ds.getValue(Double.class);
Log.d("TAG", name "/" + value);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
RoomHumi/86.0
RoomTemp/30.8
bodyPulse/126.0
bodyTemp/29.0
If the keys are always fixed, then simply use:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double roomHumi = dataSnapshot.child("RoomHumi").getValue(Double.class);
Log.d("TAG", "RoomHumi" "/" + valueroomHumi);
double roomTemp = dataSnapshot.child("RoomTemp").getValue(Double.class);
Log.d("TAG", "RoomTemp" "/" + roomTemp);
double bodyPulse = dataSnapshot.child("bodyPulse").getValue(Double.class);
Log.d("TAG", "bodyPulse" "/" + bodyPulse);
double bodyTemp = dataSnapshot.child("bodyTemp").getValue(Double.class);
Log.d("TAG", "bodyTemp" "/" + bodyTemp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
And you'll have the same result in the logcat.
Just change your line
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
to
mDatabase = FirebaseDatabase.getInstance().getReference();
Note: You do not need to put your database name into reference.

How to retrieve the child data from Firebase?

My database looks as follows, in here I want to retrieve the data inside the mylocation child (see the attached image here). But it is not working.
How to solve that?
My current code looks as this,
private void loadAddress() {
DatabaseReference ref= FirebaseDatabase.getInstance().getReference("Users");
ref.orderByChild("uid").equalTo(firebaseAuth.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
String name=""+ds.child("name").getValue();
String lat=""+ds.child("name2").getValue();
addresstv.setText(name);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
To get the data under mylocation, you use an explicit call to that child, like in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("mylocation").child("name2").getValue(String.class);
double latitude = dataSnapshot.child("mylocation").child("latitude").getValue(Double.class);
double longitude = dataSnapshot.child("mylocation").child("longitude").getValue(Double.class);
Log.d("TAG", name + "/" + latitude + "/" + longitude);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
5555/79.8571577/6.9448882

How to add data in pre-existing document by searching for specific node in Firebase? (Android)

There is one document which is student profile with student data like course, username, status etc.
I want to add another node named uid in pre-existing document by searching for emailid
For example, In document containing emailid: "abc#gmail.com" I want to add uid:"111032" in that document containing emailid.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference studentRef = rootRef.child("STUDENT");
lg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = un.getText().toString().trim();
String password= pw.getText().toString().trim();
lg.setText("Logging in...");
firebaseAuth.signInWithEmailAndPassword(username, password)
.addOnCompleteListener(Welcome.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
firebaseAuth = FirebaseAuth.getInstance();
final String current_user_id = firebaseAuth.getCurrentUser().getUid();
//Save UID to database
Query emailAddressQuery = studentRef.orderByChild("emailid").equalTo(username).limitToFirst(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> uidUpdate = new HashMap<String, Object>();
uidUpdate.put("uid", current_user_id);
ds.getRef().updateChildren(uidUpdate);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
emailAddressQuery.addListenerForSingleValueEvent(valueEventListener);
Intent i=new Intent(Welcome.this,Home.class);
// i.putExtra("useremail", username);
startActivity(i);
lg.setText("Log In");
} else {
Toast.makeText(getApplicationContext(), "Log In Failed", Toast.LENGTH_SHORT).show();
lg.setText("Log in");
}
// ...
}
});
}
});
The above code is actually is in sign in button which sign in the user get the uid and save it to that specific profile's info.this is the image with more detailed information.
As shown in this image, I want to search by emailid (Shown in yellow) and add node called uid in that specific document.
OLD CODE :
username = un.getText().toString().trim();
firebaseAuth = FirebaseAuth.getInstance();
String current_user_id = firebaseAuth.getCurrentUser().getUid();
ref= FirebaseDatabase.getInstance().getReference().child("STUDENT").child(username);
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("uid", current_user_id);
ref.updateChildren(updates);
This code works but we have to pass the name of document while I want to pass data by child node in the document.
To solve this problem, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studentRef = rootRef.child("STUDENT");
Query emailAddressQuery = studentRef.orderByChild("emailid").equalTo("abc#gmail.com").limitToFirst(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> uidUpdate = new HashMap<String, Object>();
uidUpdate.put("uid", uid);
ds.getRef().updateChildren(uidUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TAG", "task is successful!");
} else {
Log.d("TAG", task.getException().getMessage());
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
emailAddressQuery.addListenerForSingleValueEvent(valueEventListener);
The result of this operation will be the update of the uid in the user object.

how get value from Firebase

I am new in android and I want to get userIDS from Firebase Database, I've tried by using this but it returns null.
By using this code
Value of Constants.ARG_CHAT_GROUP_ROOMS=Groups and Constants.NEW_NODE=newGroup
private void getMYuid() {
String senderUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();
mTest.child(Constants.ARG_CHAT_GROUP_ROOMS).child(Constants.NEW_NODE)
.child(senderUid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
Toast.makeText(ActivityChatView.this, "not exist", Toast.LENGTH_SHORT).show();
Log.e("151","ACV"+dataSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("139","ACV"+senderUid);
}
Database Structure is this
if you want the first one under 15052169227329_myGroupName_Hell By Anne: Your problem is that you forgot the node before "Constants.NEW_NODE"
private void getMYuid() {
String senderUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();
mTest.child(Constants.ARG_CHAT_GROUP_ROOMS).child("15052169227329_myGroupName_Hell By Anne").child(Constants.NEW_NODE)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
Toast.makeText(ActivityChatView.this, "not exist", Toast.LENGTH_SHORT).show();
Log.e("151","ACV"+dataSnapshot);
}
// You can cast this object later but it seems that that is a string and not an array
Object yourRequiredObject = dataSnapshot.child("usersIDS").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("139","ACV"+senderUid);
}
As i see, it's not an array it's a String. To get the userIDS, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child(Constants.ARG_CHAT_GROUP_ROOMS).child(senderUid).child(Constants.NEW_NODE);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String usersIDS = dataSnapshot.child("usersIDS").getValue(String.class);
Log.d("TAG", usersIDS);
//Here you can split the usersIDS String by , (comma)
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
In which senderUid is the missing child. This child can have the value like 1505217176288_myGroupName_1 or other coresponding group names.

Categories

Resources