Guest User

Login

a guest
Apr 7th, 2019
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.63 KB | None | 0 0
  1. package com.bud.ohad.noticeboardeylon;
  2.  
  3. import android.Manifest;
  4. import android.app.Activity;
  5. import android.app.AlertDialog;
  6. import android.app.ProgressDialog;
  7. import android.content.Context;
  8. import android.content.DialogInterface;
  9. import android.content.Intent;
  10. import android.content.pm.PackageManager;
  11. import android.graphics.drawable.Drawable;
  12. import android.graphics.drawable.ScaleDrawable;
  13. import android.os.Bundle;
  14. import android.support.annotation.NonNull;
  15. import android.support.v4.app.ActivityCompat;
  16. import android.support.v4.content.ContextCompat;
  17. import android.text.InputType;
  18. import android.text.method.PasswordTransformationMethod;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.widget.Button;
  22. import android.widget.CheckBox;
  23. import android.widget.CompoundButton;
  24. import android.widget.EditText;
  25. import android.widget.Toast;
  26.  
  27. import com.google.android.gms.tasks.OnCompleteListener;
  28. import com.google.android.gms.tasks.Task;
  29. import com.google.firebase.auth.AuthResult;
  30. import com.google.firebase.auth.FirebaseAuth;
  31. import com.google.firebase.auth.FirebaseUser;
  32. import com.google.firebase.database.DataSnapshot;
  33. import com.google.firebase.database.DatabaseError;
  34. import com.google.firebase.database.DatabaseReference;
  35. import com.google.firebase.database.FirebaseDatabase;
  36. import com.google.firebase.database.ValueEventListener;
  37.  
  38. import java.lang.reflect.Array;
  39. import java.util.ArrayList;
  40. import java.util.List;
  41.  
  42. public class Login extends Activity {
  43.     private FirebaseAuth mAuth;
  44.     Button btnLoggedIn;
  45.     EditText etEmail, etPassword;
  46.     Intent toEventList;
  47.     CheckBox cbShowPassword;
  48.     ProgressDialog dialog;
  49.     @Override
  50.     protected void onCreate(Bundle savedInstanceState) {
  51.         super.onCreate(savedInstanceState);
  52.         setContentView(R.layout.activity_main);
  53.         //starts alerts
  54.         Job.scheduleJob(getApplicationContext());
  55.         //dialog begins
  56.         dialog=new ProgressDialog(this);
  57.         dialog.setMessage("Authenticating please wait... \n\nIf this is taking too long check your internet connection");
  58.         dialog.setCancelable(false);
  59.         dialog.setInverseBackgroundForced(false);
  60.         dialog.show();
  61.         mAuth = FirebaseAuth.getInstance();
  62.         btnLoggedIn = new Button(getApplicationContext());
  63.         btnLoggedIn = findViewById(R.id.btnLoggedIn);
  64.         cbShowPassword = findViewById(R.id.cbShowPassword);
  65.         etEmail = new EditText(getApplicationContext());
  66.         etEmail = (EditText) findViewById(R.id.etEmail);
  67.         etPassword = new EditText(getApplicationContext());
  68.         etPassword = (EditText) findViewById(R.id.etPassword);
  69.        // register();
  70.  
  71.         btnLoggedIn.setOnClickListener(new View.OnClickListener() {
  72.             @Override
  73.             public void onClick(View v) {
  74.                 if(dialog!=null){
  75.                     dialog.show();
  76.                 }
  77.                 etEmail.setError(null);
  78.                 etPassword.setError(null);
  79.                 boolean error =false;
  80.                 //retrieves user entered details
  81.                 final String retreivedEmail = etEmail.getText().toString().trim();
  82.                 final String retreivedPassword = etPassword.getText().toString();
  83.                 //Checks mail validity offline
  84.                 if(!BroardFunctions.isEmailValid(retreivedEmail)){
  85.                     etEmail.setError("Mail isn't valid");
  86.                     error=true;
  87.  
  88.                 }
  89.                 //checks for password
  90.                 if(retreivedPassword.equals("")){
  91.                     etPassword.setError("Password cannot be empty");
  92.                     error=true;
  93.                 }
  94.                 if(!error) {
  95.                     /*
  96.                      * no error has been found
  97.                      */
  98.                     final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
  99.                     rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
  100.                         @Override
  101.                         public void onDataChange(DataSnapshot snapshot) {
  102.                             mAuth = FirebaseAuth.getInstance();
  103.                             signIn(mAuth, retreivedEmail, retreivedPassword);// commence sign in
  104.  
  105.  
  106.                         }
  107.  
  108.                         @Override
  109.                         public void onCancelled(DatabaseError databaseError) {
  110.                             Toast.makeText(getApplicationContext(), "Access to firebase canceled!",
  111.                                     Toast.LENGTH_LONG).show();
  112.                             if (dialog != null) {
  113.                                 dialog.dismiss();
  114.                             }
  115.                         }
  116.                     });
  117.                 }else{
  118.                     if(dialog!=null) {
  119.                         dialog.dismiss();
  120.                     }
  121.                     Toast.makeText(getApplicationContext(),"Invalid inputs",Toast.LENGTH_SHORT).show();
  122.                 }
  123.  
  124.             }
  125.         });
  126.  
  127.         /*
  128.         shows and hides password on toggle
  129.          */
  130.         cbShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  131.             @Override
  132.             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  133.                 if(isChecked){
  134.                     etPassword.setTransformationMethod(null);
  135.                 }else{
  136.                     etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
  137.                 }
  138.             }
  139.         });
  140.  
  141.     }
  142.  
  143.     @Override
  144.     public void onStart() {
  145.         super.onStart();
  146.         // Check if user is signed in (non-null) and update UI accordingly.
  147.         FirebaseUser currentUser = mAuth.getCurrentUser();
  148.         updateUI(currentUser);
  149.     }
  150.  
  151.     /**
  152.      *
  153.      * @param mAuth Firebase auth
  154.      * @param email the user entered email
  155.      * @param password the user entered password
  156.      */
  157.     public void signIn(final FirebaseAuth mAuth, String email, String password) {
  158.         mAuth.signInWithEmailAndPassword(email, password)
  159.                 .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  160.                     @Override
  161.                     public void onComplete(@NonNull Task<AuthResult> task) {
  162.                         if (task.isSuccessful()) {
  163.                             // Sign in success, update UI with the signed-in user's information
  164.                             Log.d("5", "signInWithEmail:success");
  165.                             FirebaseUser user = mAuth.getCurrentUser();
  166.                             Toast.makeText(getApplicationContext(), "Authentication Successful!",
  167.                                     Toast.LENGTH_SHORT).show();
  168.                             updateUI(user);//update ui
  169.                         } else {
  170.                             // If sign in fails, display a message to the user.
  171.                             Log.w("5", "signInWithEmail:failure", task.getException());
  172.                             Toast.makeText(getApplicationContext(), "Authentication failed.",
  173.                                     Toast.LENGTH_SHORT).show();
  174.                             updateUI(null);
  175.                         }
  176.  
  177.  
  178.                     }
  179.                 });
  180.     }
  181.  
  182.     private void updateUI(final FirebaseUser user) {
  183.         if (user == null) {
  184.             if(dialog!=null){
  185.                 dialog.dismiss();
  186.             }
  187.  
  188.         } else {
  189.             final FirebaseDatabase database = FirebaseDatabase.getInstance();
  190.             DatabaseReference ref = database.getReference();
  191.             ref.child("Users").child(user.getUid()).addValueEventListener(new ValueEventListener() {
  192.                 @Override
  193.                 public void onDataChange(DataSnapshot dataSnapshot) {
  194.                     ServerUser currUser = dataSnapshot.getValue(ServerUser.class);
  195.                     Log.d("5", "Current user details: " + currUser.toString());
  196.                     if(dialog!=null){
  197.                         dialog.dismiss();
  198.                     }
  199.                     //move to all event activity
  200.                     toEventList = new Intent(getApplicationContext(), AllEvents.class);
  201.                     startActivity(toEventList);
  202.                 }
  203.  
  204.                 @Override
  205.                 public void onCancelled(DatabaseError databaseError) {
  206.                     System.out.println("The read failed: " + databaseError.getCode());
  207.                     if(dialog!=null){
  208.                         dialog.dismiss();
  209.                     }
  210.                 }
  211.             });
  212.         }
  213.     }
  214.  
  215.  
  216.  /*   private void register(){
  217.         mAuth.createUserWithEmailAndPassword("arel601@gmail.com", "arel1234")
  218.                 .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  219.                     @Override
  220.                     public void onComplete(@NonNull Task<AuthResult> task) {
  221.                         if (task.isSuccessful()) {
  222.                             // Sign in success, update UI with the signed-in user's information
  223.                      //       Log.d(TAG, "createUserWithEmail:success");
  224.                             final FirebaseDatabase database = FirebaseDatabase.getInstance();
  225.                             DatabaseReference ref1 = database.getReference();
  226.                             FirebaseUser user = mAuth.getCurrentUser();
  227.                             ref1.child("Users").child(user.getUid()).setValue(new ServerUser(user.getUid(),"Moshe","Smith",false,
  228.                                     1));
  229.                             updateUI(user);
  230.                         } else {
  231.                             // If sign in fails, display a message to the user.
  232.                    //         Log.w(TAG, "createUserWithEmail:failure", task.getException());
  233.                    //         Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
  234.                      //               Toast.LENGTH_SHORT).show();
  235.                             updateUI(null);
  236.                         }
  237.  
  238.                         // ...
  239.                     }
  240.                 });
  241.     }
  242. */
  243.  
  244.  
  245.  
  246.  
  247.  
  248.     /**
  249.      * overrides the back press fucntion
  250.      */
  251.     @Override
  252.     public void onBackPressed() {
  253.         Log.d("2","Back was pressed all events");
  254.         //presents a dialog that asks if you would like to quit the application
  255.         final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Login.this);
  256.         alertDialogBuilder.setTitle("Are you sure you want to exit?");
  257.         alertDialogBuilder
  258.                 .setCancelable(true)
  259.                 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  260.                     public void onClick(DialogInterface dialog, int id) {
  261.                         //user want to quit
  262.                         dialog.cancel();
  263.                         Toast.makeText(getApplicationContext(),"Goodbye", Toast.LENGTH_LONG);
  264.                         exit();//quit
  265.  
  266.                     }
  267.                 })
  268.                 .setNegativeButton("No, im not sure", new DialogInterface.OnClickListener() {
  269.                     public void onClick(DialogInterface dialog, int id) {
  270.                         //user doesn't want to quit
  271.  
  272.                     }
  273.                 });
  274.         AlertDialog alertDialog = alertDialogBuilder.create();
  275.         alertDialog.show();
  276.  
  277.     }
  278.  
  279.     /**
  280.      * This function simply exits the application
  281.      */
  282.  
  283.     private void exit(){
  284.         Intent homeIntent = new Intent(Intent.ACTION_MAIN);
  285.         homeIntent.addCategory( Intent.CATEGORY_HOME );
  286.         homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  287.         startActivity(homeIntent);
  288.     }
  289. }
Add Comment
Please, Sign In to add comment