Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
- 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);
- }
- }
- 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();
- }
- }
- });
- }
- }
- });
- }
Add Comment
Please, Sign In to add comment