I have one question, every time i want to insert data, it is replacing the old data either from another email as well, and when i go and change that line ref.child("User01").setValue(user); user01 to user02 then it is generating another user, so can u plz tell me how i resolve that issue......... , so that from one email i can create one user and when i login from other user, it will automatically create another user.
public void btnInsert(View view) {
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
getValues();
ref.child("User01").setValue(user);
Toast.makeText(EditableProfileActivity.this,"Data Inserted Successfully......", Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void btnLogout(View view) {
firebaseAuth.signOut();
finish();
startActivity(new Intent(this, MainActivity.class));
}
You'll typically store the user data in the database under each user's UID (which is guaranteed to be unique for each user).
If your user variable points to a Firebase Authentication User then this can be done with:
ref.child(user.getUid()).setValue(user);
Related
How i can in this code
#Override
protected void onStart() {
super.onStart();
//if the user is already signed in
//we will close this activity
//and take the user to profile activity
if (mAuth.getCurrentUser() != null) {
finish();
startActivity(new Intent(this, ActivitySplash.class));
}
}
make check whether the child (userId) is set to ON / OFF and if ON then we run the code
if (mAuth.getCurrentUser() != null) {
finish();
startActivity(new Intent(this, ActivitySplash.class));
}
if OFF then we show a specific activity.
My database
As #FrankvanPuffelen said, you should spend some time reading docs, it would help you write code yourself, still I am briefing the things for you here. It should make things more clear.
Reading from database is done by correctly referencing your desired node from the database and then using the correct eventListener. There are 3 types of eventListeners present, singleValueEventListener, valueEventListener and childEventListener.
Read more about each of them in detail in docs.
This answer can also help you understand childEventListeners.
To retrieve the value of status node you have to go sequentially through your database parent nodes, that are users and that uid with value nfe....
So in code it would look something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(uid);
// uid has the value nfe...
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String status = dataSnapshot.child("status").getValue(String.class);
// compare the value of status here and do what you want
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled", databaseError.toException());
}
});
I am trying to change child key in Firebase like 'Users' is a child and having different children like 'user1' , 'user2' , 'user3'.
But problem is that my code works for single application when new user installed application data is override on previous child.
Instead of using .setValue(hashMap) use .setValue(hashMap).push()
You can check if the user exists already then do not push the new one.
databaseReference.child("User"+Integer.toString(i)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
databaseReference.child("User"+Integer.toString(i)).setValue(hashMap);
}else{
// Don't create user. Start other activity or whatever you need to do
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Let me know if this worked for you
I've been struggling about the change password functionality of my app. I am confused on how I can compare the current pass and store the new password thru firebase database.
Please don't be harsh on me on comments, educate me please. I did research first before asking and tried several times. Most of the tutorials I found are about updating data while clicking an item in listview. The reason why I use db to store users is because I am going to create 2 keys that identifies if user is student or professor.I just want to ask help how am I able to implement change of password.
ChangePassAccount.class
public class ChangePassAccount extends AppCompatActivity {
Button btnSave;
EditText cpass, npass;
String pass, newpass;
DatabaseReference dbPDF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_change_pass_account);
dbPDF = FirebaseDatabase.getInstance().getReference("users").child("password");
cpass = (EditText)findViewById(R.id.currentpass);
npass = (EditText)findViewById(R.id.newpass);
btnSave = (Button) findViewById(R.id.btnsave);
btnSave.setBackgroundResource(R.drawable.button);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pass = cpass.getText().toString();
newpass = npass.getText().toString();
}
});
}
}
i'll suggest you to using firebase auth to manage User Login or Changes password etc.. So maybe you only has to store user Data by UserInfo
this is a sample from Firebase-Manage User to change the user password
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String newPassword = "SOME-SECURE-PASSWORD";
user.updatePassword(newPassword)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User password updated.");
}
}
});
This is not a very technical answer but I ran into this problem in iOS recently.
There is a FirebaseAuth method named 'reauthenticate' that can be found here. This takes a credential that you create by asking for the user's password and getting the email from currentUser. If this returns successful you will know that password is correct. After reauthenticated you can call updatePassword with the new password.
As a suggestion you should not need to store the password separately in the database since Firebase will handle all this for you.
Hope this helps out, good luck!
You'd use a Firebase Database transaction for that. This gives you the current value, which you then compare against the old password. If they match, you return the new password.
Something like:
passwordRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
String password = mutableData.getValue(String.class);
if (password.equals(oldPassword) {
mutableData.setValue(newPassword);
return Transaction.success(mutableData);
}
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
Log.d(TAG, "passwordTransaction:onComplete:" + databaseError);
}
});
First you need to read the current password using single value event listener
pass = cpass.getText().toString();
newpass = npass.getText().toString();
dbPDF.addValueEventListener(addListenerForSingleValueEvent(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
String password = dataSnapshot.getValue(String.class);
if(password.equals(pass)){
dbPDF.setValue(newpass);
}else{
// show wrong pass dialog
}
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
Also make sure dbref is correct
String username = "helpmepls";
dbPDF = FirebaseDatabase.getInstance().getReference("users").child(username).child("password");
I am creating an app and part of it's features in user interaction. I want to store user comments on a post and I do not want to limit the amount of comments any one user can make. I do this by assigning a random number as the .setValue of the database entry.
With this implementation, whenever the comment is sent to the database it is stuck in an infinite loop where it will continually update with the same string entered in the text box but it will constantly generate new posts.
Full code;
sendComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
commitPost();
finish();
}
});
}
private void commitPost() {
commentProgress.setMessage("Posting");
commentProgress.show();
final String commentInput = commentText.getText().toString().trim();
if(TextUtils.isEmpty(commentInput)){
Snackbar.make(commentLayout,"You haven't finished your post yet",Snackbar.LENGTH_SHORT);
}else{
commentDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String uniqueId = UUID.randomUUID().toString();
commentDB.child(postID).child("Comments").child(uniqueId).setValue(commentInput);
commentProgress.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
The problem lies in the commentDB.addValueEventListener
The problem is that you set a listener for data changes and you also change data inside it (so it is called).
You don't need the listener, just add:
else {
String uniqueId = UUID.randomUUID().toString();
commentDB.child(postID)
.child("Comments")
.child(uniqueId)
.setValue(commentInput);
commentProgress.dismiss();
}
Im trying to save user information in Firebase Database but a strange behavior happens that make the Save button to restart the same activity not the Intent that i made for the next activity .
public void userData () {
user.setFName(Fname.getText().toString());
user.setLName(Lname.getText().toString());
user.setEmail(Email.getText().toString());
user.setAddress(userAddress.getText().toString());
user.setPassword(UserInfo.getString("Password", ""));
user.setID(CicID.getText().toString());
user.setUsername(Usnm.getText().toString());
if (bAdmn.isChecked()) user.setMajor("Business Administrator");
if (BTech.isChecked()) user.setMajor("Business Tech");
if (masscom.isChecked()) user.setMajor("Mass Com");
if (Eng.isChecked()) user.setMajor("Engineering");
final String us = user.getUsername();
Log.i("Username", us);
MyDatabase1.child("USERS").child(us).setValue(user);
Intent i = new Intent(getApplicationContext() , chooseCoursesActivity.class);
startActivity(i);
}
that is the method for save button , Note that i want to update the user information in a profile Activity if the user wants to change his First name or Last name or something .
But after Clicking save button , the data is saved correctly but the intent never done . it recreate the same Activity .
in the Login activity there is aLogin button which checks username and password then attempt to log in based on data ,if login successful it goes to that Profile Activity .
Save button in Profile Activity re Do the method in Login button in Login Activity which checks everything and goes to Profile Activity which what causing the Re Create Problem .
Here is the code for login button :
MyDatabase = FirebaseDatabase.getInstance().getReference();
MyDatabase.child("USERS").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean exists = false;
for (DataSnapshot child : dataSnapshot.getChildren()) {
final Map<String, Object> model = (Map<String, Object>) child.getValue();
if (model.get("username").equals(Username.getText().toString())) {
exists = true;
Log.i("USername"," Correct");
if(exists){
MyDatabase.child("USERS").orderByChild("username").equalTo(Username.getText().toString())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child :dataSnapshot.getChildren()){
Log.i("Password",child.getValue().toString());
Log.i( "Password",child.child("password").toString());
if(password.getText().toString().equals(child.child("password").getValue())){
Log.i("LOGIN","Success");
loginsuccessful = true ;
if(loginsuccessful){
saveCredntials(Username.getText().toString(),password.getText().toString());
Intent i2 = new Intent(getApplicationContext(), ProfileActivity.class);
i2.putExtra("loginStats",IsLoggedIn);
i2.putExtra("Username",Un);
i2.putExtra("Password",Pw);
startActivity(i2);
finish();}
}else{
Log.i("LOGIN","Failed");
loginsuccessful= false ;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
}
break;
}else {
Log.i("LOGIN","FAiled");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Sorry for making this too long but i dont know the problem .
I just solved this problem! According to your case, please avoid using addValueEventListener, because it will listen to all changes you make to the database. That's why every time you make any change to the database, the code in the addValueEventListener (startActivity) will be executed no matter you call that login function or not.
My suggestion is using addListenerForSingleValueEvent instead of addValueEventListener (Make sure you change ALL the addValueEventListener in your Android project to addListenerForSingleValueEvent), or you can even remove the listener if you don't really need it. I don't know if it is a good design, but it should be able to solve your problem.
Avoid putting startActivity on a firebase listener. startActivity execute every time a value is added or removed from firebase database.