I have some problems related to my database, and the docs seems a lot of confusing i can't figure out how to solve that, basicly i have my user data in the firebase, and i want to see if in my user with some id i already have the key username if yes i want to update with some data of my form, if no i want to add a value based on my form, but when i want to know how to check if the id already exist, i did this:
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
userId = auth.getCurrentUser().getUid();
user = myRef.child("Users").child(userId);
Log.d("test1",String.valueOf(user.child("age").getKey()));
if(user.child("username").co){
usernameTxt.setText(user.child("username").toString());
}
if(user.child("age") != -1){
usernameTxt.setText(user.child("age").toString());
}
Try this
final FirebaseAuth auth = FirebaseAuth.getInstance();
DatabaseReference mDatabase=FirebaseDatabase.getInstance().getReference().child("Users").child(auth.getCurrentUser().getUid());
mdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild("username")){
//IT EXISTS
}
else{
//IT DOESNT EXISTS
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
I'm working on a Firebase ecommerce app, I have been trying to update the password when passing the email of the user in "forgot password" feature but i can't get it right.
Here is my Firebase structure:
I want the method to get the user with the entered email, then update his password to a new one.
Here is my code:
set_new_pass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
Query checkUserDatabase = reference.orderByChild("email").equalTo(user_email);
String user_newpass=new_password.getText().toString();
HashMap hashMap = new HashMap();
hashMap.put("password",user_newpass);
// hashMap.put("email",user_email);
checkUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
//String username_ofuser =hashMap.get("username").toString();
reference.child(user_username).updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Toast.makeText(SetNewPassword.this, "your password is successfully changed!", Toast.LENGTH_SHORT).show();
}
});
}
}
How can I achieve my results?
this code should change the password of the user that has his email entered but it doesn't change anything actually so what can i do to make it work correctly??
I'm quite confused with listeners and Firebase. I understand that the only way to retrieve data from Firebase is listeners. I'm using addListenerForSingleValueEvent to retrieve the username value, which it works well only when that value changes or when I execute this code for a second time. Username value shouldn't change at all but I still need to read it often. How do you read from FB when no changes had occurred?
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("forum")
.child("level1exercice1").child("post").child("username");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
value = snapshot.getValue(String.class);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Have you tried reading it as a snapshot and then storing it as a cookie for future use?
The following code is from Firebase Docs:
FirebaseDatabase.DefaultInstance
.GetReference("Leaders").OrderByChild("score").LimitToLast(1)
.ValueChanged += HandleValueChanged;
}
void HandleValueChanged(object sender, ValueChangedEventArgs args) {
if (args.DatabaseError != null) {
Debug.LogError(args.DatabaseError.Message);
return;
} // Do something with the data in args.Snapshot
}
I read many threads regarding how to get data from Firebase database instance, but none of them worked for me.
My code in the activity:
public class Violations extends AppCompatActivity
{
TextView textView7;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dbref = database.getReference("save");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violations);
textView7 = findViewById(R.id.textView7);
dbref.addValueEventListener(new ValueEventListener()
{
ArrayList<String> Violations = new ArrayList<>();
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
{
Violations.add(postSnapshot.getValue().toString());
System.out.println(postSnapshot.getValue().toString());
}
for(int i=0; i < Violations.size(); i++)
{
textView7.setText(textView7.getText() + Violations.get(i) + System.lineSeparator());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
}
There is no error in there, but no data displays. I am pretty sure, my problem is connecting to the right instance and retrieving the data.
Firebase data, are like this:
Can someone please help me in there?
Thanks you in advance.
Initialize the Firebase database & the DatabaseReference inside onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violations);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dbref = database.getReference("save");
...
..
Also, the reference you are getting is save but the Firebase database shows that is : you violate .... You may try changing the name to save or getting the right data : you violate ....
Try to use addListenerForSingleValue() instead of addValueEventListener(). Hope it helps. And change your firebase link save to you violate your own speed limit with
I cannot see in your database schema o reference named save but I see one named You violate your own speed limit with, which mush be used in your reference in order to be able to get data from the database. So to solve this, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("You violate your own speed limit with");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> violations = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String speed = ds.getValue(String.class);
violations.add(speed);
Log.d(TAG, speed);
}
//Do what you need to do with y our violations list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be all those values:
3 km / h at time: ...
3 km / h at time: ...
//an so on
i was trying to update only one field when user clicks a button
here is the database
i need to update report_status when user clicks a button
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
report_value=Integer.parseInt(arrayforreport.get(posi));
report_value++;
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//i need to update report_status by id
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
In order to update a value in your Firebase database there is no need to attach a listener, that is needed only when you need to read data. So to update a particular node, you only need to use setValue() method directly on the databaseReference object.
So assuming that the type node is a direct child of your Firebase database, please use the following line of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("type")
.child("Whatsapp")
.child("Shopping Deals")
.child(shoppingDealId)
.child("report_status")
.setValue("newValue");
In which shoppingDealId is the id of a particular shopping deal. You can get this id using the following line of code:
String key = ref.push().getKey();
addValueEventListener is to retrieve the value, you don't need it to set the value.
First get the key from DatabaseReference then use setValue to change the value.
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
report_value=Integer.parseInt(arrayforreport.get(posi));
report_value++;
DatabaseReference databaseReference = adapter.getRef(position);
String key = databaseReference.getKey();
databaseReference.child("type").child("Whatsapp").child("Shopping Deals").child(key).child("report_status").setValue(report_status);
}
});
When a user makes an account with firebase on my android app, they then need to be directed to a screen where they can add some separate information like username, for example. The app knows to switch the activity through an AuthStateListener, so when an account is made or someone signs in the code here is executed (no intents are changed here right now, keep reading to see why):
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
userID = user.getUid();
toastMessage("User has signed in: " + user.getEmail());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
In the if block where it is checking to see if user does not equal to null, this is where I need to change the intent to another activity where they will enter their username. Basically the logic is, if the user already has a username and they are just signing in then they will be directed to the home screen activity, and if they are signing up they need to be directed to the activity where they make a username. To know which activity I need to send them to I need to have the code look in the firebase database and see if their account has a username already or not. I cannot figure out how to read data from the firebase in this situation, it seems as if the only way to read from the database (according to others) is through an onDataChange methods like so:
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "This: "+dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
which uses dataSnapshots. the problem with this is this code is only fired when data is added to the database, therefor this method will not execute any code when a user is simply signing up and has never added a username to the database. How can I query to see data from the database just to check if a certain user has any data there?
OnDatachange is fired in all of cases, if user add data, remove data, change data ect.
To check is user already have username do this inside OnDatachange:
if(dataSnapshot.exists()){
//GO TO OTHER ACTIVITY
]else{
//GO TO SET USER DATA ACTIVITY
]
See this exemple of one of my implementations:
if (user !=null){
DatabaseReference myRef = database.getReference("users").child(user.getUid()).child("user_bio");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
bio.setText(dataSnapshot.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
In this exemple if user_bio exists then set text to userbio if not do nothing. In the first time that user log in in my app this method do nothing but when user add bio this method set the bio text in userbio text. but if i want to show some text if user hasnt bio i simply add na else and set text to the bio for exemple:
if (user !=null){
DatabaseReference myRef = database.getReference("users").child(user.getUid()).child("user_bio");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
bio.setText(dataSnapshot.getValue(String.class));
}else{
bio.setText("no user bio");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Have you try to use addValueEventListener inside onCreate method?
If you run an activity while the listener inside onCreate method it will fired once when you open an activity. So i think you shouldn't have a problem here.