Guest User

Untitled

a guest
Dec 8th, 2018
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.21 KB | None | 0 0
  1. public class MainActivity extends AppCompatActivity {
  2.  
  3. private SignInButton signIn;
  4.  
  5.  
  6. private int RC_SIGN_IN=1;
  7. private GoogleSignInClient mGoogleSignInClient;
  8. private String TAG = "MainActivity";
  9. private FirebaseAuth mAuth;
  10.  
  11. private Button registration;
  12.  
  13. private EditText email;
  14. private EditText password;
  15. private Button login;
  16.  
  17.  
  18. private BottomNavigationView bottomNavigationItemView;
  19.  
  20.  
  21.  
  22. @Override
  23. protected void onCreate(Bundle savedInstanceState) {
  24. super.onCreate(savedInstanceState);
  25. setContentView(R.layout.activity_main);
  26.  
  27. signIn = (SignInButton)findViewById(R.id.sign_in_button);
  28.  
  29. mAuth = FirebaseAuth.getInstance();
  30.  
  31. registration = (Button) findViewById(R.id.registrate);
  32. email = (EditText)findViewById(R.id.email);
  33. password = (EditText)findViewById(R.id.password);
  34. login = (Button)findViewById(R.id.login);
  35.  
  36.  
  37. bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;
  38. bottomNavigationItemView.getMenu().getItem(0).setChecked(true);
  39.  
  40.  
  41. bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
  42. @Override
  43. public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
  44. switch (menuItem.getItemId()) {
  45. case R.id.register_menu: {
  46.  
  47. Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
  48. startActivity(intent);
  49. break;
  50. }
  51. }
  52. return true;
  53. }
  54. });
  55.  
  56.  
  57.  
  58. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  59. .requestIdToken(getString(R.string.default_web_client_id))
  60. .requestEmail()
  61. .build();
  62.  
  63. mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
  64.  
  65.  
  66.  
  67. signIn.setOnClickListener(new View.OnClickListener() {
  68. @Override
  69. public void onClick(View v) {
  70. signIn();
  71. }
  72. });
  73.  
  74.  
  75. registration.setOnClickListener(new View.OnClickListener() {
  76. @Override
  77. public void onClick(View v) {
  78. Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
  79. startActivity(intent);
  80. }
  81. });
  82.  
  83.  
  84.  
  85. login.setOnClickListener(new View.OnClickListener() {
  86. @Override
  87. public void onClick(View v) {
  88.  
  89. String email_text = email.getText().toString().trim();
  90. String password_text = password.getText().toString().trim();
  91.  
  92. if(TextUtils.isEmpty(email_text) || TextUtils.isEmpty(password_text))
  93. {
  94. Toast.makeText(MainActivity.this, "One or more fields are empty", Toast.LENGTH_LONG).show();
  95. }
  96. else
  97. {
  98. mAuth.signInWithEmailAndPassword(email_text, password_text).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
  99. @Override
  100. public void onComplete(@NonNull Task<AuthResult> task) {
  101.  
  102. if(!task.isSuccessful())
  103. {
  104. Toast.makeText(MainActivity.this, "Sign in problem", Toast.LENGTH_LONG).show();
  105. }
  106. else
  107. {
  108. Intent intent = new Intent(MainActivity.this, AccountActivity.class);
  109. startActivity(intent);
  110. }
  111. }
  112. });
  113. }
  114.  
  115. }
  116. });
  117.  
  118.  
  119. }
  120.  
  121.  
  122. private void signIn() { /*Sign in to the app with Google Account*/
  123. Intent signInIntent = mGoogleSignInClient.getSignInIntent();
  124. startActivityForResult(signInIntent, RC_SIGN_IN);
  125.  
  126.  
  127. }
  128.  
  129. @Override
  130. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  131. super.onActivityResult(requestCode, resultCode, data);
  132.  
  133. // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
  134. if (requestCode == RC_SIGN_IN) {
  135. // The Task returned from this call is always completed, no need to attach
  136. // a listener.
  137. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
  138. try{
  139. GoogleSignInAccount account = task.getResult(ApiException.class);
  140. firebaseAuthWithGoogle(account);
  141. }
  142. catch(ApiException e){
  143.  
  144. Log.w(TAG, "Google Sin in Failed");
  145. }
  146. }
  147. }
  148.  
  149. private void firebaseAuthWithGoogle(GoogleSignInAccount acct)
  150. {
  151. Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
  152. AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
  153. mAuth.signInWithCredential(credential)
  154. .addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
  155. {
  156. @Override
  157. public void onComplete(@NonNull Task<AuthResult> task)
  158. {
  159. if(task.isSuccessful())
  160. {
  161. Log.d(TAG, "signInWithCredential: success");
  162. FirebaseUser user = mAuth.getCurrentUser();
  163. updateUI(user);
  164. }
  165. else
  166. {
  167. Log.w(TAG, "signInWithCredential: failure", task.getException()); /*In case of unsuccessful login*/
  168. Toast.makeText(MainActivity.this, "You are not able to log in to Google", Toast.LENGTH_LONG).show();
  169. //updateUI(null);
  170. }
  171. }
  172. });
  173.  
  174.  
  175. }
  176.  
  177. private void updateUI(FirebaseUser user) /*In case of successful registration*/
  178. {
  179.  
  180. GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
  181. if (acct != null) {
  182. String personName = acct.getDisplayName();
  183. String personGivenName = acct.getGivenName();
  184. String personFamilyName = acct.getFamilyName();
  185. String personEmail = acct.getEmail();
  186. String personId = acct.getId();
  187. Uri personPhoto = acct.getPhotoUrl();
  188. Toast.makeText(this, "Name of User : " + personName + "UserId is : " + personId, Toast.LENGTH_LONG);
  189.  
  190.  
  191. Intent intent = new Intent(this, AccountActivity.class);
  192. intent.putExtra("personPhoto", personPhoto.toString());
  193. startActivity(intent);
  194. }
  195. }
  196.  
  197. public class AccountActivity extends AppCompatActivity {
  198.  
  199. private GoogleSignInClient mGoogleSignInClient;
  200.  
  201.  
  202. private FirebaseAuth mAuth;
  203. private FirebaseAuth.AuthStateListener mAuthStateListener;
  204.  
  205.  
  206. private CardView signOut;
  207. private CardView ratingTable;
  208. private CardView settings;
  209. private CardView map;
  210. private CardView favoritePlaces;
  211.  
  212. DatabaseReference databaseReference;
  213. FirebaseDatabase database;
  214. List<User> users;
  215.  
  216. CollapsingToolbarLayout collapsingToolbarLayout;
  217.  
  218.  
  219. String photoString="No photo";
  220.  
  221.  
  222. @Override
  223. protected void onCreate(Bundle savedInstanceState) {
  224. super.onCreate(savedInstanceState);
  225. setContentView(R.layout.activity_account);
  226.  
  227.  
  228. mAuth = FirebaseAuth.getInstance();
  229.  
  230.  
  231. signOut = (CardView) findViewById(R.id.logout);
  232. ratingTable = (CardView) findViewById(R.id.rating);
  233. settings = (CardView)findViewById(R.id.settings);
  234. map = (CardView) findViewById(R.id.map);
  235. favoritePlaces = (CardView)findViewById(R.id.favorite);
  236.  
  237.  
  238.  
  239. database = FirebaseDatabase.getInstance();
  240. databaseReference = database.getReference();
  241. users = new ArrayList<User>();
  242.  
  243. collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collaps);
  244.  
  245.  
  246.  
  247.  
  248. if(mAuth.getCurrentUser().getDisplayName()!=null)
  249. {
  250. Intent i = getIntent();
  251. photoString = i.getStringExtra("personPhoto");
  252. }
  253.  
  254.  
  255.  
  256. databaseReference.child("user").addValueEventListener(new ValueEventListener() { /*A new user is registered in the database*/
  257. @Override
  258. public void onDataChange(DataSnapshot dataSnapshot) {
  259.  
  260. Iterable<DataSnapshot> children = dataSnapshot.getChildren();
  261. for (DataSnapshot child : children) {
  262. User user = child.getValue(User.class);
  263. users.add(user);
  264. }
  265.  
  266. if (!findUser()) /*If the user is not found, this is a new user and must be registered*/
  267. addUser();
  268. showName(); /*A user-specific message*/
  269. }
  270.  
  271.  
  272. @Override
  273. public void onCancelled(DatabaseError databaseError) {
  274.  
  275. }
  276. });
  277.  
  278.  
  279. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  280. .requestIdToken(getString(R.string.default_web_client_id))
  281. .requestEmail()
  282. .build();
  283. mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
  284.  
  285.  
  286.  
  287.  
  288. signOut.setOnClickListener(new View.OnClickListener() {
  289. @Override
  290. public void onClick(View v) {
  291.  
  292. if(mAuth.getCurrentUser().getDisplayName()!=null)
  293. {
  294. mGoogleSignInClient.signOut();
  295. //Intent intent = new Intent(AccountActivity.this, MainActivity.class);
  296. // startActivity(intent);
  297. Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
  298. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  299. startActivity(i);
  300.  
  301.  
  302. }
  303. else
  304. {
  305. mAuth.signOut();
  306. Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
  307. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  308. startActivity(i);
  309. }
  310. }
  311. });
  312.  
  313.  
  314.  
  315. settings.setOnClickListener(new View.OnClickListener() {
  316. @Override
  317. public void onClick(View v) {
  318. Intent intent = new Intent(AccountActivity.this, SettingsActivity.class);
  319. startActivity(intent);
  320. }
  321. });
  322.  
  323. map.setOnClickListener(new View.OnClickListener() {
  324. @Override
  325. public void onClick(View v) {
  326. Intent intent = new Intent(AccountActivity.this, MapsActivity.class);
  327. startActivity(intent);
  328. }
  329. });
  330.  
  331. favoritePlaces.setOnClickListener(new View.OnClickListener() {
  332. @Override
  333. public void onClick(View v) {
  334. Intent intent = new Intent(AccountActivity.this, favoritePlacesActivity.class);
  335. startActivity(intent);
  336. }
  337. });
  338.  
  339. ratingTable.setOnClickListener(new View.OnClickListener() {
  340. @Override
  341. public void onClick(View v) {
  342. Intent intent = new Intent(AccountActivity.this, RatingTableActivity.class);
  343. startActivity(intent);
  344.  
  345. }
  346. });
  347.  
  348.  
  349. }
  350.  
  351.  
  352.  
  353.  
  354. private void showName() /*A user-specific message*/
  355. {
  356. String name = "";
  357. String userId = mAuth.getUid();
  358. for (User tmpUser : users) {
  359. if (userId.equals(tmpUser.getUserId()))
  360. {
  361. name = tmpUser.getUserName();
  362. break;
  363. }
  364. }
  365. collapsingToolbarLayout.setTitle("Hi " + name);
  366. }
  367.  
  368.  
  369.  
  370. private boolean findUser() /*Check if a logged-on user is already registered in the database*/
  371. {
  372.  
  373. FirebaseUser user = mAuth.getCurrentUser();
  374. String userId = mAuth.getUid();
  375.  
  376.  
  377.  
  378. for (User tmpUser : users) {
  379. if (userId.equals(tmpUser.getUserId())) {
  380. return true;
  381. }
  382. }
  383. return false;
  384.  
  385. }
  386.  
  387. private void addUser() /*In case of registration from Google Account*/
  388. {
  389. String userId = mAuth.getUid();
  390. if(mAuth.getCurrentUser().getDisplayName()!=null) /*In case of registration not from Google Account*/
  391. {
  392. databaseReference = FirebaseDatabase.getInstance().getReference("user");
  393. FirebaseUser user = mAuth.getCurrentUser();
  394. String userName = user.getDisplayName();
  395. User newUser = User.getInstance(userId, userName, photoString);
  396. databaseReference.child(userId).setValue(newUser);
  397. }
  398.  
  399. else /*If the user is not registered the function registers it in the database*/
  400. {
  401. databaseReference = FirebaseDatabase.getInstance().getReference("user");
  402. Intent i = getIntent();
  403. String firstName = i.getStringExtra("firstName");
  404. String lastName = i.getStringExtra("lastName");
  405.  
  406.  
  407. User newUser = User.getInstance(userId, firstName + " " + lastName, photoString);
  408. databaseReference.child(userId).setValue(newUser);
  409. }
  410.  
  411. }
  412.  
  413. public class RegistrationActivity extends AppCompatActivity {
  414.  
  415. EditText email_text;
  416. EditText pass1;
  417. EditText pass2;
  418. EditText first;
  419. EditText last;
  420. Button registrate;
  421.  
  422. FirebaseAuth mAuth;
  423. private ProgressDialog progressDialog;
  424.  
  425.  
  426.  
  427. private BottomNavigationView bottomNavigationItemView;
  428.  
  429. @Override
  430. protected void onCreate(Bundle savedInstanceState) {
  431. super.onCreate(savedInstanceState);
  432. setContentView(R.layout.activity_registration);
  433.  
  434. mAuth = FirebaseAuth.getInstance();
  435. progressDialog = new ProgressDialog(this);
  436.  
  437. email_text = (EditText)findViewById(R.id.email);
  438. pass1 = (EditText)findViewById(R.id.password1);
  439. pass2 = (EditText)findViewById(R.id.password2);
  440. first = (EditText)findViewById(R.id.first_name);
  441. last = (EditText)findViewById(R.id.last_name);
  442. registrate = (Button)findViewById(R.id.registrate);
  443.  
  444.  
  445.  
  446.  
  447. bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;
  448.  
  449. bottomNavigationItemView.getMenu().getItem(1).setChecked(true);
  450.  
  451.  
  452.  
  453. bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
  454. @Override
  455. public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
  456. switch (menuItem.getItemId()) {
  457. case R.id.Signin_menu: {
  458.  
  459. Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
  460. startActivity(intent);
  461. break;
  462. }
  463. }
  464. return true;
  465. }
  466. });
  467.  
  468.  
  469. registrate.setOnClickListener(new View.OnClickListener() {
  470. @Override
  471. public void onClick(View v) {
  472.  
  473. final String email = email_text.getText().toString().trim();
  474. String password1 = pass1.getText().toString().trim();
  475. String password2 = pass2.getText().toString().trim();
  476. final String first_name = first.getText().toString().trim();
  477. final String last_name = last.getText().toString().trim();
  478. boolean correctFlag=true;
  479.  
  480. /*All tests for input integrity*/
  481. if(!password1.equals(password2))
  482. {
  483. Toast.makeText(RegistrationActivity.this, "The password does not match", Toast.LENGTH_LONG).show();
  484. correctFlag=false;
  485. }
  486. if(password1.equals("") && password2.equals(""))
  487. {
  488. Toast.makeText(RegistrationActivity.this, "No password entered", Toast.LENGTH_LONG).show();
  489. correctFlag=false;
  490. }
  491. if(email.equals("") || first_name.equals("") || last_name.equals(""))
  492. {
  493. Toast.makeText(RegistrationActivity.this, "One or more of the parameters are incorrect", Toast.LENGTH_LONG).show();
  494. correctFlag=false;
  495. }
  496.  
  497. if(correctFlag) /*There is no problem filling the fields*/
  498. {
  499. progressDialog.setMessage("Registrating user...");
  500. progressDialog.show();
  501.  
  502. mAuth.createUserWithEmailAndPassword(email, password1).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
  503. @Override
  504. public void onComplete(@NonNull Task<AuthResult> task) {
  505.  
  506. if(task.isSuccessful())
  507. {
  508. Toast.makeText(RegistrationActivity.this, "Registered Succesfully", Toast.LENGTH_SHORT).show();
  509. progressDialog.cancel();
  510. Intent intent = new Intent(RegistrationActivity.this, AccountActivity.class);
  511. intent.putExtra("firstName", first_name);
  512. intent.putExtra("lastName", last_name);
  513. startActivity(intent);
  514. }
  515. else
  516. {
  517. Toast.makeText(RegistrationActivity.this, "could not register. please try again", Toast.LENGTH_SHORT).show();
  518. progressDialog.cancel();
  519. }
  520. }
  521. });
  522. }
  523. }
  524. });
  525. }
Add Comment
Please, Sign In to add comment