Java Code Examples for com.google.firebase.auth.FirebaseUser

The following are top voted examples for showing how to use com.google.firebase.auth.FirebaseUser. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: mobile-app-dev-book   File: JournalFragment.java   View source code 8 votes vote down vote up
@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;
}
 
Example 2
Project: snippets-android   File: MainActivity.java   View source code 7 votes vote down vote up
private void reauthenticate() {
    // [START reauthenticate]
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    // Get auth credentials from the user for re-authentication. The example below shows
    // email and password credentials but there are multiple possible providers,
    // such as GoogleAuthProvider or FacebookAuthProvider.
    AuthCredential credential = EmailAuthProvider
            .getCredential("[email protected]", "password1234");

    // Prompt the user to re-provide their sign-in credentials
    user.reauthenticate(credential)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    Log.d(TAG, "User re-authenticated.");
                }
            });
    // [END reauthenticate]
}
 
Example 3
Project: cordova-plugin-firebase-authentication   File: FirebaseAuthenticationPlugin.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: mobile-app-dev-book   File: MediaDetailsActivity.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 5
Project: SIIEScanner   File: FirebaseScanner.java   View source code 6 votes vote down vote up
protected void startSession() {
    Log.i("scan.log", "Init database session" );
    final ScannerDao scannerDao = new ScannerDao( this.context );

    this.auth = FirebaseAuth.getInstance();
    FirebaseUser currentUser = this.auth.getCurrentUser();
    if( currentUser == null ) {
        Log.i("scan.log", "No Has User connerct" );
        this.auth.signInWithEmailAndPassword( "[email protected]", "123456" )
                .addOnCompleteListener( new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if( task.isSuccessful() ) {
                            initDataBase( scannerDao );
                        }
                    }
                });
    } else {
        Log.i("scan.log", "Has user connected" );
        this.initDataBase( scannerDao );
    }
}
 
Example 6
Project: VEHICLE-APP   File: Login.java   View source code 6 votes vote down vote up
@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);
        }

}
 
Example 7
Project: mobile-app-dev-book   File: JournalFragment.java   View source code 6 votes vote down vote up
@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;
}
 
Example 8
Project: NITKart   File: newUser.java   View source code 6 votes vote down vote up
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();
                    }
                }
            });
}
 
Example 9
Project: wirtualnaApteczka   File: SessionManager.java   View source code 6 votes vote down vote up
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) {
        }
    });
}
 
Example 10
Project: social-journal   File: SettingsActivity.java   View source code 6 votes vote down vote up
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();
                }
            }
        };
    }
 
Example 11
Project: RxFirebase2   File: RxFirebaseAuthTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 12
Project: wirtualnaApteczka   File: MainActivity.java   View source code 6 votes vote down vote up
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) {
        }
    });
}
 
Example 13
Project: wirtualnaApteczka   File: RegistrationOnCompleteListener.java   View source code 6 votes vote down vote up
@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();
}
 
Example 14
Project: Forager   File: AccountSettings.java   View source code 6 votes vote down vote up
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());
                }
            });
}
 
Example 15
Project: Forager   File: Community.java   View source code 6 votes vote down vote up
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());
                }
            });
}
 
Example 16
Project: Forager   File: StartGame.java   View source code 6 votes vote down vote up
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());
                }
            });
}
 
Example 17
Project: GogoNew   File: Login.java   View source code 6 votes vote down vote up
@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);
        }

    }
 
Example 18
Project: Android-MVP-vs-MVVM-Samples   File: FirebaseAuthManager.java   View source code 6 votes vote down vote up
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);
        }
    };
}
 
Example 19
Project: mobile-app-dev-book   File: JournalFragment.java   View source code 6 votes vote down vote up
@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;
}
 
Example 20
Project: androidadvanced   File: MainActivity.java   View source code 6 votes vote down vote up
@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");
            }
            // ...
        }
    };
}
 
Example 21
Project: Dispatch   File: LoginActivity.java   View source code 6 votes vote down vote up
/**
     * 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);
    }
 
Example 22
Project: FirebasePost   File: RegisterActivity.java   View source code 6 votes vote down vote up
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();
                    }

                    // ...
                }

            });
}
 
Example 23
Project: VR-One   File: ForumPost.java   View source code 6 votes vote down vote up
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;
}
 
Example 24
Project: snippets-android   File: MainActivity.java   View source code 6 votes vote down vote up
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]
}
 
Example 25
Project: Chore-Manager-App   File: AppLoginActivity.java   View source code 6 votes vote down vote up
@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);
        }
    });
}
 
Example 26
Project: item-reaper   File: ItemsActivity.java   View source code 6 votes vote down vote up
@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);
}
 
Example 27
Project: Botanist   File: AccountController.java   View source code 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 28
Project: FeedFire   File: MainActivity.java   View source code 6 votes vote down vote up
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) {

        }
    });

}
 
Example 29
Project: snippets-android   File: MainActivity.java   View source code 6 votes vote down vote up
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]
}
 
Example 30
Project: iSPY   File: Login.java   View source code 5 votes vote down vote up
private void onSignInIntialize(FirebaseUser user) {

        startActivity(new Intent(this,MyLocation.class));
        if(user.getDisplayName() != null) {
            mUsername = user.getDisplayName().toString();
        } else {
            mUsername = "User";
        }
    }
 
Example 31
Project: do-road   File: LoginActivity.java   View source code 5 votes vote down vote up
@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();

}
 
Example 32
Project: cordova-plugin-firebase-authentication   File: FirebaseAuthenticationPlugin.java   View source code 5 votes vote down vote up
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());
                    }
                }
            );
        }
    });
}
 
Example 33
Project: StudyBuddy   File: MainActivity.java   View source code 5 votes vote down vote up
@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("");
        }
    }
 
Example 34
Project: friendlychat-android   File: SignInActivity.java   View source code 5 votes vote down vote up
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));
    }
}
 
Example 35
Project: wirtualnaApteczka   File: ContactsTabFragment.java   View source code 5 votes vote down vote up
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) {

        }
    });
}
 
Example 36
Project: wirtualnaApteczka   File: FirebaseDbServiceImpl.java   View source code 5 votes vote down vote up
@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);
}
 
Example 37
Project: mobile-app-dev-book   File: MainActivity.java   View source code 5 votes vote down vote up
@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);
}
 
Example 38
Project: wirtualnaApteczka   File: FirebaseDbServiceImpl.java   View source code 5 votes vote down vote up
@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);
}
 
Example 39
Project: wirtualnaApteczka   File: FirebaseDbServiceImpl.java   View source code 5 votes vote down vote up
@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);
}
 
Example 40
Project: CineReminDay   File: CRDMainActivity.java   View source code 5 votes vote down vote up
@Override
protected void onFirebaseUserSignedIn(FirebaseUser user) {
    super.onFirebaseUserSignedIn(user);

    if (CRDTimeManager.isCinedayCodeToShareEpochValid(this)) {
        String codeToShare = CRDSharedPreferences.getInstance(this).getCinedayCodeToShare();

        if (codeToShare != null) {
            shareCinedayCode(codeToShare);
        }
    }
}