Android Firebase Admin user Java [duplicate] - java

This question already has answers here:
How to redirect multiple types of users to their respective Activities?
(3 answers)
Closed 3 years ago.
I have 3 types of user
parents, teacher, admin,
I have already made login activity
and for parent and they will provide email and password and when firebase authenticate it. and when successful it will go to parents activity
And i want to make activity for admin to add and register/signup parents
and they still provide email and pass to my login activity and will be directly to the new admin activity after authenticated by firebase
what changes will do to my login
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText editTextEmail;
private EditText editTextPassword;
private Button Login;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FirebaseApp.initializeApp(this);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() != null) {
// profile activity
finish();
startActivity(new Intent(getApplicationContext(), Parent_Home.class));
}
editTextEmail = findViewById(R.id.input_username);
editTextPassword = findViewById(R.id.input_password);
findViewById(R.id.btn_login).setOnClickListener(this);
progressDialog = new ProgressDialog(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_login: {
userLogin();
break;
}
}
}
private void userLogin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email is required");
editTextEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
editTextEmail.setError("Please enter valid email");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length()<6 ){
editTextPassword.setError("Minimum of length of password should be 6");
editTextPassword.requestFocus();
return;
}
//if the email&pass is not empty
//display dialog
progressDialog.setMessage("Please Wait...");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
//start profile/ menu activity
finish();
SharedPrefs.saveSharedSetting(Login.this, "CaptainCode", "false");
startActivity(new Intent(getApplicationContext(), Parent_Home.class));
} else {
Toast.makeText(Login.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
//Todo: add back confirmation

In sign up process add additional object in your database for every user, for example you can call it a type. So when someone sign up to your app make him choose which type of account he is creating (or maybe you already have this), so object will contain info what account is created: parent or teacher or admin. For example: type: "teacher"
After login return data from database for user who just logged in and check what is the type of his account and according to type value (parent, teacher, admin) you will know who logged in in your app and you can start corresponding screen.

Related

Firebase Login should go to Home Screen if user already exists [duplicate]

This question already has answers here:
How to redirect multiple types of users to their respective Activities?
(3 answers)
Checking if a particular value exists in the Firebase database
(6 answers)
Closed 2 years ago.
First, I will tell the flow of my App.
Login Screen(SignInActivity.java) -> Enter details(MainActivity.java) ->Home Screen(HomeScreenActivity.java)
In my app, I have used Firebase Authentication and Firebase Database. When the user is new, then it should go to Main Activity from SignInActivity where user enters his name, a short description and his hobby. The details are stored in Firebase Database and then HomeScreenActivity opens where user details are shown in Recycler View.
But currently what happens is when same user does login again, it again asks user for details. I want to check if users Google Account already exists in Firebase Auth, then instead of asking details, it should directly go to HomeScreenActivity.
I checked many answers on StackOverflow, but nothing seems to work. One thing that i tried was additionalUserInfo.isNewUser but in this app crashes when user does login again, showing null error where I display user details in HomeScreenActivity.
SignInActivity.java
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuthIn.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");
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(SignInActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
MainActivity.java
public void init() {
hobbiesContinueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name=user.getText().toString().trim();
String desc=description.getText().toString().trim();
String hobby=spinner.getSelectedItem().toString();
String image="default";
String thumbnail="default";
if(!TextUtils.isEmpty(name))
{
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
String userId=currentUser.getUid();
User user=new User(name,hobby,desc,image,thumbnail);
dbRef.child(userId).setValue(user);
startActivity(new Intent(getApplicationContext(), HomeScreenActivity.class));
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Enter a name",Toast.LENGTH_SHORT).show();
}
}
});
}
HomeScreenActivity.java
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
imgvw = headerView.findViewById(R.id.imageView);
imgvw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//to open gallery
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
TextView nameDrawer = findViewById(R.id.navName);
TextView descDrawer = findViewById(R.id.navDescription);
User change = snapshot.getValue(User.class);
assert change != null;
//This is where null error occurs
nameDrawer.setText(change.getUserName());
descDrawer.setText(change.getUserDesc());
//change profile picture
image= Objects.requireNonNull(snapshot.child("userImage").getValue()).toString();
Log.d(TAG, "onComplete: "+image);
if(!image.equals("default")){
Picasso.get().load(image).placeholder(R.drawable.avatar).into(imgvw);
}
}
The solution is to save your user details in shared preferences for the first time when the user sign in , then after the user signs out and sign it again , you get data from shared preferences and set them directly to your edittexts
Try this Code :
///save sharedpreferences
SharedPreferences sharedPreferences =
getSharedPreferences("prefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username","put here your username"); //
editor.putString("email","put your email here"); //you can add more details
editor.apply();
///get sharedpreferences
SharedPreferences sharedPreferences1 =
getSharedPreferences("prefs",Context.MODE_PRIVATE);
String username = sharedPreferences1.getString("username","");
String email = sharedPreferences1.getString("email","");
//then here set the valeus from sharedpreferences to your edittexts

Stay Logged in with Firebase to the app when closed [duplicate]

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
}

Cannot read data from firebase - Firebase DatabaseError: Permission denied

I have created a simple app on which a user can register an login. authentication is working perfectly. I have also added a real-time database. I am getting "permission denied" when i try to read the data from firebase, despite the "write data" is working perfect.
I want to fetch the data for logged in user.
here are firebase rules:
{
"rules": {
"users": {
"$userId": {
".write": "$userId === auth.uid",
".read": "$userId === auth.uid"
}
}
}
}
This is the write method(this works perfect):
public void writeUserInfo(){
String username = etUserName.getText().toString().trim();
String age = etAge.getText().toString().trim();
String sex = etSex.getText().toString().trim();
if(username.isEmpty()){
etUserName.setError("user name required");
etUserName.requestFocus();
return;
}
if(age.isEmpty()){
etAge.setError("age required");
etAge.requestFocus();
return;
}
if(sex.isEmpty()){
etSex.setError("sex required");
etSex.requestFocus();
return;
}
User user = new User(username,age,sex);
mDatabase.child("users/"+firebaseUser.getUid()).setValue(user);
}
And this is the read method:
public void readUserData(){
mDatabase.child("users").orderByChild(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//array list to staore user data as elements
ArrayList<User> userData = new ArrayList<>();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
User element = snapshot.getValue(User.class);
userData.add(element);
}
for(User user: userData){
etUserName.setText(user.getmUsername());
etAge.setText(user.getmAge());
etSex.setText(user.getmSex());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
here is the database hierarchy:
Firebase Console
I am also including login and signup methods:
Login method:
public void signIn(){
String userEmail = etEmail.getText().toString().trim();
String userPassword = etPassword.getText().toString().trim();
//validation
//validation
if(userEmail.isEmpty()){
etEmail.setError("Email is required");
//et is focused
etEmail.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
etEmail.setError("Invalid email address");
//focus et
etEmail.requestFocus();
return;
}
if(userPassword.isEmpty()){
etPassword.setError("Password is required");
//et is focused
etPassword.requestFocus();
return;
}
if(userPassword.length()<6){
etPassword.setError("Password length should be atleast 6 characters");
//request focus
etPassword.requestFocus();
return;
}
//setting progress bar
progressBar.setVisibility(View.VISIBLE);
//firebase signin method
mAuth.signInWithEmailAndPassword(userEmail,userPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//hiding progress bar
progressBar.setVisibility(View.GONE);
if(task.isSuccessful()){
Intent intent = new Intent(getApplicationContext(),Profile.class);
//this flag will clear all the open activities
//so that user cant go back to login activyty upon pressing
//back button
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
Toast.makeText(getApplicationContext(),"Logged in successfully",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
and here is the signUp method:
public void userRegistration(){
String userEmail = etSignupEmail.getText().toString().trim();
String userPassword = etSignupPassword.getText().toString().trim();
//validation
if(userEmail.isEmpty()){
etSignupEmail.setError("Email is required");
//et is focused
etSignupEmail.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
etSignupEmail.setError("Invalid email address");
//focus et
etSignupEmail.requestFocus();
return;
}
if(userPassword.isEmpty()){
etSignupPassword.setError("Password is required");
//et is focused
etSignupPassword.requestFocus();
return;
}
if(userPassword.length()<6){
etSignupPassword.setError("Password length should be atleast 6 characters");
//request focus
etSignupPassword.requestFocus();
return;
}
//showing progressbar upon regisration process lifetime
progressBar.setVisibility(View.VISIBLE);
//calling firebase register users methods via mAuth instance
mAuth.createUserWithEmailAndPassword(userEmail,userPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//changing visibility of progress bar to gone upon registration
progressBar.setVisibility(View.GONE);
//checking if the process was successful
//using this task obj
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"user registered successfully", Toast.LENGTH_SHORT).show();
}else{
//this line checks whether the email is already registered or not
//using the task obj and FirebasesuthUSerCollisonException
if(task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(getApplicationContext(),"email already exists",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
});
}
I cannot figure what has gone wrong. Help is appreciated. Thanks
You're trying to read from /users here:
mDatabase.child("users").orderByChild(userId).addValueEventListener(new ValueEventListener() {
But your rules only gives a user access to /users/$uid. Since the user doesn't have read permission on /users, the listener gets rejected.
If you want to read the user's own data, read that specific child node:
mDatabase.child("users").child(userId).addValueEventListener(new ValueEventListener() {
Now since the user has read permission to their own node, the listener will be allowed.
Make sure app name and client id are same as in firebase console.
If you are not sure re-download google-services.json from your project's console and add it your project.
and also change your rules during development and testing period to this
{
"rules": {
".read": true,
".write": true
}
}

One time login in app - FirebaseAuth

I'm working on an app that uses Firebase authentication to sign in users through phone number. I want to add a functionality such that there is only one-time login for the user, i.e. even if the user kills the app and starts it again, he should be logged in. Also, I don't want to add a logout feature. What can be done for this?
The simplest way to achieve this is to use a listener. Let's assume you have two activities, the LoginActivity and the MainActivity. The listener that can be created in the LoginActivity should look like this:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
};
This basically means that if the user is logged in, skip the LoginActivity and go to the MainActivity.
Instantiate the FirebaseAuth object:
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
And start listening for changes in your onStart() method like this:
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}
In the MainActivity, you should do the same thing:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
Which basically means that if the user is not logged in, skip the MainActivity and go to the LoginActivity. In this activity you should do the same thing as in the LoginActivity, you should start listening for changes in the onStart().
In both activities, don't forget to remove the listener in the moment in which is not needed anymore. So add the following line of code in your onStop() method:
#Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(authStateListener);
}
You can save user login session in shared Preference
Do this when your login got Login Success
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", Activity.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.commit();
and When Your apps is Starts (like Splash or login Page) use this
SharedPreferences sp=this.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
boolean b = sp.getBoolean("key_name", false);
if(b==true){
//User Already Logged in skip login page and continue to next process
}else{
//User is Not logged in, show login Form
}
It will works for you.
This is from my working code from logging class:
private void LoginUserAccount(String email, String password)
{
if (TextUtils.isEmpty(email))
{
Toast.makeText(ResponseStartPage.this, "Please write Your Email", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(ResponseStartPage.this, "Please write Your password", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Login Account");
loadingBar.setMessage("Please wait for verification...");
loadingBar.show();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if (task.isSuccessful())
{
String online_user_id = mAuth.getCurrentUser().getUid();
String DeviceToken = FirebaseInstanceId.getInstance().getToken();
usersReference.child(online_user_id).child("device_token").setValue(DeviceToken)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid)
{
Intent mainIntent = new Intent(ResponseStartPage.this, ResponseMainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
});
}
else
{
Toast.makeText(ResponseStartPage.this, "Please Check your email and password", Toast.LENGTH_SHORT).show();
}
loadingBar.dismiss();
}
});
}
}

Using Login Authentication on more than one device - Android App [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm having difficulty understanding something with my app.
I am using Firebase to provide user authentication which works fine until I try it on other phones/devices.
When I put in the email and password and press 'Login', the app crashes and the log gives the following:
FATAL EXCEPTION: main Process: com.example.android.frapp, PID: 14822
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.android.gms.common.api.GoogleApi.zzb(com.google.android.gms.common.api.internal.zzdf)' on a null object reference
at com.google.android.gms.internal.zzdtp.zzb(Unknown Source)
at com.google.android.gms.internal.zzdtw.zzb(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source)
at com.example.android.frapp.MainLoginActivity.startSiginIn(MainLoginActivity.java:105)
at com.example.android.frapp.MainLoginActivity.access$000(MainLoginActivity.java:23)
at com.example.android.frapp.MainLoginActivity$2.onClick(MainLoginActivity.java:65)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20926)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
It's all happening from my main login class (which I have provided below):
public class MainLoginActivity extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private Button mLoginBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private boolean isUserClickedBackButton = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_login);
mAuth = FirebaseAuth.getInstance();
mEmailField = (EditText) findViewById(R.id.emailField);
mPasswordField = (EditText) findViewById(R.id.passwordField);
mLoginBtn = (Button) findViewById(R.id.loginBtn);
// connection to user authentication on firebase (database)
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null){
startActivity(new Intent(MainLoginActivity.this, MainActivity.class));
}
}
};
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSiginIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
// code for exiting from app by using back button on login page
public void onBackPressed() {
//moveTaskToBack(true);
if (!isUserClickedBackButton){
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
isUserClickedBackButton = true;
} else {
System.exit(0); // exits right out of app
super.onBackPressed();
}
}
// for login
private void startSiginIn() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
Toast.makeText(MainLoginActivity.this, "Please input email and password", Toast.LENGTH_LONG).show();
} else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful())
Toast.makeText(MainLoginActivity.this, "Sign in problem. Please check email" +
" and password", Toast.LENGTH_LONG).show();
}
});
}
}
}
As I say, it works perfect on my main device but doesn't when I install and try to login on other devices. And it also works fine on the emulator.
I've tried searching for similar problems but can't find any.
Has anyone got any ideas?
Thanks
If your authentication process works fine on your phone/emulator but you get that error when testing on another device it means that most likely that device does not have Google Play Services installed. Make sure it is installed correctly and try again.

Categories

Resources