To get data of authenticated user failure - java

public void loadUserInformation() {
final String uid = mAuth.getCurrentUser().getPhoneNumber();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Users");
// DatabaseReference uidRef = rootRef.child("ref").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot: dataSnapshot.getChildren()){
String name=postSnapshot.child("Name").getValue().toString();
// String email=postSnapshot.child("Email").getValue().toString();
Name.setText(name);
// Email.setText(email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(),"Error Loading UserDetails",Toast.LENGTH_LONG).show();
}
};
rootRef.addListenerForSingleValueEvent(eventListener);
}
I know why I'm not getting the expected results, its because there's one more child after users. I'm not sure on how to access it, child(uid) gave me a NullPointerException. The present code gives me name of some random user. I want it to return name of the authenticated user i.e. myself
Database - http://ibb.co/iRnF77

Change the phone number to the userid:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
So you will have this database:
Users
userid
Name: namehere
Phone_Number: numberhere
//etc
then you can simply retrieve the data of the current user:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name=dataSnapshot.child("Name").getValue().toString();
Name.setText(name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
You don't need the phone number to be the parent node since you already have it as an attribute Phone_Number: number_here, no need to write it twice.
Also getPhoneNumber() can be used if you did phone authentication:
https://firebase.google.com/docs/auth/android/phone-auth

Related

Edit specific values in Firebase database using Android Studio

I want to create an "edit user profile" page on Android Studio. The user(which is logged in obviously) can go in and edit user info such as weight and age. Here is how my firebase database is set up:
The database
In this case, a user who is logged in as "Raxor2k", wants to change he`s info such as Age and Weight.
I have made a function that queries the database, and it manages to reach the "AdditionalUserInfo" table which is good. But the next task is to reach those specific values that belong to the logged-in user.
here is the code:
public class UserSettingsActivity extends AppCompatActivity {
private Button mEditInfoButton;
private TextView usernameField;
private EditText ageField, weightField;
private DatabaseReference dbUsernames;
DatabaseReference the_additional_userInfo_table = FirebaseDatabase.getInstance().getReference("AdditionalUserInfo");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_settings);
ageField = (EditText) findViewById(R.id.ageID);
weightField = (EditText) findViewById(R.id.weightID);
mEditInfoButton = (Button) findViewById(R.id.editButton);
usernameField = (TextView) findViewById(R.id.usernameTextViewID);
mEditInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QueryUserInfo();
}
});
}
public void QueryUserInfo(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference the_additional_userInfo_table = database.getReference("AdditionalUserInfo");
//Query query =the_additional_userInfo_table.child("username");
the_additional_userInfo_table.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(UserSettingsActivity.this, "User exists!", Toast.LENGTH_SHORT).show();
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
if(!dataSnapshot.exists()){
Toast.makeText(UserSettingsActivity.this, "nooooo user!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
To get the data under AdditionalUserInfo that corresponds to a specific user, you need to use a query that looks like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference additionalUserInfoRef = rootRef.child("AdditionalUserInfo");
Query userQuery = additionalUserInfoRef.orderByChild("username").equalTo("Raxor2k");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = new HashMap<>();
map.put("user-age", "30");
map.put("user-weight", "30");
ds.getRef().updateChildren(map);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
userQuery.addListenerForSingleValueEvent(valueEventListener);
The result in your database will be the change of both properties from 25 to 30. Since you didn't add the database as a text, file I have used in the query he user name but a more elegant way of querying the database would be to use the uid.
Query userQuery = additionalUserInfoRef.orderByChild("user-id").equalTo("IXL ... Eoj");

Firebase database query to fetch particular data

My Database struckture
This is my database in Firebase and I'm developing an Android application. Now I want to retrieve all the data from "Generated" node where my current user's userid matches the "userId" in data.
I want to know the query in Firebase to fetch that particular data.
Firebase Query firebase query
Read the Firebase Realtime Database Documentation to get some idea firebase realtime database
To Get Current User Uid
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = user.getUid(); // user.getUid() will return null if you are not log in
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query query = db.child("Leads").child("Generated").orderByChild("userid").equalTo(current_uid);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// do something
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or Try This One
db.child("Leads").child("Generated").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot ds: dataSnapshot.getChildren())
{
SomeClass someClass = ds.getValue(SomeClass.class);
if(someClass.getUid().equals("uid")){
// i don't if it is the best practice or not but you can do with this as well
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To access every item from that reference you will need something like this:
mDatabase.child("Leads").child("Generated").child(uid).addValueEventListener(new ValueEventListener() {
final List<String> lstItems= new ArrayList<String>();
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = (String) ds.getKey();
String values = (String) ds.getValue();
Log.e("Values",""+values );
lstItems.add(values );
}
PS: you can remove .child(uid) in your reference if you want to get all the children of Generated (it's going to be all the uids).

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.

Firebase data retrieve with singlechildevent

Here is my firebase data structure . The child "Tags" is a child of root.
final Query searchquery = mDatabase.child("Tags").orderByKey().limitToFirst(10).startAt(s.toString().toLowerCase()).endAt(s.toString().toLowerCase() + "\uf8ff");
searchquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String u = dataSnapshot.child("article_name").getValue(String.class);
Toast.makeText(MainActivity.this,":/ : "+u.toString(),Toast.LENGTH_LONG).show();
}catch (Exception tg){
Toast.makeText(MainActivity.this,tg.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get the value of child "article_name" . I used the code above . But it is returning null .
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tagsRef = rootRef.child("Tags");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String article_name = ds.child("article_name").getValue(String.class);
Log.d("TAG", tagsRef);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
tagsRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Blood Circulation
Dummy Article
Also don't forget to use names for the keys that does not contain any spaces. So you need to change blood circulation in blood_circulation or bloodCirculation

Retrieve all data from Firebase Database

ANDROID: I have a Firebase database like this.
In my app, I would like to compile an arraylist that displays all values from the nameofEntry [DESCRIBED BELOW]. By this I mean the "balso," the "nairboh" and so on.
I have the references:
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference users = root.child("Users");
DatabaseReference childRef = users.child(userID);
DatabaseReference childRefNameNode = childRef.child(nameOfEntry);
childRefNameNode.child(nameOfEntry).setValue(nameOfEntry);
//FETCH DATA
childRefNameNode.child(nameOfEntry).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valueFromDB = dataSnapshot.getValue(String.class);
Log.i("Jimit", valueFromDB);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But this only fetches for one entry. How can I get more entries? [All of them]?
You need to use this code snippet. You haven't used any for loop to step over your children.
EDIT: Also, update your database reference as:
//Updated ref
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);*
//add listener to updated ref
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//use the for loop here to step over each child and retrieve data
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){
String valueFromDB = childSnapshot.getValue(String.class);
Log.i("Jimit", valueFromDB);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Do let me know if it changes anything for you.

Categories

Resources