@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_journal_list, container, false); // Set the adapter if (view instanceof RecyclerView) { FirebaseDatabase dbRef = FirebaseDatabase.getInstance(); FirebaseAuth auth = FirebaseAuth.getInstance(); FirebaseUser user = auth.getCurrentUser(); DatabaseReference userRef = dbRef.getReference(user.getUid()); userRef.addChildEventListener (chEvListener); userRef.addValueEventListener(valEvListener); Context context = view.getContext(); RecyclerView recyclerView = (RecyclerView) view; if (mColumnCount <= 1) { recyclerView.setLayoutManager(new LinearLayoutManager(context)); } else { recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount)); } adapter = new JournalAdapter(allTrips, mListener); recyclerView.setAdapter(adapter); } return view; }
private static JSONObject getProfileData(FirebaseUser user) { JSONObject result = new JSONObject(); try { result.put("uid", user.getUid()); result.put("displayName", user.getDisplayName()); result.put("email", user.getEmail()); result.put("phoneNumber", user.getPhoneNumber()); result.put("photoURL", user.getPhotoUrl()); result.put("providerId", user.getProviderId()); } catch (JSONException e) { Log.e(TAG, "Fail to process getProfileData", e); } return result; }
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); mAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { } }); if (currentUser != null) { Intent i = new Intent(Login.this, MapsActivity.class); /*SharedPreferences prefs = Login.this.getSharedPreferences("contact", MODE_WORLD_READABLE); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putString("password", password); prefsEditor.apply();*/ startActivity(i); } }
private void sendVerificationEmail() { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); user.sendEmailVerification() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { // Email sent finish(); } else { // overridePendingTransition(0, 0); // finish(); // overridePendingTransition(0, 0); // startActivity(getIntent()); sendVerificationEmail(); } } }); }
public static void initializeCurrentUserFirebaseListeners() { FirebaseUser firebaseUser = getFirebaseUser(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference userRef = database.getReference().child(FirebaseConstants.USERS).child(firebaseUser.getUid()); userRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { currentUser = dataSnapshot.getValue(User.class); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
private void initializeFirebaseAuth() { // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); } else { // User is signed out Log.d(TAG, "onAuthStateChanged:signed_out"); // signOut(); } } }; }
@Test public void testSignInWithEmailAndPassword() { mockSuccessfulAuthResult(); when(mockFirebaseAuth.signInWithEmailAndPassword("email", "password")).thenReturn( mockAuthResultTask); TestObserver<FirebaseUser> obs = TestObserver.create(); RxFirebaseAuth.signInWithEmailAndPassword(mockFirebaseAuth, "email", "password").subscribe(obs); callOnComplete(mockAuthResultTask); obs.dispose(); // Ensure no more values are emitted after unsubscribe callOnComplete(mockAuthResultTask); obs.assertNoErrors(); obs.assertComplete(); obs.assertValueCount(1); }
private void initializeFirebaseListeners() { FirebaseUser firebaseUser = SessionManager.getFirebaseUser(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference userRef = database.getReference().child(FirebaseConstants.USERS).child(firebaseUser.getUid()); userRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = dataSnapshot.getValue(User.class); Map<String, Medicine> medicinesMap = user.getMedicines(); List<Medicine> currentUserMedicines = new ArrayList<>(medicinesMap.values()); initializeRecentlyUsedMedicinesList(currentUserMedicines); } @Override public void onCancelled(DatabaseError databaseError) { } }); }
@Override public void onComplete(@NonNull Task<AuthResult> task) { int messageId = R.string.user_not_registered; if (task.isSuccessful()) { FirebaseAuth firebaseAuth = SessionManager.getFirebaseAuth(); FirebaseUser currentUser = firebaseAuth.getCurrentUser(); if (currentUser != null) { currentUser.sendEmailVerification(); DbService dbService = SessionManager.getDbService(); dbService.createOrUpdateUserAccountInFirebase(userRegistrationTO); messageId = R.string.verification_email_sent; } Intent intent = new Intent(context, LogInActivity.class); context.startActivity(intent); } Toast.makeText(context, messageId, Toast.LENGTH_SHORT).show(); }
private void setNumberOfMushroomsToUI(DatabaseReference databaseReference, FirebaseUser firebaseUser) { databaseReference.child("users") .child(firebaseUser.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the android UI setNumberOfMushroomsToUI(dataSnapshot.getValue(User.class).getNumberOfMushrooms()); } @Override public void onCancelled(DatabaseError databaseError) { Log.e(TAG, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); }
private void setDistanceRemainingToUI(final DatabaseReference databaseReference, FirebaseUser firebaseUser) { databaseReference.child("global") .child("distanceRemaining") .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the android UI setDistanceRemainingToUI(dataSnapshot.getValue(Long.class).intValue()); } @Override public void onCancelled(DatabaseError databaseError) { Log.e(TAG, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); }
private void subtractFromDistanceRemaining(final DatabaseReference databaseReference, FirebaseUser firebaseUser) { databaseReference.child("global") .child("distanceRemaining") .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the database subtractFromDistanceRemaining(databaseReference, (dataSnapshot.getValue(Long.class).intValue() - 1)); } @Override public void onCancelled(DatabaseError databaseError) { Log.e(TAG, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); }
@Override public void onStart() { super.onStart(); // new MapsActivity().showInternetStatus(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); mAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { } }); if (currentUser != null) { Intent i = new Intent(Login.this, MapsActivity.class); startActivity(i); } }
public FirebaseAuthManager() { super(); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public final void onAuthStateChanged(final @NonNull FirebaseAuth firebaseAuth) { final FirebaseUser _user = firebaseAuth.getCurrentUser(); if (_user != null) { // User is signed in user = _user; } else { // User is signed out user = null; } if (authStateListener != null) authStateListener.onAuthorized(_user != null); } }; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in Log.d("FIREBASEDBRULES", "onAuthStateChanged:signed_in:" + user.getUid()); } else { // User is signed out Log.d("FIREBASEDBRULES", "onAuthStateChanged:signed_out"); } // ... } }; }
/** * Updates user node with appropriate shift-start data */ private void beginShift(){ Intent authenticationHandoff = new Intent(this, ShiftStartActivity.class); //Update user object in database as logged in FirebaseUser user = mAuth.getCurrentUser(); String loginSuccess = "User " + user.getUid() + " has signed in."; Bundle params = new Bundle(); params.putString("time_stamp", ""); //TODO 12/5/17 KB can be removed // Log.d(TAG, "signInWithEmail:success"); // // Log.d(TAG, "instanceid: " + FirebaseInstanceId.getInstance().getToken()); mAnalyticsInstance.logEvent(FirebaseAnalytics.Event.LOGIN, params); //TODO 12/5/17 KB can be removed //get or add employee in database //createEmployee(email); startActivity(authenticationHandoff); }
private void handleFacebookAccessToken(AccessToken token) { Log.e(TAG, "handleFacebookAccessToken:" + token); AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.e(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUser(user); updateUi(); } else { // If sign in fails, display a message to the user. Log.e(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(RegisterActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // ... } }); }
public FirebaseUser initUser() { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user == null) { setUserId(ANONYMOUS); setUserName(ANONYMOUS); // setAvatarUrl(); TODO: add a template for anonymous avatar } else { setUserId(user.getUid()); setUserName(user.getDisplayName()); setAvatarUrl(user.getPhotoUrl().toString()); } return user; }
private void updateProfile() { // [START update_profile] FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder() .setDisplayName("Jane Q. User") .setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg")) .build(); user.updateProfile(profileUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User profile updated."); } } }); // [END update_profile] }
@Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); counter =0; mAuth = FirebaseAuth.getInstance(); databaseFamilies = FirebaseDatabase.getInstance().getReference("Families"); setContentView(R.layout.activity_app_login); Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); //Signs in user with Google sign in mEmailSignInButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // Check if user is signed in (non-null) FirebaseUser currentUser = mAuth.getCurrentUser(); // Add user to database startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setAvailableProviders(providers) .build(), RC_SIGN_IN); } }); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_ITEM_DELETED) { if (resultCode == RESULT_OK && data != null) { Item item = (Item) data.getSerializableExtra(EXTRA_DELETED_ITEM); Fragment itemsFragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_ITEMS); ((ItemsFragment) itemsFragment).onItemDeleted(item); } } if (requestCode == REQUEST_CODE_SIGNIN) { if (resultCode == RESULT_CANCELED) { finish(); } else { FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (firebaseUser != null) { mItemsPresenter.setUid(firebaseUser.getUid()); } else { mItemsPresenter.setUid(null); } } } super.onActivityResult(requestCode, resultCode, data); }
/** * Delete a user from the database */ public void deleteUserFromDatabase() { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { String userId = user.getUid(); getDatabaseManager().deleteUserRecords(getActivity(), userId); user.delete().addOnCompleteListener(new OnCompleteListener<Void>() { /** * Delete the user task completed * @param task - the completed task */ @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { mUser = null; } } }); resetDatabaseManager(); } }
private void addLike(final Feed feed){ flagLike = true; final DatabaseReference referenceLike = FirebaseDatabase.getInstance().getReference().child(LIKE_ROOT); final FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser(); referenceLike.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (flagLike){ if (dataSnapshot.child( feed.getIdFeed() ).hasChild( auth.getUid())){ referenceLike.child(feed.getIdFeed()).child(auth.getUid()).removeValue(); flagLike = false; }else{ referenceLike.child(feed.getIdFeed()).child(auth.getUid()).setValue(true); flagLike = false; } } } @Override public void onCancelled(DatabaseError databaseError) { } }); }
private void getProviderData() { // [START get_provider_data] FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { for (UserInfo profile : user.getProviderData()) { // Id of the provider (ex: google.com) String providerId = profile.getProviderId(); // UID specific to the provider String uid = profile.getUid(); // Name, email address, and profile photo Url String name = profile.getDisplayName(); String email = profile.getEmail(); Uri photoUrl = profile.getPhotoUrl(); }; } // [END get_provider_data] }
private void onSignInIntialize(FirebaseUser user) { startActivity(new Intent(this,MyLocation.class)); if(user.getDisplayName() != null) { mUsername = user.getDisplayName().toString(); } else { mUsername = "User"; } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); context = this; mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in Toast.makeText(context,"User present",Toast.LENGTH_SHORT).show(); Log.d(Constants.LOGGER, "onAuthStateChanged:signed_in:" + user.getUid()); //go straight to main activity Intent intent = new Intent(context,MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); finish(); } else { // User is signed out Toast.makeText(context,"User not present",Toast.LENGTH_SHORT).show(); Log.d(Constants.LOGGER, "onAuthStateChanged:signed_out"); } } }; initViews(); }
private void verifyPhoneNumber(final String phoneNumber, final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { phoneAuthProvider.verifyPhoneNumber(phoneNumber, 0, MILLISECONDS, cordova.getActivity(), new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user == null) { firebaseAuth.signInWithCredential(credential); } else { user.updatePhoneNumber(credential); } callbackContext.success(""); } @Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken) { callbackContext.success(verificationId); } @Override public void onVerificationFailed(FirebaseException e) { callbackContext.error(e.getMessage()); } } ); } }); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_media_details); ButterKnife.bind(this); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); String uid = user.getUid(); storageRef = FirebaseStorage.getInstance().getReference().child (uid); Intent incoming = getIntent(); if (incoming.hasExtra("FIREBASE_REF")) { String fbUrl = incoming.getStringExtra("FIREBASE_REF"); FirebaseDatabase db = FirebaseDatabase.getInstance(); entriesRef = db.getReferenceFromUrl(fbUrl); } if (incoming.hasExtra("PHOTO_URI")) { mediaType = 2; try { dataUri = incoming.getParcelableExtra("PHOTO_URI"); InputStream istr = getContentResolver().openInputStream (dataUri); Bitmap bmp = BitmapFactory.decodeStream(istr); photoView.setImageBitmap(bmp); istr.close(); } catch (IOException e) { e.printStackTrace(); } } if (incoming.hasExtra("VIDEO_URI")) { mediaType = 4; dataUri = incoming.getParcelableExtra("VIDEO_URI"); videoView.setVideoURI(dataUri); MediaController mc = new MediaController(this); videoView.setMediaController(mc); photoView.setVisibility(View.INVISIBLE); videoView.setVisibility(View.VISIBLE); } }
@Override public void onStart() { super.onStart(); FirebaseUser currentUser = mAuth.getCurrentUser(); if (currentUser == null) { out.println("Not logged in"); final AlertDialog.Builder signInDialogBuilder = new AlertDialog.Builder(context); LayoutInflater inflater = this.getLayoutInflater(); View signInDialogView = inflater.inflate(R.layout.dialog_sign_in, null); signInDialogBuilder.setView(signInDialogView); signInDialogBuilder.setTitle("Sign in"); final SignInButton signInButton = (SignInButton) signInDialogView.findViewById(R.id.signInDialogGoogle); final AlertDialog signInDialog = signInDialogBuilder.create(); signInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); out.println("TEST"); signInDialog.dismiss(); } }); signInDialog.show(); } else { // Logged in // TODO: Add firestore Log.d("Tag", "Successfully logged in!"); String emailAddr = currentUser.getEmail(); String[] userNameDots = emailAddr.substring(0, emailAddr.lastIndexOf("@")) .split("."); StringJoiner joiner = new StringJoiner(""); for (String string:userNameDots) joiner.add(string); userName = joiner.toString(); out.println(userName); // userName = userNameDots.join(""); } }
private void handleFirebaseAuthResult(AuthResult authResult) { if (authResult != null) { // Welcome the user FirebaseUser user = authResult.getUser(); Toast.makeText(this, "Welcome " + user.getEmail(), Toast.LENGTH_SHORT).show(); // Go back to the main activity startActivity(new Intent(this, MainActivity.class)); } }
private void initializeFirebaseListeners() { FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); FirebaseUser currentUser = SessionManager.getFirebaseUser(); DatabaseReference currentUserReference = firebaseDatabase.getReference(FirebaseConstants.USERS).child(currentUser.getUid()); currentUserReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = dataSnapshot.getValue(User.class); Map<String, FamilyMember> userIdToFamilyMemberObjMap = user.getFamilyMembers(); List<FamilyMember> acceptedFamilyMembers = new ArrayList<>(); if (userIdToFamilyMemberObjMap != null) { for (FamilyMember familyMember : userIdToFamilyMemberObjMap.values()) { if (familyMember.getInvitationStatus() == InvitationStatusEnum.ACCEPTED) { acceptedFamilyMembers.add(familyMember); } } } Context context = getContext(); if (context != null) { FamilyContactArrayAdapter familyContactArrayAdapter = new FamilyContactArrayAdapter(getContext(), R.id.contacts_list_view, acceptedFamilyMembers); contactsListView.setAdapter(familyContactArrayAdapter); } } @Override public void onCancelled(DatabaseError databaseError) { } }); }
@Override public void createOrUpdateUserAccountInFirebase(UserRegistrationTO userRegistrationTO) { FirebaseUser currentUser = SessionManager.getFirebaseUser(); DatabaseReference userRef = firebaseDB.getReference(USERS).child(currentUser.getUid()); User user = new User(); user.setId(currentUser.getUid()); user.setUsername(userRegistrationTO.getUsername()); user.setEmail(userRegistrationTO.getEmail()); userRef.setValue(user); }
@Override public void onResume(){ super.onResume(); FirebaseDatabase dbRef = FirebaseDatabase.getInstance(); FirebaseAuth mAuth = FirebaseAuth.getInstance(); FirebaseUser mUser = mAuth.getCurrentUser(); String uid = mUser.getUid(); topRef = dbRef.getReference(uid); }
@Override public void updateSearchValueFamilyInSession(String searchValue) { FirebaseUser currentUser = SessionManager.getFirebaseUser(); DatabaseReference userPreferencesRef = firebaseDB.getReference(USERS).child(currentUser.getUid()).child(USER_SESSION).child(SEARCH_VALUE_IN_FAMILY); userPreferencesRef.setValue(searchValue); }
@Override public void saveOrUpdateMedicine(Medicine medicine) { FirebaseUser firebaseUser = SessionManager.getFirebaseUser(); DatabaseReference medicinesRef = firebaseDB.getReference(USERS).child(firebaseUser.getUid()).child(MEDICINES); if (TextUtils.isEmpty(medicine.getId())) { String medicineId = medicinesRef.push().getKey(); medicine.setId(medicineId); medicine.setCreatedAt(new Date()); } medicine.setUpdatedAt(new Date()); medicinesRef.child(medicine.getId()).setValue(medicine); }
@Override protected void onFirebaseUserSignedIn(FirebaseUser user) { super.onFirebaseUserSignedIn(user); if (CRDTimeManager.isCinedayCodeToShareEpochValid(this)) { String codeToShare = CRDSharedPreferences.getInstance(this).getCinedayCodeToShare(); if (codeToShare != null) { shareCinedayCode(codeToShare); } } }