Firebase not creating new node - android

I have one node name users which is populating fine, but I am trying to incorporate a new node events, which I am having trouble with. I have copied exactly what works in the users, but I am clearly doing something wrong. It never goes into the OnCompleteListener. Is there something I am missing?
R.string.dbnode_events ="events"
Events events = new Events();
events.setEvent_key(mEventKey);
events.setEvent_title("");
events.setEvent_date("");
events.setEvent_time("");
events.setEvent_millis("");
events.setEvent_desc("");
events.setEvent_filter("");
events.setGroup_number("");
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbnode_events))
.child(mEventKey)
.setValue(events).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(CreateEventActivity.this, "Success", Toast.LENGTH_SHORT);
}
});
More Information/ Example: The top user one creates a node no problem but the events one has yet to create. I hope this might give some more insight.
User user = new User();
user.setName(email.substring(0, email.indexOf("#")));
user.setPhone("1");
user.setProfile_image("");
user.setSecurity_level("1");
user.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
user.setEmail(FirebaseAuth.getInstance().getCurrentUser().getEmail());
user.setStreet_address("");
user.setCity("");
user.setState("");
user.setZip("");
user.setMember_filter("Member");
user.setSmall_group_subscription1("");
user.setSmall_group_subscription2("");
user.setSmall_group_subscription3("");
user.setSmall_group_subscription4("");
user.setSmall_group_subscription5("");
user.setShow_phone("No");
user.setShow_email("Yes");
user.setShow_address("No");
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbnode_users))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
.addOnCompleteListener(task1 -> {
FirebaseAuth.getInstance().signOut();
redirectLoginScreen();
}).addOnFailureListener(e -> {
FirebaseAuth.getInstance().signOut();
redirectLoginScreen();
Toast.makeText(RegisterActivity.this, "Database Problem ",Toast.LENGTH_SHORT);
});
/////////////////////////
String mEventKey = UUID.randomUUID().toString();
Events events = new Events();
events.setEvent_key(mEventKey);
events.setEvent_title("");
events.setEvent_date("");
events.setEvent_time("");
events.setEvent_millis("");
events.setEvent_desc("");
events.setEvent_filter("");
events.setGroup_number("");
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbnode_events))
.child(mEventKey)
.setValue(events)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(RegisterActivity.this, "Success", Toast.LENGTH_SHORT);
}
});

This is what i have done, probably it will help :D
When you add a class, you have to create a reference like this :
private DatabaseReference Accounts;
And inside the onCreate :
Accounts = FirebaseDatabase.getInstance().getReference("Accounts");
After that, set ur class. I do this for the user :
currentwithID = new Class_user(uID,uSer,matchFound);
And than set it on the node :
uID is the token given by Google
Accounts.child(uID).setValue(currentwithID);
I have done the same things to every node of my database, and it perfectly works.
Try to do that with this code, and tell me if it works :D

Related

How to use set Value instead of getUid in FirebaseDatabase in android

I'm working with Firebase authentication and database.In my project user sign in and sign up with their email and password.I use a model class where i have three variable email,password and name.I can store email in authentication sector and users details in database.
code is given below:
User user = new User(name,mail,password);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
startActivity(new Intent(SignUp.this,Home.class));
finish();
}else {
Toast.makeText(SignUp.this, "Getting error", Toast.LENGTH_SHORT).show();
}
}
Is there any way that i used user name instead of getUid value?like this
To solve this, instead of passing the uid (FirebaseAuth.getInstance().getCurrentUser().getUid()) of the user to the child() method, pass the userName:
FirebaseDatabase.getInstance().getReference("Users").child(name).setValue(user).addOnCompleteListener(/* ... */);
// ^ ^
See I have passed the name instead of the uid.
You can set like below: replace FirebaseAuth.getInstance().getCurrentUser().getUid() with name. It will create node with userName.
user = new User(name,mail,password);
FirebaseDatabase.getInstance().getReference("Users")
.child(name) // replace the getUid() code with name
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
startActivity(new Intent(SignUp.this,Home.class));
finish();
}else {
Toast.makeText(SignUp.this, "Getting error", Toast.LENGTH_SHORT).show();
}
}
Hope it will help you:)

Signing out from Firebase recall signinwithemailandpassword

The situation is the following:
The activity started on app's launch (let's call it splash activity, because used for some checkings and for read/write some settings) is made by frameworks and the last one of them has firebase signInWithEmailAndPassword whose addOnCompleteListener contains the code for starting a new activity (let's say the main activity).
one of the options of the (so called) main activity's menu is firebase signOut, when i tap it the current user signs out but the signInWithEmailAndPassword (coded into the last fragment of previous activity) is called again!
is it because i splitted sign-in and sign-out in two different activities?
can anybody kindly help me with that, thanks in advance.
here is code schema:
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// read some data from realtime database
database
.getReference(path)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
get snapshot data ...
// Store them into shared preferences
mSettings
.edit()
.putStringSet("STRING_SET_KEY", dataSet)
.apply();
// Update some Realtime database data
database
.getReference(path)
.updateChildren(newData)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// Start new activity
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
});
});
});
});
}
});
});
p.s. - i noticed because the signOut() kicks out the firebase user and when the signInWithEmailAndPassword is called again i got an error because it's not possible to read realtime database
You may check whether the user is still sign in or not.
According to this link: https://firebase.google.com/docs/auth/android/manage-users
This code put at the onCreateView...
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
// Start new activity
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
} else {
// No user is signed in
}

firestore onSuccess listener isn't working

I am trying to download some Quiz objects from my database.
The following function is called from onCreate of a certain activity.
private void downloadQuizzesFromCloud(){
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
final FirebaseFirestore db = FirebaseFirestore.getInstance();
String user_quizzes_path = "users/".concat(user_id).concat("/quizzes");
Query userQuizzes = db.collection(user_quizzes_path);
userQuizzes.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
quizzes.clear();
for (QueryDocumentSnapshot document : task.getResult()) {
Quiz quizDownloaded = getQuizFromCloud(document.getId());
quizzes.add(quizDownloaded);
}
Toast.makeText(QuizzesActivity.this,"downloaded to list ".concat(String.valueOf(quizzes.size()).concat(" quizzes")), Toast.LENGTH_SHORT).show();
//TODO put in recycle adapter
} else { }
}
});
}
(user_quizzes_path contains the correct path to a collection of Quiz objects stored on the cloud)
I debugged this functions and found out that after the command:
userQuizzes.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>()
The function finishes execution, that is the onComplete cases aren't checked and executed and all this code is just skipped.
I tried to find this on the documentation of firebase but didn't find anything.
Why is this happening and how can I fix this?
Would appreciate some help here, thanks!
The onComplete is called when the read operation has completed from the Firestore servers. If it's not getting called, I can see two possible reasons:
You're not connected to the server. Unless you've read the data before (and it's in the local database that the Firestore client maintains), this means the read never completes locally.
You're not thinking asynchronously. Note that data is read from the server asynchronously, and there may be some time between when you call get() and when onComplete fires. To test if this is the case, put a breakpoint on if (task.isSuccessful()) { and run the app in the debugger. The breakpoint will hit when the data is read from the server.
Use a callback interface. Just like this below.
private void downloadQuizzesFromCloud(Consumer listener) {
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
final FirebaseFirestore db = FirebaseFirestore.getInstance();
String user_quizzes_path = "users/".concat(user_id).concat("/quizzes");
Query userQuizzes = db.collection(user_quizzes_path);
userQuizzes.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Quiz> quizzes = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
Quiz quizDownloaded = getQuizFromCloud(document.getId());
quizzes.add(quizDownloaded);
}
listener.onGet(quizzes);
Toast.makeText(QuizzesActivity.this,"downloaded to list ".concat(String.valueOf(quizzes.size()).concat(" quizzes")), Toast.LENGTH_SHORT).show();
//TODO put in recycle adapter
} else { }
}
});
}
interface Consumer {
void onGet(List<Quiz> quizzes);
}

How to check whether a user is authenticated or not in Firebase?

I have a few sign-up methods in my app as shown below:
Let's revolve the problem around Google sign-in method:
What I am doing is that when a user signs in enteringDataIntoUserNode() method is called inside signInWithCredential() method like:
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential =
GoogleAuthProvider.getCredential(acct.getIdToken(), null);
// signing in
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// entering default values in the database
enteringDataIntoUserNode();
Intent intent = new Intent(LoginAndSignupActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
}
}
});
}
enteringDataIntoUserNode()
private void enteringDataIntoUserNode() {
final String currentUid = mAuth.getCurrentUser().getUid();
//
String deviceToken = FirebaseInstanceId.getInstance().getToken();
final String userName = mAuth.getCurrentUser().getDisplayName();
String imageUrl = mAuth.getCurrentUser().getPhotoUrl().toString();
String userStatus = "Hi there! How is it going?";
// inserting data in key-value pair
usersReference.child(currentUid).child("user_name").setValue(userName);
usersReference.child(currentUid).child("user_status").setValue(userStatus);
usersReference.child(currentUid).child("user_image").setValue(imageUrl);
usersReference.child(currentUid).child("device_token").setValue(deviceToken);
// when this last value will be inserted then, making an intent to MainActivity
usersReference.child(currentUid).child("user_thumb_image").setValue(imageUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: Data insertion for the new user is successful ");
}
}
});
}
enteringDataIntoUserNode() method is simply passing some default data to the database every time a user signs in. But if a user change its details like image or username etc. and sign out and again sign in through Google sign in method then again enteringDataIntoUserNode() method will be called and user details would be overwritten with the default ones.
My question is that is there any way to check whether a user is signing in for the first time or not during the Google sign in so that in the latter case I can skip calling enteringDataIntoUserNode() method and prevent overwriting of data.
Same thing I want to acheive during Facebook and Phone Number sign in.
If you check if the user logs in for the first time, it's the same thing if you want to check if a user is new. So to solve this, we can simply call the isNewUser() method in the OnCompleteListener.onComplete callback like this:
OnCompleteListener<AuthResult> completeListener = new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d("TAG", "The user is new!");
} else {
Log.d("TAG", "The user is not new!");
}
}
}
};
For more informations, please see the official documentation.
You could check when the account was created with:
task.getResult().getUser().getMetadata().getCreationTimestamp()
See the reference docs.
But a common approach is also to check if the user already exists in the database using a transaction.

Firebase user delete code not working from application

I have used the following code after the button clicked event :
mCurrentUser = FirebaseAuth.getInstance.getCurrentUser();
mCurrentUser.delete.addOnCompleteListner(............)
and also used if and else statement for appropriate actions for the task to be done.
But nothing's happening in the application on that click event, also not deleting the firebase user account. Help me regarding this.
thank you.
try with this answer, I had tried with this
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted.");
}
}
});

Categories

Resources