Keep User logged in Java Firebase - java

I am trying to keep the user logged into my chat app even after they close the app. So the only way they will be logged out of their account is if they click the log out button.
So far the user does stayed logged in but when I click the log out button, the app crashes. This is the error I get
Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.example.chatterbox.ChatsFragment.onCreateView(ChatsFragment.java:54)
the problem is that that error is from a different file. Can someone please help me ?
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private Button LoginButton ;
private EditText UserEmail, UserPassword;
private TextView NeedNewAccountLink, ForgetPasswordLink;
private DatabaseReference UsersRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
RelativeLayout relativeLayout = findViewById(R.id.layout);
AnimationDrawable animationDrawable = (AnimationDrawable) relativeLayout.getBackground();
animationDrawable.setEnterFadeDuration(5000);
animationDrawable.setExitFadeDuration(5000);
animationDrawable.start();
mAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
InitializeFields();
if (UsersRef != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
NeedNewAccountLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToRegisterActivity();
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AllowUserToLogin();
}
});
}
private void AllowUserToLogin () {
String email = UserEmail.getText().toString();
String password = UserPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show();
} else {
loadingBar.setTitle("Logging In");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String currentUserId = mAuth.getCurrentUser().getUid();
String deviceToken = FirebaseInstanceId.getInstance().getToken();
UsersRef.child(currentUserId).child("device_token")
.setValue(deviceToken)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(LoginActivity.this, "Logged in successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
} else {
String message = task.getException().toString();
Toast.makeText(LoginActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void InitializeFields () {
LoginButton = (Button) findViewById(R.id.login_button);
UserEmail = (EditText) findViewById(R.id.login_email);
UserPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccountLink = (TextView) findViewById(R.id.need_new_account_link);
ForgetPasswordLink = (TextView) findViewById(R.id.forget_password_link);
loadingBar = new ProgressDialog(this);
}
private void SendUserToMainActivity () {
Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
private void SendUserToRegisterActivity () {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerIntent);
}
Error line :
currentUserID = mAuth.getCurrentUser().getUid();
This is how I check if the user is logged in. If they are I send them to the MainActivity. If they are not they stay on the LoginActivity
if (UsersRef != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}

You call
mAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
and then
if (UsersRef != null) {
//do something
}
It's a bit odd because you need to know if there's currently a valid user logged in Firebase. This snippet maybe can be useful:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
} else {
// No user is signed in
}
But you're checking if the variable UsersRef (that is a DatabaseReference, i guess) is null or not... Indeed you just gived it a value!!!

Use addOnSuccessListener instead of addOnCompleteListener
auth.signInWithEmailAndPassword(mEmail, mPassword)
.addOnSuccessListener(LoginActivity.this, new OnSuccessListener<AuthResult>(){
#Override
public void onsuccess(#NonNull AuthResult authResult){
//your code goes here
}
});

Related

Retrieve current logged in user's data from Firestore

I've tried out many times, still couldn't display current logged in data of a user. I would like to fetch the data from Firestore database to the user's profile page but it keep blank.
Here's my register.java:
public class Register extends AppCompatActivity {
//Variables
TextInputLayout username, email, PhoneNo, password;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
//Hooks to all xml elements in activity_register.xml
username = findViewById(R.id.reg_username);
email = findViewById(R.id.reg_email);
PhoneNo = findViewById(R.id.reg_phoneNo);
password = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regToLoginBtn = findViewById(R.id.reg_login_btn);
radioGroup = findViewById(R.id.radio_type);
selectedGuardian = findViewById(R.id.radioGuardian);
selectedElderly = findViewById(R.id.radioElderly);
regToLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
}
});
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
} else {
validateUsername();
validateEmail();
validatePhoneNo();
validateUserType();
validatePassword();
}
fAuth.createUserWithEmailAndPassword(email.getEditText().getText().toString(), password.getEditText().getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
FirebaseUser user = fAuth.getCurrentUser();
Toast.makeText(Register.this, "Account Created", Toast.LENGTH_SHORT).show();
DocumentReference df = fStore.collection("Users").document(user.getUid());
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("Username", username.getEditText().getText().toString());
userInfo.put("Email", email.getEditText().getText().toString());
userInfo.put("phoneNo", PhoneNo.getEditText().getText().toString());
userInfo.put("Password",password.getEditText().getText().toString());
//specify the user is elderly
if (selectedElderly.isChecked()) {
userInfo.put("isElderly", "1");
}
if (selectedGuardian.isChecked()) {
userInfo.put("isGuardian", "1");
}
df.set(userInfo);
if (selectedElderly.isChecked()) {
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
if (selectedGuardian.isChecked()) {
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, "Failed to Create Account", Toast.LENGTH_SHORT).show();
}
});
}
Here's profile.java:
public class profileGuardian extends AppCompatActivity {
TextInputLayout username, email, PhoneNo, password, address;
TextView usernameLabel, emailLabel;
Button save;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_guardian);
//Hooks
username = findViewById(R.id.full_name_profile);
email = (TextInputLayout) findViewById(R.id.email_profile);
PhoneNo = (TextInputLayout) findViewById(R.id.phoneNo_profile);
password = (TextInputLayout) findViewById(R.id.password_profile);
address = (TextInputLayout) findViewById(R.id.address_profile);
emailLabel = (TextView) findViewById(R.id.email_field);
usernameLabel = (TextView) findViewById(R.id.username_field);
save = findViewById(R.id.save_btn);
getData();
}
private void getData() {
fStore = FirebaseFirestore.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String current = user.getUid();//getting unique user id
fStore.collection("Users")
.whereEqualTo("uId", current)//looks for the corresponding value with the field
// in the database
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
emailLabel.setText((CharSequence) document.get("Email"));
usernameLabel.setText((CharSequence) document.get("Username"));
username.getEditText().setText((CharSequence) document.get("Username"));
email.getEditText().setText((CharSequence) document.get("Email"));
PhoneNo.getEditText().setText((CharSequence) document.get("phoneNo"));
password.getEditText().setText((CharSequence) document.get("Password"));
}
}
}
});
}
Here's my database structure:
I've tried multiple solution on Youtube but keep failed..
In the presented code get method returns results of type QuerySnapshot (reference). I think that task.getResult() will get QuerySnapshot object not list of documents, so the loop is not working properly.
According to reference for statement should be something like this instead:
for (DocumentSnapshot document : task.getResult().getDocuments())
than it should be possible to iterate over list of documents included in QuerySnapshot.

Multiple Auth Providers Android Firebase

I have LoginActivity with Email/password login, facebook, google authentication. It works separately but if I create account with google, I can't login with facebook.
Login activity code:
public class LoginActivity extends AppCompatActivity {
private Button mLogin,mRegister;
private int RC_SIGN_IN =0;
private EditText mEmail, mPassword;
public FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
CallbackManager callbackManager;
private LoginButton loginButton;
private static final String EMAIL = "email";
private TextView facebookRegister;
private SignInButton googleSignIn;
GoogleSignInClient mGoogleSignInClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Intent intent = new Intent(LoginActivity.this, LoginTest.class);
startActivity(intent);
//FACEBOOK
mAuth = FirebaseAuth.getInstance();
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(getApplication());
callbackManager = CallbackManager.Factory.create();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
googleSignIn = findViewById(R.id.sign_in_button);
googleSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
// ...
}
}
});
firebaseAuthStateListener= new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user !=null){
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
}
};
loginButton = findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList(EMAIL));
mLogin = (Button) findViewById(R.id.login);
mEmail = (EditText) findViewById(R.id.email);
mPassword=(EditText) findViewById(R.id.password);
mRegister=(Button)findViewById(R.id.register);
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
handleFacebookToken(loginResult.getAccessToken());
//fill database
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logInEmailPassword();
}
});
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegistrationActivity.class);
startActivity(intent);
finish();
return;
}
});
}
#Override
protected void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
mAuth.addAuthStateListener(firebaseAuthStateListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthStateListener);
}
private void logInEmailPassword() {
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if(email.isEmpty()){
Toast.makeText(LoginActivity.this, "Wrong email", Toast.LENGTH_SHORT).show();
mEmail.setError("Enter email!");
};
if(password.isEmpty()){
mPassword.setError("Enter password!");
Toast.makeText(LoginActivity.this, "Wrong password", Toast.LENGTH_SHORT).show();
}
if(!email.isEmpty() && !password.isEmpty()){
AuthCredential credential = EmailAuthProvider.getCredential(email, password);
linkWithCredential(credential);
}
}
private void handleFacebookToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
linkWithCredential(credential);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
// 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.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
FirebaseGoogleAuth(account);
// Signed in successfully, show authenticated UI.
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w("myLog", "signInResult:failed code=" + e.getStatusCode());;
}
}
private void FirebaseGoogleAuth(GoogleSignInAccount account) {
AuthCredential authCredential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
linkWithCredential(authCredential);
}
private void linkWithCredential(AuthCredential credential){
mAuth = FirebaseAuth.getInstance()
//mAuth.getCurrentUser().linkWithCredential(credential)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("myLog", "linkWithCredential:success");
FirebaseUser user = task.getResult().getUser();
updateUI(user);
} else {
Log.w("myLog", "linkWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
LoginManager.getInstance().logOut();
updateUI(null);
}
// ...
}
});
}
}
I've followed https://firebase.google.com/docs/auth/android/account-linking?authuser=0 tutorial but I stuck at linkWithCredential.
Can you help me fix that issue? Thanks
The problem if that user exists in Firebase Authentication already and is assigned to GoogleAuth i cant login with Facebook.
It works vice versa, if facebook user exists in firebase and i login with google it overrides that user.
Register ---- logout ---- login
Google --->>>>>>>>>>>>>>>>Facebook >>>>dont work
Facebook--->>>>>>>>>>>>>>>Google >>>>> works

The authentification firebase remember me after logout

I enter my main activity, inside the MainActivity I have registration, after the registartion accure I want to log out from firebase so that he doesn't remember me.
Because when I retured to the MainActivity after the signout he still remembers the previous user when I register as a new user. This occurs only after logging and logout immediately. Btw, if I run the app its working fine. The problem is only when I signout and then going to RegistrationActivity to register another user.
Here is the MainActivity code:
public class MainActivity extends AppCompatActivity {
private SignInButton signIn;
private int RC_SIGN_IN=1;
private GoogleSignInClient mGoogleSignInClient;
private String TAG = "MainActivity";
private FirebaseAuth mAuth;
private Button registration;
private EditText email;
private EditText password;
private Button login;
private BottomNavigationView bottomNavigationItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = (SignInButton)findViewById(R.id.sign_in_button);
mAuth = FirebaseAuth.getInstance();
registration = (Button) findViewById(R.id.registrate);
email = (EditText)findViewById(R.id.email);
password = (EditText)findViewById(R.id.password);
login = (Button)findViewById(R.id.login);
bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;
bottomNavigationItemView.getMenu().getItem(0).setChecked(true);
bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.register_menu: {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
break;
}
}
return true;
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
registration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_text = email.getText().toString().trim();
String password_text = password.getText().toString().trim();
if(TextUtils.isEmpty(email_text) || TextUtils.isEmpty(password_text))
{
Toast.makeText(MainActivity.this, "One or more fields are empty", Toast.LENGTH_LONG).show();
}
else
{
mAuth.signInWithEmailAndPassword(email_text, password_text).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful())
{
Toast.makeText(MainActivity.this, "Sign in problem", Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent(MainActivity.this, AccountActivity.class);
startActivity(intent);
}
}
});
}
}
});
}
private void signIn() { /*Sign in to the app with Google Account*/
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 GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try{
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
}
catch(ApiException e){
Log.w(TAG, "Google Sin in Failed");
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct)
{
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
Log.d(TAG, "signInWithCredential: success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
}
else
{
Log.w(TAG, "signInWithCredential: failure", task.getException()); /*In case of unsuccessful login*/
Toast.makeText(MainActivity.this, "You are not able to log in to Google", Toast.LENGTH_LONG).show();
//updateUI(null);
}
}
});
}
private void updateUI(FirebaseUser user) /*In case of successful registration*/
{
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (acct != null) {
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Toast.makeText(this, "Name of User : " + personName + "UserId is : " + personId, Toast.LENGTH_LONG);
Intent intent = new Intent(this, AccountActivity.class);
intent.putExtra("personPhoto", personPhoto.toString());
startActivity(intent);
}
}
Here is the AccountActivity code:
public class AccountActivity extends AppCompatActivity {
private GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private CardView signOut;
private CardView ratingTable;
private CardView settings;
private CardView map;
private CardView favoritePlaces;
DatabaseReference databaseReference;
FirebaseDatabase database;
List<User> users;
CollapsingToolbarLayout collapsingToolbarLayout;
String photoString="No photo";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
mAuth = FirebaseAuth.getInstance();
signOut = (CardView) findViewById(R.id.logout);
ratingTable = (CardView) findViewById(R.id.rating);
settings = (CardView)findViewById(R.id.settings);
map = (CardView) findViewById(R.id.map);
favoritePlaces = (CardView)findViewById(R.id.favorite);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference();
users = new ArrayList<User>();
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collaps);
if(mAuth.getCurrentUser().getDisplayName()!=null)
{
Intent i = getIntent();
photoString = i.getStringExtra("personPhoto");
}
databaseReference.child("user").addValueEventListener(new ValueEventListener() { /*A new user is registered in the database*/
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child : children) {
User user = child.getValue(User.class);
users.add(user);
}
if (!findUser()) /*If the user is not found, this is a new user and must be registered*/
addUser();
showName(); /*A user-specific message*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mAuth.getCurrentUser().getDisplayName()!=null)
{
mGoogleSignInClient.signOut();
//Intent intent = new Intent(AccountActivity.this, MainActivity.class);
// startActivity(intent);
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
else
{
mAuth.signOut();
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
map.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, MapsActivity.class);
startActivity(intent);
}
});
favoritePlaces.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, favoritePlacesActivity.class);
startActivity(intent);
}
});
ratingTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, RatingTableActivity.class);
startActivity(intent);
}
});
}
private void showName() /*A user-specific message*/
{
String name = "";
String userId = mAuth.getUid();
for (User tmpUser : users) {
if (userId.equals(tmpUser.getUserId()))
{
name = tmpUser.getUserName();
break;
}
}
collapsingToolbarLayout.setTitle("Hi " + name);
}
private boolean findUser() /*Check if a logged-on user is already registered in the database*/
{
FirebaseUser user = mAuth.getCurrentUser();
String userId = mAuth.getUid();
for (User tmpUser : users) {
if (userId.equals(tmpUser.getUserId())) {
return true;
}
}
return false;
}
private void addUser() /*In case of registration from Google Account*/
{
String userId = mAuth.getUid();
if(mAuth.getCurrentUser().getDisplayName()!=null) /*In case of registration not from Google Account*/
{
databaseReference = FirebaseDatabase.getInstance().getReference("user");
FirebaseUser user = mAuth.getCurrentUser();
String userName = user.getDisplayName();
User newUser = User.getInstance(userId, userName, photoString);
databaseReference.child(userId).setValue(newUser);
}
else /*If the user is not registered the function registers it in the database*/
{
databaseReference = FirebaseDatabase.getInstance().getReference("user");
Intent i = getIntent();
String firstName = i.getStringExtra("firstName");
String lastName = i.getStringExtra("lastName");
User newUser = User.getInstance(userId, firstName + " " + lastName, photoString);
databaseReference.child(userId).setValue(newUser);
}
}
RegistrationActivity code:
public class RegistrationActivity extends AppCompatActivity {
EditText email_text;
EditText pass1;
EditText pass2;
EditText first;
EditText last;
Button registrate;
FirebaseAuth mAuth;
private ProgressDialog progressDialog;
private BottomNavigationView bottomNavigationItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
mAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
email_text = (EditText)findViewById(R.id.email);
pass1 = (EditText)findViewById(R.id.password1);
pass2 = (EditText)findViewById(R.id.password2);
first = (EditText)findViewById(R.id.first_name);
last = (EditText)findViewById(R.id.last_name);
registrate = (Button)findViewById(R.id.registrate);
bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;
bottomNavigationItemView.getMenu().getItem(1).setChecked(true);
bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.Signin_menu: {
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
break;
}
}
return true;
}
});
registrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = email_text.getText().toString().trim();
String password1 = pass1.getText().toString().trim();
String password2 = pass2.getText().toString().trim();
final String first_name = first.getText().toString().trim();
final String last_name = last.getText().toString().trim();
boolean correctFlag=true;
/*All tests for input integrity*/
if(!password1.equals(password2))
{
Toast.makeText(RegistrationActivity.this, "The password does not match", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(password1.equals("") && password2.equals(""))
{
Toast.makeText(RegistrationActivity.this, "No password entered", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(email.equals("") || first_name.equals("") || last_name.equals(""))
{
Toast.makeText(RegistrationActivity.this, "One or more of the parameters are incorrect", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(correctFlag) /*There is no problem filling the fields*/
{
progressDialog.setMessage("Registrating user...");
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email, password1).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Toast.makeText(RegistrationActivity.this, "Registered Succesfully", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
Intent intent = new Intent(RegistrationActivity.this, AccountActivity.class);
intent.putExtra("firstName", first_name);
intent.putExtra("lastName", last_name);
startActivity(intent);
}
else
{
Toast.makeText(RegistrationActivity.this, "could not register. please try again", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
}
}
});
}
}
});
}
You need to log out of GoogleSignInClient :
public void signOut() {
signOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(getContext(), gso);
mGoogleSignInClient.signOut();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getContext(), LoginActivity.class));
}
});
}

Firebase NullPointException when logging in

Hello im trying to create a firebase logging in auth with 2 different users, the admin, and user. but like when i was trying to log in, The application would crash. Heres the error i think
my database
and here is my code on the login
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
auth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//db
mFirebaseInstance = FirebaseDatabase.getInstance();
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, signup.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.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() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
onAuthSuccess(task.getResult().getUser());
}
}
private void onAuthSuccess(FirebaseUser user) {
if (user !=null){
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid()).child("type");
mFirebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
if(Integer.parseInt(value) == 1) {
startActivity(new Intent(LoginActivity.this, UserActivity.class));
Toast.makeText(LoginActivity.this, "Welcome User", Toast.LENGTH_SHORT).show();
finish();
}else {
startActivity(new Intent(LoginActivity.this, AdminActivity.class));
Toast.makeText(LoginActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
});
}
I feel like the problem lies on the ondata change one but I don't know what to do to fix this, so im asking for your help :O
Try this:
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(user.getUid());
mFirebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.child("type").getValue(String.class);
if(Integer.parseInt(value) == 1) {
startActivity(new Intent(LoginActivity.this, UserActivity.class));
Toast.makeText(LoginActivity.this, "Welcome User", Toast.LENGTH_SHORT).show();
finish();
}else {
startActivity(new Intent(LoginActivity.this, AdminActivity.class));
Toast.makeText(LoginActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
finish();
}
}
try the above, have the reference at the userid then inside onDataChange retrieve the type. you need to reference in order and specify the child name like this:
String value = dataSnapshot.child("type").getValue(String.class);

Firebase database entry is only created when breakpoint is set in Android Studio

I have the following SignUp Activity that does not work properly: after the user receives the verification email and tries to sign in, the app crashes with a NullPointerException, as a new user entry in Firebase Realtime Database is not created. I noticed, though, during debugging, that if I set a breakpoint at where generateUser() is defined, a new database entry is created (the app crashes the same way, though).
What could be the solution here?
Any help would be highly appreciated.
Update: The emphasis here is not on NullPointerException, I can handle that. The question is why generateUser() is not being called.
public class SignUpActivity extends AppCompatActivity {
private EditText inputUsername, inputEmail, inputPassword;
private Button btnSignIn, btnSignUp;
private ProgressBar progressBar;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
if (user.isEmailVerified()) {
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
finish();
}
}
setContentView(R.layout.activity_sign_up);
btnSignIn = findViewById(R.id.sign_in_button);
btnSignUp = findViewById(R.id.sign_up_button);
inputUsername = findViewById(R.id.username);
inputEmail = findViewById(R.id.email);
inputPassword = findViewById(R.id.password);
progressBar = findViewById(R.id.progressBar);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignUpActivity.this, SignInActivity.class));
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = inputUsername.getText().toString().trim();
final String email = inputEmail.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (TextUtils.isEmpty(username)) {
Toast.makeText(getApplicationContext(), "Enter username!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
} else {
new GenerateUserAsyncTask().execute(username, email, password, 0);
}
}
});
}
class GenerateUserAsyncTask extends AsyncTask<Object, Void, Void> {
#Override
protected Void doInBackground(Object... params) {
String username = (String) params[0];
String email = (String) params[1];
String password = (String) params[2];
int score = (int) params[3];
generateUser(username, email, password, score);
return null;
}
#Override
protected void onPostExecute(Void result) {
sendVerificationEmail();
}}
});
}
public void sendVerificationEmail() {
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Signup successful, verification email sent", Toast.LENGTH_SHORT).show();
auth.signOut();
startActivity(new Intent(SignUpActivity.this, SignInActivity.class));
finish();
} else {
Toast.makeText(SignUpActivity.this, "Failed to send email!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
});
}
}
public void generateUser(String username, String email, String password, int score) {
FirebaseDatabase database = Utils.getDatabase();
DatabaseReference users = database.getReference("users");
User user = new User(username, email, password, score);
users.child(auth.getUid()).setValue(user);
}
}
I have found the solution. The problem is caused by the Realtime Database security rules: they only allow users to write to the database if they are authenticated. In my code, though, where generateUser() is called, users are not fully authenticated yet. So I need to generate new entries in the database after the user has clicked on the link in the verification email.

Categories

Resources