I am using email and password. I have create user and authenticate user but I don't know how to add a session for this user.
For example, if the user logs into his/her account. He/she is able to delete the application's process on their phone when they do not want to use the app, then get rid of the app's process and the session is should still be ongoing, therefore when they go back to their application they should still be logged in until he/she logs out (unauth).
I am having trouble making a session for a logged in user. I believe a token must be used but I have no idea how I should use it.
Login Activity:
Firebase user_data = new Firebase("https://myapp.firebaseio.com");
user_data.authWithPassword(login_email.getText().toString(), login_pwd.getText().toString(), new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
Toast.makeText(getBaseContext(), "Login success!", Toast.LENGTH_LONG).show();
Intent toMainActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(toMainActivity);
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// there was an error
System.out.println("ERROR.........................................");
}
});
Heres a simple scenerio:
User logs in. (From Login class is being Intent to Main activity class)
User does not log out but delete app's process.
Later User decides to use the app.
My problem: When click on app, it brings the user back to the Login page whereas it should brought the user to the Main Activity page.
Updated - Initialization
I have initialize it's still not saving the logged in state.
My problem: When click on app, it brings the user back to the Login page whereas it should brought the user to the Main Activity page.
Here's the Main Activity page:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.activity_main);
Firebase user_data = new Firebase("https://myapp.firebaseio.com");
user_data.addAuthStateListener(new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
if (authData != null) {
System.out.println("Authentication is currently working"); //this did print
} else {
System.out.println("Failed authentication");
}
}
});
AuthData authData = user_data.getAuth();
if (authData != null) {
System.out.println("The state is: " + authData); //this did print
} else {
System.out.println("Failed");
}
I check the authentication and they seem to be fine but when I delete the process after logging in at the Main Activity it jumps back to the Login page when I reload the app.
The results for monitoring the auth data above:
working auth
Authentication is currently working
state
The state is: AuthData{uid='simplelogin:3', provider='password', token='***', expires='1426758087', auth='{provider=password, uid=simplelogin:3}', providerData='{email=du16493#gmail.com, isTemporaryPassword=false}'}
Authentication is currently working
SOLVED
Just add the intent if authentication is currently running and it should straight back into the Main activity when the app first loads up on your phone at your first activity you called.
Here's the Login Activity page:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.activity_main);
Firebase user_data = new Firebase("https://myapp.firebaseio.com");
user_data.addAuthStateListener(new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
if (authData != null) {
System.out.println("Authentication is currently working"); //this did print
Intent toMainActivity = new Intent( getBaseContext(), MainActivity.class);
startActivity(toMainActivity);
} else {
System.out.println("Failed authentication");
}
}
});
AuthData authData = user_data.getAuth();
if (authData != null) {
System.out.println("The state is: " + authData); //this did print
} else {
System.out.println("Failed");
}
In order for authentication sessions to be persisted across application restarts, you'll need to initialize the Firebase Android client library with you Android context:
From https://www.firebase.com/docs/android/guide/setup.html:
The Firebase library must be initialized once with an Android context.
This must happen before any Firebase reference is created or used. You
can add the Firebase setup code to your Android Application's or
Activity's onCreate method.
#Override
public void onCreate() {
super.onCreate();
Firebase.setAndroidContext(this);
// other setup code
}
The Firebase client will automatically be authenticated on subsequent application cold starts. To check authentication state, see Firebase Android: Monitoring Authentication.
Related
i want to make a swiggy type app. i have integrated gmail login in my login screen and it changes to dashboard activity on success but when i click on account tab it goes back to dashboard screen instead of account activity. pls help......
login screen
dashboard
if you want any portion of code just comment and i will update
//login screen part
//check if already signed in using google
account = GoogleSignIn.getLastSignedInAccount(this);
if(account!=null) {
finish();
Intent intent = new Intent(this, DashboardActivity.class);
startActivity(intent);
return;
}
//onclicklistener added
//method
private void googleSignin() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
onActivity result(//params provided){
if(googleLogin){
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
googleLogin = false; //set to false so that it can be set true again if login is actually successful
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
sessionManager.setLogin(true);
googleLogin = true;
Intent intent = new Intent(this,DashboardActivity.class);
intent.putExtra("googleLogin", googleLogin);
startActivity(intent);
finish();
}
//Dashboard part
Intent i = new Intent(DashboardActivity.this ,MyAccountActivity.class);
i.putExtra("googleLogin", googleLogin);
startActivity(i);
//myaccount part
if(googleLogin){
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null) {
String personName = acct.getDisplayName();
//System.out.println(personName); working fine
account_name.setText(personName);
String personEmail = acct.getEmail();
//System.out.println(personEmail); fine
account_email.setText(personEmail);
account_mobile.setText("+91 1234567890");
// System.out.println(googleLogin);
// System.out.println(fbLogin);
}
}
solved this problem.
the issue was gmail was not able to provide account details for use when i tried to display them in MY ACCOUNT activity that i integrated in my app, thats why it kept on getting crashed. the code was correct thats why it wasnt giving any error i even tried logging it. there it showed correct details but still it wasnt displaying the result in text views.
so what i did was use shared preferences. everytime the user logs in using gmail, the details are stored in them and i retrieve it in MY ACCOUNT activity and yes it displayed the results correctly.
let me know if you need any more help.
This question already has answers here:
One time login in app - FirebaseAuth
(3 answers)
Closed 3 years ago.
I have an application there is user login screen sends to an activity if logging action is OK. But everytime I closed the application, app asks for email and password, I want to stay logged in like instagram or facebook. Have can I do that? And also how can I do that, do I have to change the code in signin activity or create another class for saving the current user, I am so much confused. There is my login code for firebase:
SignInActivity;
public class SignInActivity extends AppCompatActivity {
private EditText SignInMail, SignInPass;
private FirebaseAuth auth;
private Button SignInButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
// set the view now
setContentView(R.layout.activity_signin);
SignInMail = (EditText) findViewById(R.id.SignInMail);
SignInPass = (EditText) findViewById(R.id.SignInPass);
SignInButton = (Button) findViewById(R.id.SignInButton);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
SignInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = SignInMail.getText().toString();
final String password = SignInPass.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Mail", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Password", Toast.LENGTH_SHORT).show();
return;
}
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(SignInActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// 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.
// progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 8) {
Toast.makeText(getApplicationContext(),"pass min 8",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
} else {
Intent intent = new Intent(SignInActivity.this, CampaignActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
public void NavigateSignUp(View v) {
Intent inent = new Intent(this, SignupActivity.class);
startActivity(inent);
}
public void NavigateForgetMyPassword(View v) {
Intent inent = new Intent(this, ResetPasswordActivity.class);
startActivity(inent);
}
}
In the onCreate function, you need to add this piece of code
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
This code will fetch you the currently logged in user if the user has previously signed in, else will return null.
Check this link for further understanding.
Get the currently signed-in user - Firebase Docs
I hope this solved your problem. If you feel this answer is correct, please accept the answer.
When a user logged in successfully store the LOGIN TYPE of User SharedPreferenceence and check that flag again when user restart app. If Shared Preference contains value then just take him to Main Screen.
Like this on each login update this value and check
PreferencesManager.getInstance().getString(ANNONYMOUS_SIGNUP_DATE, "")) && (PreferencesManager.getInstance().getInt(LOGIN_TYPE, 0) == LOGIN_TYPE_ANNONYMOUS)
Since you authenticated the user, then you can create a splash screen before your sign in activity, and write the following code:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
Intent i = new Intent(SplashActivity.this, HomeActivity.class);
} else{
Intent i = new Intent(SplashActivity.this, SignInActivity.class);
}
Here, you check if currently there is a logged in user and then navigate to the right activity according to the condition.
I would recommend you to use splash screen first and check it user is logged in by the following
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
// go to main page
} else {
// No user is signed in
// go to loging page
}
I have a SignInActivity with Firebase AuthStateListener.
final FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
final FirebaseAuth.AuthStateListener firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(FirebaseAuth auth) {
FirebaseUser user = auth.getCurrentUser();
if (user != null && user.isEmailVerified()) {
firebaseAuth.removeAuthStateListener(this);
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
}
};
firebaseAuth.addAuthStateListener(firebaseAuthListener);
When I successfully registered a new Account, I setVisibity(View.Visible) a verify page with EditTextEmail & VerifyButton inside the activity (in case someone wants to resend the email verification).
What I want to do is when I verify my email from my email account, I want the page to automatically start my MainActivity instead of just staying idle in my LoginActivity, like SMS verification, when verification code received in SMS, the app reads the SMS and navigate to MainActivity. Is it possible to achieve this with email verification? Because the FirebaseAuthState never changed even after I click on verification link on my email.
I need something like OnFirebaseAuthUserEmailVerifiedListener
I'm new to firebase, please kindly give me advice on how to achieve this or if it is not possible.
This link is really useful.
Because the FirebaseAuthState never changed even after I click on verification link on my email.
That's because the user is cached, and you need to reload the user:
Do note that the FirebaseUser object is cached within an app session, so if you want to check on the verification state of a user, it's a good idea to call .getCurrentUser().reload() for an update.
You need something like this
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isEmailVerified())
{
// user is verified, so you can finish this activity or send user to activity which you want.
finish();
Toast.makeText(LoginActivity.this, "Successfully logged in", Toast.LENGTH_SHORT).show();
}
else
{
// email is not verified, so just prompt the message to the user and restart this activity.
sendVerificationEmail();
}
}
And method to get emailVerification
private void sendVerificationEmail(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// email sent
// after email is sent just logout the user and finish this activity
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(SignupActivity.this, LoginActivity.class));
finish();
}
else{
// email not sent, so display message and restart the activity or do whatever you wish to do
}
}
});
}
Hope this helps you.
I have followed twitter fabric log in and everything is working fine except for the part where i try to post a tweet. When i execute this following code i need to login again, so it seems like i have to check an access token or some, but i have no idea and can't find how to do that.
#Override
public void onCreate(Bundle savedInstanceState) {
//initialize facebook sdk
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
super.onCreate(savedInstanceState);
TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
if (token != null ) {
Log.d(TAG, "twitter token" + token);
}
if (secret != null ) {
Log.d(TAG, "twitter secret" + secret);
}
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this.getActivity(), new TwitterCore(authConfig), new TweetComposer());
}
then i am using a function to post the tweet
public void TwitterSharing() {
Log.d(TAG, "Running twitter share");
Log.d(TAG, "Share on twitter 1: " + sport);
Log.d(TAG, "Share on twitter 2: " + speed);
Log.d(TAG, "Share on twitter 3: " + distance);
Log.d(TAG, "Share on twitter 4: " + date);
Log.d(TAG, "Shared image url: " + sharedImage);
TweetComposer.Builder builder = new TweetComposer.Builder(this.getActivity())
.text("just setting up my Fabric.")
.image(Uri.parse(sharedImage));
builder.show();
}
It all works but on the web page it is loading i need to login again, that should not happen but i have no idea how.
Thanks for any input.
For that, you need to make an Activity as the launcher activity. Let's call it DispatchActivity
public class DispatchActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
This returns true if user is logged in.
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (isLoggedIn){
//User is logged in, take him to your activity
Intent i = new Intent(this,yourMainActivity.class);
this.startActivity(i);
}
else{
//User is not logged in, take him to your SignIn activity
Intent i = new Intent(this,SignUp.class);
this.startActivity(i);
}
}
}
Remember to make this your launcher activity, and don't create a layout file for it.
I'm creating an app for Android and I've integrated the Facebook SDK to present the users a Feed Dialog with the following code:
public void showDialog()
{
Bundle parameters = new Bundle();
parameters.putString("description", "description about link");
parameters.putString("link", "http://google.nl");
parameters.putString("name","Name of link");
parameters.putString("caption","describe your caption text");
parameters.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = new WebDialog.FeedDialogBuilder(this, Session.getActiveSession(), parameters).build();
feedDialog.show();
}
I call this method after I've created the session:
public void onClick(View v)
{
Session.StatusCallback callback = new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception exception)
{
if(session.isOpened()) showDialog();
}
};
Session.openActiveSession(this, true, callback);
}
The WebDialog comes up and I can login. Then It says that I've already authorized this app but after that, the dialog closes without a warning or something. I don't know why this is the case: all the parameters seems to be ok. Can anyone help me with this and explain why the dialog disappears?