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));
}
});
}
Related
I need to get
FirebaseAuth.getInstance().getCurrentUser()
from a second activity "DetailActivity" but i've got a Null pointer :
Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
I can access it from the "MainActivity" but not from my bottomnavigationview fragments nor from the second activity "DetailActivity"
here is my code :
Connexion activity
public class ConnexionActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = ActivityConnexionBinding.inflate(getLayoutInflater());
setContentView(mBinding.getRoot());
mAuth = FirebaseAuth.getInstance();
setGoogleSignIn();
}
//////////////////////GOOGLE LOGIN
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// GOOGLE
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> mAccountTask = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = mAccountTask.getResult(ApiException.class);
FirebaseAuthWithGoogleAccount(account);
} catch (ApiException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "OnClick: ERROR ACTIVITY RESULT NOT OK");
}
// FACEBOOK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void FirebaseAuthWithGoogleAccount(GoogleSignInAccount account) {
Log.d(TAG, "firebaseauthwithgoogleaccount: begin firebase auth with google account");
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Log.d(TAG, "OnSuccess: Logged in");
// Get logged in user
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
// Get user info
String uid = firebaseUser.getUid();
String email = firebaseUser.getEmail();
Log.d(TAG, "OnSuccess: Email" + email);
Log.d(TAG, "OnSuccess: uid" + uid);
// Check if user is new or existing
if (Objects.requireNonNull(authResult.getAdditionalUserInfo()).isNewUser()) {
// User is new account created
Log.d(TAG, "OnSuccess: Account created...\n" + email);
Toast.makeText(ConnexionActivity.this, "Account created...\n" + email, Toast.LENGTH_SHORT).show();
} else {
// Existing user logged in
Log.d(TAG, "OnSuccess: Existing user... \n" + email);
Toast.makeText(ConnexionActivity.this, "Existing user...\n" + email, Toast.LENGTH_SHORT).show();
}
// Start MainActivity
startActivity(new Intent(ConnexionActivity.this, MainActivity.class));
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "OnFailure: Loggin failed" + e.getMessage());
}
});
}
private void setGoogleSignIn() {
// Configure google sign in
GoogleSignInOptions mGoogleSignInOption = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.requestidtoken))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, mGoogleSignInOption);
// Init firebase auth
mAuth = FirebaseAuth.getInstance();
}
//////////////////////GOOGLE END
FirebaseAuth.AuthStateListener mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//Start main activity
startActivity(new Intent(ConnexionActivity.this, MainActivity.class));
Toast.makeText(ConnexionActivity.this,
"You successfully signed-in ", Toast.LENGTH_SHORT).show();
finish();
}
}
};
// #Override
// protected void onDestroy() {
//
// // FIREBASE LOGOUT
// FirebaseAuth.getInstance().signOut();
// // GOOGLE LOGOUT
// GoogleSignInOptions gso = new GoogleSignInOptions.
// Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).
// build();
//
// GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(ConnexionActivity.this, gso);
// googleSignInClient.signOut();
// // FACBOOK LOGOUT
// LoginManager.getInstance().logOut();
// super.onDestroy();
// }
MainActivity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = ActivityMainBinding.inflate(getLayoutInflater());
View view = mBinding.getRoot();
setContentView(view);
mAuth = FirebaseAuth.getInstance();
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
reload();
}
}
// restart connexion activity if the user isn't connected
private void reload(){
startActivity(new Intent(this, ConnexionActivity.class));
finish();
}
private void setBottomNavigationView(){
mBinding.bottomNavigation.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(mBinding.fragmentContainer.getId(), new MapFragment()).commit();
}
private final BottomNavigationView.OnNavigationItemSelectedListener navListener = item -> {
Fragment selectedFragment = null;
int itemId = item.getItemId();
if (itemId == R.id.map_view) {
selectedFragment = new MapFragment();
} else if (itemId == R.id.list_view) {
selectedFragment = new ListViewFragment();
} else if (itemId == R.id.workmates) {
selectedFragment = new WorkmatesFragment();
}
if (selectedFragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
}
return true;
};
The fragment adapter where i launch the DetailActivity :
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final Result restaurant = mRestaurants.get(position);
((ListViewViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("idrestaurant", restaurant.getPlaceId());
context.startActivity(intent);
}
});
}
}
DetailActivty :
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = ActivityDetailBinding.inflate(getLayoutInflater());
View view = mBinding.getRoot();
setContentView(view);
}
private void setClickChosenRestaurantButton(){
mBinding.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
Map<String, Object> chosenRestaurant = new HashMap<>();
chosenRestaurant.put("restaurantChosen", getRestaurantId());
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DocumentReference docRef = UserCallData.getAllUsers().getFirestore().collection("users").document(firebaseUser.getUid());
docRef.set(chosenRestaurant, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d("123", "DocumentSnapshot successfully written!");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("123", "Error writing document", e);
}
});
}
else {
Log.d("123", "pb with firebaseauth!");
}
}
});
}
}
D/123: pb with firebaseauth!
To be honest i do not understand in detail the behavior of the Firebase auth system that's why i'm stuck here.
Any idea?
I found out why it doesn't work :
#Override
protected void onDestroy() {
// FIREBASE LOGOUT
FirebaseAuth.getInstance().signOut();
// GOOGLE LOGOUT
GoogleSignInOptions gso = new GoogleSignInOptions.
Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).
build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(ConnexionActivity.this, gso);
googleSignInClient.signOut();
// FACBOOK LOGOUT
LoginManager.getInstance().logOut();
super.onDestroy();
}
In my ConnectionActivity
This disconnected my FirebaseUser when i destroyed ConnexionActivity after each connexion of the user.
I switch it to my MainActivity which isn't destroyed until the app crash or the user forces it to close.
Email login activity allows user to log in to his account. here , after the user is logged in , he will be sent to main activity using the main activity intent. here as soon as the user is logged in to the account , he is sent to main activity , and the main activity is restating continously . the screen recording video is uploaded in the link mentioned "https://drive.google.com/file/d/1QRy2J1YkMRJdbjgMIIl-T58DsGnamtGX/view?usp=sharing"
here is the "LOGCAT"
1650989781.030 22200-22200/com.example.indiatalks V/FA: onActivityCreated
1650989781.184 22200-22231/com.example.indiatalks D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=9033321453691971948, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=9033321453691971949}]
1650989781.193 22200-22200/com.example.indiatalks I/InputTransport: Create ARC handle: 0x7d16279460
1650989781.263 22200-22231/com.example.indiatalks V/FA: Activity resumed, time: 629575044
1650989781.437 22200-22231/com.example.indiatalks V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 264
1650989781.439 22200-22231/com.example.indiatalks V/FA: Activity paused, time: 629575308
1650989781.678 22200-22779/com.example.indiatalks D/libMEOW: applied 1 plugins for [com.example.indiatalks]:
1650989781.678 22200-22779/com.example.indiatalks D/libMEOW: plugin 1: [libMEOW_gift.so]:
1650989781.687 22200-22200/com.example.indiatalks V/FA: onActivityCreated
1650989781.777 22200-22225/com.example.indiatalks I/mple.indiatalk: Waiting for a blocking GC ProfileSaver
1650989781.830 22200-22231/com.example.indiatalks D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=9033321453691971949,
public class MainActivity extends AppCompatActivity {
private ImageButton AddNewPostButton, ChatListButton;
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
private DatabaseReference RootRef, PostsRef;
private ProgressDialog loadingBar;
public ImageButton selectPostButton;
private Button UpdatePostButton, WritePost;
private EditText PostDescription;
private static final int GalleryPick = 100;
private Uri ImageUri;
private String checker = "";
private String Description;
private StorageReference PostsReference;
private DatabaseReference UsersRef;
private String saveCurrentDate, saveCurrentTime, postRandomName, downloadurl, currentUserid, userName;
private Toolbar mToolbar;
private CircleImageView navProfileImage;
private TextView navUserName;
private ActionBarDrawerToggle actionBarDrawerToggle;
private ViewPager myNewsFeedViewpager;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private BottomNavigationView BottomNavMenu;
private RecyclerView postsLists;
private RecyclerView.LayoutManager newsFeedsLinearlayoutManager;
private PostsAdapter postsAdapter;
private final List < Posts > postsArraylist = new ArrayList < > ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
RootRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsReference = FirebaseStorage.getInstance().getReference();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.explore_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Boww Talks");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (currentUser == null) {
SendUserToLoginActivity();
} else {
updateUserStatus("online");
VerifyUserExistence();
}
IntializeControllers();
drawerLayout = (DrawerLayout) findViewById(R.id.drawyer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navProfileImage = (CircleImageView) navView.findViewById(R.id.nav_profile_image);
navUserName = (TextView) navView.findViewById(R.id.nav_profile_name);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem Item) {
NavMenuSelector(Item);
return false;
}
});
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.ic_home)
{
return true;
}
if (menuItem.getItemId() == R.id.ic_search)
{
Intent FindFriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
overridePendingTransition(0, 0);
startActivity(FindFriendsIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_addpost)
{
Intent MyaddPostIntent = new Intent(MainActivity.this, addPostActivity.class);
overridePendingTransition(0, 0);
startActivity(MyaddPostIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_alert)
{
Intent NotificationIntent = new Intent(MainActivity.this, NotificationActivity.class);
overridePendingTransition(0, 0);
startActivity(NotificationIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_profile)
{
Intent MyProfileIntent = new Intent(MainActivity.this, settingsActivity.class);
overridePendingTransition(0, 0);
startActivity(MyProfileIntent);
return true;
}
return false;
}
});
BottomNavMenu.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
#Override
public void onNavigationItemReselected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.ic_home)
{
Intent MyMainIntent = new Intent(MainActivity.this, MainActivity.class);
overridePendingTransition(0, 0);
startActivity(MyMainIntent);
}
if (menuItem.getItemId() == R.id.ic_search)
{
Intent FindFriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
overridePendingTransition(0, 0);
startActivity(FindFriendsIntent);
}
if (menuItem.getItemId() == R.id.ic_addpost)
{
Intent addPostIntent = new Intent(MainActivity.this, addPostActivity.class);
overridePendingTransition(0, 0);
startActivity(addPostIntent);
}
if (menuItem.getItemId() == R.id.ic_alert)
{
}
}
});
ChatListButton = (ImageButton) findViewById(R.id.chat_list_button);
ChatListButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Intent = new Intent(MainActivity.this, ChatListActivity.class);
startActivity(Intent);
}
});
}
#Override
protected void onRestart() {
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
super.onRestart();
}
private void NavMenuSelector(MenuItem Item) {
switch (Item.getItemId()) {
case R.id.BirthDays:
Toast.makeText(this, "Birthdays selected", Toast.LENGTH_SHORT).show();
break;
case R.id.shortClips:
Toast.makeText(this, "Short Clips selected", Toast.LENGTH_SHORT).show();
break;
case R.id.short_Films:
Toast.makeText(this, "ShortFilms selected", Toast.LENGTH_SHORT).show();
break;
case R.id.marketing:
Toast.makeText(this, "Marketing selected", Toast.LENGTH_SHORT).show();
break;
case R.id.Find_Friends_option:
Toast.makeText(this, "Find Friends selected", Toast.LENGTH_SHORT).show();
break;
case R.id.my_contacts:
Toast.makeText(this, "My Friends selected", Toast.LENGTH_SHORT).show();
break;
case R.id.privacy_Settings_option:
Toast.makeText(this, "Privacy Settings selected", Toast.LENGTH_SHORT).show();
break;
case R.id.main_Log_Out_option:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
private void IntializeControllers() {
postsAdapter = new PostsAdapter(postsArraylist);
postsLists = (RecyclerView) findViewById(R.id.news_feeds);
postsLists.setHasFixedSize(true);
newsFeedsLinearlayoutManager = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL, false);
postsLists.setLayoutManager(newsFeedsLinearlayoutManager);
postsLists.setAdapter(postsAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStop() {
super.onStop();
if (currentUser != null) {
updateUserStatus("offline");
}
}
private void updateNewsFeeds() {
PostsRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Posts posts = dataSnapshot.getValue(Posts.class);
postsArraylist.add(posts);
postsAdapter.notifyDataSetChanged();
postsAdapter.notifyDataSetChanged();
newsFeedsLinearlayoutManager.scrollToPosition(postsArraylist.size() - 1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
postsAdapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
newsFeedsLinearlayoutManager.scrollToPosition(postsArraylist.size() - 1);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void updateNavMenu() {
currentUserid = currentUser.getUid();
UsersRef.child(currentUserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("profileImage") && (dataSnapshot.hasChild("FullName"))))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("profileImage").getValue().toString();
navUserName.setText(retrieveUserName);
Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profilepic).into(navProfileImage);
} else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("FullName")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
navUserName.setText(retrieveUserName);
} else {
navUserName.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "Set profile NAVIGATION", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void VerifyUserExistence() {
currentUserid = currentUser.getUid();
RootRef.child(currentUserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("profileImage") && (dataSnapshot.hasChild("FullName"))))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("profileImage").getValue().toString();
navUserName.setText(retrieveUserName);
Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profilepic).into(navProfileImage);
updateNavMenu();
updateNewsFeeds();
} else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("FullName")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
updateNavMenu();
updateNewsFeeds();
navUserName.setText(retrieveUserName);
} else if ((dataSnapshot.child("name").exists())) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
navUserName.setText(retrieveUserName);
updateNavMenu();
updateNewsFeeds();
} else {
SendUserTosettingsActivity();
Toast.makeText(MainActivity.this, "Update your profile for settings!!!!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void updateUserStatus(String state) {
String saveCurrentTime, saveCurrentDate;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a");
saveCurrentTime = currentTime.format(calendar.getTime());
HashMap < String, Object > onlineStateMap = new HashMap < > ();
onlineStateMap.put("time", saveCurrentTime);
onlineStateMap.put("date", saveCurrentDate);
onlineStateMap.put("state", state);
currentUserid = currentUser.getUid();
RootRef.child(currentUserid).child("userOnlineState")
.updateChildren(onlineStateMap);
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserTosettingsActivity() {
Intent settingsIntent = new Intent(MainActivity.this, settingsActivity.class);
startActivity(settingsIntent);
}
private void SendUserToFIndFriendsActivity() {
Intent findfriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
startActivity(findfriendsIntent);
}
private void SendUserToMyProfileActivity() {
Intent MyProfileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(MyProfileIntent);
}
}
public class emailloginActivity extends AppCompatActivity
{
private EditText UserEmail,UserPassword;
private TextView ForgotPasswordLink;
private Button LoginButton ,NeedNewAccount;
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private DatabaseReference UsersRef;
private FirebaseUser currentUser;
public emailloginActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emaillogin);
mAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUser = mAuth.getCurrentUser();
LoginButton = (Button) findViewById(R.id.login_button);
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AllowUserToLogin();
}
});
InitializeFields();
NeedNewAccount.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SendUserToRegisterActivity();
}
});
}
#Override
protected void onPause() {
if (loadingBar != null) {
loadingBar.dismiss();
}
super.onPause();
}
private void AllowUserToLogin()
{
String email = UserEmail.getText().toString();
String password = UserPassword.getText().toString();
if (TextUtils.isEmpty(email))
{
Toast.makeText(this, "Please Enter Email", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please Enter Password", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Sign 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())
{
VerifyUserExistence();
Toast.makeText(emailloginActivity.this, "Welcome!!!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else
{
String message = task.getException().toString();
Toast.makeText(emailloginActivity.this, "Roasted!!!: Check the Email Id and Password", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void InitializeFields()
{
UserEmail = (EditText) findViewById(R.id.login_email);
UserPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccount = (Button) findViewById(R.id.Need_new_Account_button);
LoginButton = (Button) findViewById(R.id.login_button);
ForgotPasswordLink = (TextView) findViewById(R.id.Forgot_password);
loadingBar = new ProgressDialog(this);
}
private void VerifyUserExistence ()
{
String userName = mAuth.getCurrentUser().getUid();
UsersRef.child(userName).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists())&& (dataSnapshot.hasChild("name"))) {
SendUserToMain();
loadingBar.dismiss();
finish();
}
else
{
SendUserTosettingsActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserTosettingsActivity()
{
Intent mainIntent = new Intent(emailloginActivity.this , settingsActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainIntent);
finish();
}
private void SendUserToMain() {
String userName = mAuth.getCurrentUser().getUid();
Intent MainIntent = new Intent(emailloginActivity.this, MainActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
MainIntent.putExtra("mUserID" , userName );
finish();
startActivity(MainIntent);
}
private void SendUserToRegisterActivity()
{
Intent RegisterIntent = new Intent(emailloginActivity.this, RegisterActivity.class);
startActivity(RegisterIntent);
}
}
Mistake is here that you called finish(); before calling startActivity(MainIntent);. Use camelCaseinstade of Capital case in defining variable.
Make changes in your emailloginActivity as below
// changed from MainIntent to mIntent.
private void SendUserToMain() {
String userName = mAuth.getCurrentUser().getUid();
Intent mIntent = new Intent(emailloginActivity.this, MainActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
mIntent.putExtra("mUserID" , userName );
startActivity(mIntent);
finish();
}
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
I want to create Phone Auth Credential like Uber, I mean when user use the app for the first time he has to complete his registration information after phone authentication then he will be able to move to DriverHome Activity, but next time he uses the authentication he will redirect to the DriverHome Activity automatically.
I've used Phone Auth Credential code and it works fine but I need to add the part is responsible for checking if the user registered before or not.
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference users;
ProgressBar progressBar;
TextInputEditText editText;
AppCompatButton buttonSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification_code);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbar);
editText = findViewById(R.id.editTextCode);
buttonSignIn = findViewById(R.id.buttonSignIn);
String phoneNumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phoneNumber);
// save phone number
SharedPreferences prefs = getApplicationContext().getSharedPreferences("USER_PREF",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("phoneNumber", phoneNumber);
editor.apply();
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(VerifyPhoneActivity.this, DriverHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
progressBar.setVisibility(View.GONE);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
};
}
before onCreateView
check if sharepreference has phone number if it has then using startActivity(new Intent(this, DriverHomeActivity.class); to go directly to driverhome activity
if sharepreference has no phone number then
Save phone number in sharepreference if onComplete function of signInWithCredential return successful using isSucessful
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference users;
ProgressBar progressBar;
TextInputEditText editText;
AppCompatButton buttonSignIn;
SharedPreferences prefs ;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getApplicationContext().getSharedPreferences("USER_PREF",
Context.MODE_PRIVATE);
editor = prefs.edit();
//add this line
if(prefs.getString("phoneNumber", null) != null)
startActivity(new Intent(this, DriverHomeActivity.class));
setContentView(R.layout.activity_verification_code);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbar);
editText = findViewById(R.id.editTextCode);
buttonSignIn = findViewById(R.id.buttonSignIn);
String phoneNumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phoneNumber);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//insert data if task is successful
editor.putString("phoneNumber", phoneNumber);
editor.apply();
Intent intent = new Intent(VerifyPhoneActivity.this, DriverHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
progressBar.setVisibility(View.GONE);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
};
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
}
});