Can't resolve (Firebase)User expression expected - android

Just trying to make a phone authentication as per a tutorial i'm watching which I have written down the code as below, but i keep getting the error expression expected for 'User' - I am completely new to this so I imagine it's something simple I need help nonetheless! Thank you in advance!
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this, new OnCompleteListener<Credential.UserCredential>() {
#Override
public void onComplete(#NonNull Task<Credential.UserCredential> task) {
if(task.isSuccessful())
userIsLoggedIn();
}
private void userIsLoggedIn() {
User = FirebaseAuth.getInstance().getCurrentUser();
if(User != null){
startActivity(new Intent(getApplicationContext(), MainPageActivity.class));
finish();
return;

You have a class named "User" and you didn't define its variable here which showing java expression error . Actually you are looking for User of Firebase , FirebaseAuth has class FirebaseUser . So it should be below code to check current user .
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){.....
Update (cause of new error) - You are implementing PhoneAuthCredential , but passing Username-password based Credential.UserCredential and implemeting wrong method.
Your signInWithPhoneAuthCredential void would be -
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this , new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
userIsLoggedIn();
} else {
//
}
}
});
}
And your attached code would be -
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
//TODO
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
//TODO
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this , new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
userIsLoggedIn();
} else {
//
}
}
});
}
private void userIsLoggedIn() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
startActivity(new Intent(getApplicationContext(), MainPageActivity.class));
finish();
// return;
}
}
Please check the documentation.

Related

How to read data from a branch in firebase

im trying to get the "type" value here (see the image)
and here is what im doing
firebaseAuth.signInWithEmailAndPassword(email , password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
DatabaseReference reference = firebaseDatabase.getReference("user type").child(firebaseAuth.getCurrentUser().getUid());
}
}
});
but i don't know what todo further.
Change it to
DatabaseReference reference = firebaseDatabase.getReference("usertype").child(firebaseAuth.getCurrentUser().getUid()).child("type");
i did this and it worked
firebaseAuth.signInWithEmailAndPassword(email , password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
DatabaseReference reference = firebaseDatabase.getReference("user type").child(firebaseAuth.getCurrentUser().getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String temp = snapshot.child("type").getValue().toString();
Log.d("hereIm","temp == "+temp);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
});

How to associate each Firebase user with their own recyclerView Data

I'm creating an app that display notes list in a recyclerView. I connected the app with firebase authentication and realtime database.
The Realtime Database JSON tree looks like this:
The problem is that I want "Notes" to be part of "Users" which is not the case, because when I login to my app, I found the same Notes in every user account. I want the notes to be displayed for a specific user when they create them.
Here is my code:
SignupActivity.java
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
EditText mName, mEmail,mPassword;
Button mSignupBtn;
FirebaseAuth mAuth;
ProgressBar progressBar;
View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
FirebaseFirestore fStore;
String userID;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.agree_terms)));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
mEmail = findViewById(R.id.et_email_address);
mPassword = findViewById(R.id.et_password);
mName = findViewById(R.id.et_name);
mSignupBtn = findViewById(R.id.create_btn);
progressBar = findViewById(R.id.loading_spinner);
mViewHelper = findViewById(R.id.view_helper);
button = findViewById(R.id.login_google_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
mSignupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
final String name = mName.getText().toString();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(name)) {
mName.setError("Name is required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
mSignupBtn.setVisibility(View.INVISIBLE);
// register the user in firebase
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "User Created", Toast.LENGTH_SHORT).show();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("email", email);
user.put("image", "default");
user.put("thumb_image", "default");
current_user_db.setValue(user);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: user Profile is created for "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: "+ e.toString());
}
});
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else{
Toast.makeText(SignupActivity.this, "Error !" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
mSignupBtn.setVisibility(View.VISIBLE);
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("886475354465-j5suema9gt5mhi2fhli0un9vsn1olvaa.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
NotesAdapter.java
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyHolder>
{
List<Listdata> noteslist;
private Context context;
public NotesAdapter(List<Listdata> noteslist,Context context)
{
this.context=context;
this.noteslist=noteslist;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
MyHolder myHolder=new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, int position) {
Listdata data=noteslist.get(position);
myHolder.title.setText(data.getTitle());
myHolder.desc.setText(data.getDesc());
}
#Override
public int getItemCount() {
return noteslist.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView title,desc;
public MyHolder(#NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title);
desc=itemView.findViewById(R.id.desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listdata listdata=noteslist.get(getAdapterPosition());
Intent i=new Intent(context, StreamActivity.class);
i.putExtra("id",listdata.id);
i.putExtra("title",listdata.title);
i.putExtra("desc",listdata.desc);
context.startActivity(i);
}
});
}
}
}
AddNotesActivity.java
public class AddNotesActivity extends AppCompatActivity {
EditText title,desc;
String titlesend,descsend;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_notes);
title=findViewById(R.id.title);
desc=findViewById(R.id.desc);
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public void AddNotes(View view) {
titlesend=title.getText().toString();
descsend=desc.getText().toString();
if(TextUtils.isEmpty(titlesend) || TextUtils.isEmpty(descsend)){
return;
}
AddNotes(titlesend,descsend);
}
private void AddNotes(String titlesend, String descsend)
{
String id=mDatabase.push().getKey();
Listdata listdata = new Listdata(id,titlesend, descsend);
mDatabase.child("Notes").child(id).setValue(listdata).
addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AddNotesActivity.this, "Notes Added", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),NotesActivity.class));
}
});
}
}
NotesActivity.java
public class NotesActivity extends AppCompatActivity {
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
//HomeScreen variables
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
List<Listdata> list =new ArrayList<>();
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
recyclerView=findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(NotesActivity.this);
recyclerView.setLayoutManager(layoutManager);
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
// Notes Screen
final NotesAdapter notesAdapter=new NotesAdapter(list,this);
recyclerView.setAdapter(notesAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference("Notes");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Listdata listdata=dataSnapshot1.getValue(Listdata.class);
list.add(listdata);
}
notesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddNotesActivity.class));
}
});
// end NotesScreen
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart() {
Intent startIntent = new Intent(NotesActivity.this, LoginActivity.class);
startActivity(startIntent);
finish();
}
Please I need help on how should I modify my code to display the notes for a specific user when they create them. documentation links will be much appreciated.
you simply need to change this line of code from AddNotesActivity.java
mDatabase.child("Notes").child(id)
to
mDatabase.child("Users").child(userID).child("Notes").child(id)
and don't forget to retrieve the data in NotesActivity.java
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID).child("Notes");

java.lang.IllegalArgumentException while authentication using firebase

I am making a Whatsapp like app(By Following tutorial). It crashes when i click on send code button. i confirmed it by try/catch my phone number verification is not working or there's a problem with it
java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential
without either verificationProof, sessionInfo, ortemprary proof.
What i confirmed/tried:
both activities are declared in manifest,
assigned id to layout,
initialized relative argument,
Nothing is there in libs folder of the project,
swapped initialization with layout ,
Tried this code to get value:
String.valueOf(phoneNumberEdt)
I did all what i could as per my level
public class MainActivity extends AppCompatActivity {
private EditText phoneNumberEdt, verificationcodeEdt;
Button sendCodeButton;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks;
String mVerificationId = "0";
//private PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNumberEdt = (EditText) findViewById(R.id.phonenumber_edt);
verificationcodeEdt = (EditText)
findViewById(R.id.verificationcode_edt);
sendCodeButton = (Button) findViewById(R.id.sendcode_btn);
FirebaseApp.initializeApp(this);
userIsLoggedIn();
phoneNumberEdt.setText("03026989523");
sendCodeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//try{
if(mVerificationId != null)
verifyPhoneNumberWithCode();
else
startPhoneNumberVerification();
/*}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(),
"Verification Code is wrong, try again", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}*/
mCallBacks = new
PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential
phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {}
#Override
public void onCodeSent(String VerificationId,
PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(VerificationId, forceResendingToken);
mVerificationId = VerificationId;
sendCodeButton.setText("Verify Code");
}
};
}
});
}
Error points here
private void startPhoneNumberVerification() {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumberEdt.getText().toString(),//String.valueOf(phoneNumberEdt)
60,
TimeUnit.SECONDS,
this,
mCallBacks);
}
Rest of the functions
private void verifyPhoneNumberWithCode(){
PhoneAuthCredential credential =
PhoneAuthProvider.getCredential(mVerificationId,
verificationcodeEdt.getText().toString());
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential
phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).
addOnComp leteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
userIsLoggedIn();
}
});
}
private void userIsLoggedIn() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
startActivity(new
Intent(getApplicationContext(),MainPageActivity.class));
finish();
return;
}
}

Phone auth error

I wrote the code for firebase phone auth, and no error occured. But when i execute the app and entered the number ,i am getting as verification failed .pls help me out
I even connected to firebase proj and enables phone and also wrote SHA certificate
my code for main activity-
public class MainActivity extends AppCompatActivity {
EditText phone,vcode;
TextView msg;
Button getcode,verify;
private FirebaseAuth mAuth;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.phone);
vcode = findViewById(R.id.code);
getcode = findViewById(R.id.getcode);
verify = findViewById(R.id.verify);
msg = findViewById(R.id.msgtxt);
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Toast.makeText(MainActivity.this, "Verified", Toast.LENGTH_LONG).show();
vcode.setVisibility(View.GONE);
verify.setVisibility(View.GONE);
msg.setVisibility(View.VISIBLE);
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(MainActivity.this, "Login Failed", Toast.LENGTH_LONG).show();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
phone.setError("Invalid phone number");
} else if (e instanceof FirebaseTooManyRequestsException) {
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
mResendToken = token;
}
};
}
public void GetCode(View view) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone.getText().toString(),
60,
TimeUnit.SECONDS,
this,
mCallbacks);
phone.setVisibility(View.GONE);
getcode.setVisibility(View.GONE);
vcode.setVisibility(View.VISIBLE);
verify.setVisibility(View.VISIBLE);
}
public void verify(View view) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, vcode.getText().toString());
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>
() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user=task.getResult().getUser();
startActivity(new Intent(MainActivity.this,MainActivity.class));
vcode.setVisibility(View.GONE);
verify.setVisibility(View.GONE);
msg.setVisibility(View.VISIBLE);
finish();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "Invalid code", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
For main2 activity-
public class Main2Activity extends AppCompatActivity {
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Main2Activity.this, MainActivity.class);
startActivity(i);
}
});
}
}

How to make a user sign out in Firebase?

I am making a simple authentication app in Android using Firebase authentication. Till now I am successful in signing the user in, however the issue is that the user remains signed in, and I can't find a way to sign him out.
Here is my MainActivity.java code
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//tracking the sign in and singn out operations
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user!=null){
System.out.println("User logged in");
}
else{
System.out.println("User not logged in");
}
}
};
}
public void onStart(){
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
public void onStop(){
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
public void buttonClicked(View view){
EditText editemail = (EditText) findViewById(R.id.email);
EditText editpass = (EditText) findViewById(R.id.password);
String email = editemail.getText().toString();
String password = editpass.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
Toast.makeText(MainActivity.this, "Authentication Success.",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this,Success.class));
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
// Log.w(TAG, "signInWithEmail", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
Use this code FirebaseAuth.getInstance().signOut();
You can simply call this
FirebaseAuth.getInstance().signOut();
If you want to perform some action after sign out then use this one.
public void onClick(View v) {
if (v.getId() == R.id.sign_out) {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(MyActivity.this, SignInActivity.class));
finish();
}
});
}
}
This can be solved by using AuthStateListener
//Declaration and defination
private FirebaseAuth firebaseAuth;
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null){
//Do anything here which needs to be done after signout is complete
signOutComplete();
}
else {
}
}
};
//Init and attach
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.addAuthStateListener(authStateListener);
//Call signOut()
firebaseAuth.signOut();
Snippet : https://codepad.co/snippet/aPeehdoD
Firebase auth is provide signout method.
FirebaseAuth.getInstance().signOut();
Try This
FirebaseAuth fAuth = FirebaseAuth.getInstance();
fAuth.signOut();
if you are using firebaseAuthUI then recommended method is
public void onClick(View v) {
if (v.getId() == R.id.sign_out) {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(MyActivity.this, SignInActivity.class));
finish();
}
});
}
}
according to firebaseAuthUI github Guide.
use this`
findViewById(R.id.signout).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(currentActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);//makesure user cant go back
startActivity(intent);
}
});`
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseAuth.getInstance().signOut();
Intent intent = new Intent(SettingsActivity.this,SignInActivity.class);
startActivity(intent);
}
});
This one just signs you out from the current application .
if you are using a fragment do this
AuthUI.getInstance().signOut(getActivity());
if you are using an activity do this
AuthUI.getInstance().signOut(getApplicationContext);
cheers!
For complete log out I would recommend :
mFirebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
There have several way to sign out user:
1. FirebaseUI: Refarence
Add depenencies:
dependencies {
implementation 'com.firebaseui:firebase-ui-auth:4.0.0'
}
Then:
public void onClick(View v) {
if (v.getId() == R.id.sign_out) {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(MyActivity.this, SignInActivity.class));
finish();
}
});
}
}
2. Kotlin: Referance
Use Android default Authentication dependency, ex: com.google.firebase:firebase-auth:16.0.1
firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
3. Default with java:
Use Android default Authentication dependency, ex: com.google.firebase:firebase-auth:16.0.1
FirebaseAuth mAuth = FirebaseAuth.getInstance();
try {
mAuth.signOut();
Toast.makeText(this, "User Sign out!", Toast.LENGTH_SHORT).show();
}catch (Exception e) {
Log.e(TAG, "onClick: Exception "+e.getMessage(),e );
}
FirebaseAuth.getInstance().signOut();
Then, to detect the sign-in status:
private FirebaseAuth mAuth = FirebaseAuth.getInstance()
public static boolean mAuthSignIn() {
if (mAuth != null) {
FirebaseUser user = mAuth.getCurrentUser();
return user != null;
}
return false;
}
Try this one it is working for me.
FirebaseAuth.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(YOUR CURRENT ACTIVITY, ACTIVITY IN WHICH YOU WANT TO MOVE));
finish();
}
});

Categories

Resources