Retrieve User Data Firebase on Android - android

Is there a way to retrieve data from a specific user who is authenticated via firebase through ID?
For example to retrieve information like name, photo etc.
Thanks in advance.

This is more of a port of the iOS answer i have given here
Firebase provides authentication for users using the FIRAuth Clases/API
However they can't be edited with custom fields like the Firebase Database.
To allow custom fields for user, you need to duplicate users in the Database with the same unique uid you receive in the auth of the user. Something like this
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
String name = user.displayName;
String email = user.email;
String photoUrl = user.photoURL;
String uid = user.uid;
FirebaseDatabase database = FirebaseDatabase.getInstance();
String key = database.getReference("users").push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put( "uid", uid);
childUpdates.put( "name", name);
// other properties here
database.getReference("users").updateChildren(childUpdates, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
}
}
});
}
We push it at the users end point in our db and with the uid key by the following line /users/\(key).
Now you can retrieve users detail from your database by querying anywhere in your code.

Related

Searching in firebase database returns null value

I am working on an app where I have to fetch the status of a message from the database, but whenever I try to fetch and display data, the app crashes back to home screen.
user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
database = FirebaseDatabase.getInstance();
String msg = textView.getText().toString().trim();
DatabaseReference myRef = database.getReference();
myRef.child("Users").child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot db : dataSnapshot.getChildren()) {
if(db.getKey().equals(textView.getText().toString().trim())) {
count=1;
String key = db.getKey();
String key2= db.child(key).child("status").getValue(String.class);
Toast.makeText(CheckMsg.this,key2, Toast.LENGTH_SHORT).show();
}
}
}
Database Format
You should modify the key2 statement to
String key2= db.child("status").getValue(String.class);
OR
String key2= dataSnapshot.child(key).child("status").getValue(String.class);
db is already a child as it is an element of getChildren()(like abc and all) and you are trying to find a child of abc with the name abc.
I am assuming the crash is because key2 is null:
In the for loop:
Change this:
String key2= db.child(key).child("status").getValue(String.class);
to this:
String key2= db.child("status").getValue(String.class);
After Reading your Details Provided.
Issues-
1) Update the key as
String key2=db.child("status").getValue(String.class);
Try this. If this doesn't Work, comment below...

Get Value from Firebase Database

I need to get the string value from the node passcode in my Firebase database to compare with a user input, but unfortunately I am not able to get the value. This is the link to my firebase database in the below image.
This is my codes below:
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("pin_code");
mDatabase.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
if (rface.equals("") || rface.equals(null)){
// Creating new user node, which returns the unique key value
// new user node would be /users/$userid/
String userId = mDatabase.push().getKey();
// creating user object
Pin pin = new Pin(authUserId, userPassword);
mDatabase.child(userId).setValue(pin);
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
Toast.makeText(PinActivity.this,"Invalid PIN code", Toast.LENGTH_SHORT).show();
return;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is the json code
{
"pin_code" : {
"id" : "TQYTo1NHNnhPJnOxhe1Vok3U6ic2",
"pincode" : "12345"
}
}
This FirebaseDatabase.getInstance().getReference("pin_code") does not refer to the node you're looking for. Most likely you know the id property, in which case you can get the node with:
DatabaseReference collection = FirebaseDatabase.getInstance().getReference("p...");
Query query = collection.orderByChild("id").equalTo("TQT...ic2");
query.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String rface = (String) child.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
The changes I made:
On the first line we get the collection: the node under which you want to run a query. You struck out the name of that node in the screenshot, but it's the second line you marked.
In the second line we create a query on the id property of each child node under the collection.
In the onDataChange we added a loop. This is needed because a query against the Firebase Database will potentially have multiple results. So the dataSnapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. We loop over dataSnapshot.getChildren() to handle those multiple results.
If there can ever only be one node with the same id, you should consider changing your data structure to use the id as the key of the node. So:
pin_codes
uid1: "pincode1"
uid2: "pincode2"
Your code then becomes significantly simpler, because you don't need to query for the user anymore. You can just directly read from the path:
DatabaseReference user = FirebaseDatabase.getInstance().getReference("pin_codes").child("TQT...ic2");
user.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.getValue();
if (rface.equals(userPassword) && !rface.equals("")){
Try change this:
String rface = (String) dataSnapshot.child("pincode").getValue();
To this:
String rface = (String) dataSnapshot.child("pincode").getValue(String.class);
Use the following::
Object some = dataSnapshot.getValue();
String value = some.toString();

How to filter Contact list with Firebase DB with phonenumbers

I have a Firebase DB which is used as a backend for the Android App I'm developing. I app users have their mobile numbers considered as their Id which is stored in Firebase DB . While searching users in app ( phone contacts) it should show only the contacts which uses this app ( ie phone numbers which is already registered/available in Firebase DB ).
Tried searching and found something similar [Android application with phone book synchronization? but not useful.
Appreciate help
Store all your contacts in a HashMap using phone no. as a Key and name as a Value. Here I'm creating as
HashMap<String, String> phoneContacts = new HashMap<>();
and now call this method
void getFirebaseContacts(){
databaseReference.child("ProfileData").addListenerForSingleValueEvent(new ValueEventListener() { //all users profile data
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map value = (Map) dataSnapshot.getValue();
if (value != null) {
Iterator myVeryOwnIterator = value.keySet().iterator();
while (myVeryOwnIterator.hasNext()) {
String Mobile = (String) myVeryOwnIterator.next();
if (Mobile != null && phoneContacts.containsKey(Mobile)) {
//Mobile and it's associated details will be stored in local database and displayed to user..
Map userData = (Map) value.get(Mobile);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

How to add new data in firebase android

This is my logic for adding new person in firebase realtime databse. But instead of making a new entry it is just updating the old data with new one.
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
/*
new Firebase(Config.FIREBASE_URL)
.push()
.child("title")
.setValue(text.getText().toString());
*/
Firebase ref = new Firebase(Config.FIREBASE_URL);
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
//Creating Person object
Person person = new Person();
//Adding values
person.setName(name);
person.setAddress(address);
ref.child("Person").setValue(person);
}
});
new Firebase(Config.FIREBASE_URL).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
//Adding it to a string
String string = "Name: "+person.getName()+"\nAddress: "+person.getAddress()+"\n\n";
//Displaying it on textview
textViewPersons.setText(string);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
What is wrong here? Can anyone help me on this?
You are using always the same ref
Person person = new Person();
//Adding values
person.setName(name);
person.setAddress(address);
ref.child("Person").setValue(person);
Check the doc:
Using setValue() in this way overwrites data at the specified location, including any child nodes.
In your case you are overriding the same data for this reason.
You should use the push() method to generate a unique ID every time a new child is added to the specified Firebase reference.
Person person = new Person();
//Adding values
person.setName(name);
person.setAddress(address);
DatabaseReference newRef = ref.child("Person").push();
newRef.setValue(person);
You can add a new Child to your data, such as:
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userId = user.getUid();
Firebase rootRef = new Firebase(Config.USER_URL);
Firebase userRef = rootRef.child("Users");
Person newUser = new Person();
newUser.setFirstName(firstName);
newUser.setLastName(lastName);
userRef.child(userId).setValue(newUser);
The userId varies when the logging user is different, therefore, you will always go to a new data list for a new logged-in-user in the userId under Users.
every time when you optate to insert data to database call the follwing method.
You can integrate as many attributes you optate.It will engender a unique key everytime and insert records.
public void insert2database(double latitude,double longitude,String name) {
HashMap<String,String> student=new HashMap<>();
student.put("Name",name);
student.put("Lat", String.valueOf(latitude));
student.put("Long", String.valueOf(longitude));
student.put("Phone", String.valueOf("78787500000"));
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tasksRef = rootRef.child("USERS").push();
tasksRef.setValue(student);
}
It will be in the database hierarchy like this
-database-4df17-default-rtdb
-USERS
-MUqgUu8zUpYcIaUVSsj
-Lat: "25.9405145"
-Long: "79.9100086"
-Name:"Dilroop"
-Phone: "78787500000"
-MUqoL2AUQFjH2ggKWev
-Lat: "32.9405145"
-Long: "73.9178186"
-Name: "Sanghavi"
-Phone: "78787500000"
-MUsfc-H-7KdQhrkHb_F
-Lat: "52.9405145"
-Long: "79.9175856"
-Name: "MDNSRF"
-Phone: "78787500000"
You are referencing to the "Person" child and setting it's value (setValue()) every time you click buttonSave, which only edits that one child. Try to use push() instead.

Userlist from facebook users for variables on android firebase?

Is this the best way to create a user list from facebook users to hold variables on firebase? I want each user to have a few int variables, tokens, spins, and biggestWin. but the createUser method doesn't seem to add any data to the firebase, and doesnt seem to work well with the facebook code. It always toasts "not created"
public void createUser(String mEmail, String mProvide){
Firebase rootRef = new Firebase("https://luckycashslots.firebaseio.com/data/");
Firebase userRef = rootRef.child("users");
userRef.setValue(mAuthData.getUid());
Firebase newRef = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + mAuthData.getUid() + "/");
Firebase tokRef = newRef.child("tokens");
Firebase spinRef = newRef.child("spins");
newRef.setValue(mAuthData.getProvider());
Tokens token = new Tokens("100");
Spins spin = new Spins(55);
tokRef.setValue(token);
//spinRef.setValue(spin);
rootRef.createUser(mEmail, mProvide , new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result){
Toast.makeText(getApplicationContext(), "Yes-UID=" + result.get("Uid") , Toast.LENGTH_LONG).show();
}
#Override
public void onError(FirebaseError firebaseError){
Toast.makeText(getApplicationContext(), "Not Created", Toast.LENGTH_LONG).show();
}
});
}
Creating an email+password user or authenticating a user with Facebook does indeed not store any data about that user in the Firebase Database.
If you want to store user data in the database, see the section on storing user data in the Firebase documentation.

Categories

Resources