Guest User

Untitled

a guest
Mar 31st, 2016
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.44 KB | None | 0 0
  1. package com.dattz.sprout.activities;
  2.  
  3. import android.animation.Animator;
  4. import android.animation.AnimatorListenerAdapter;
  5. import android.annotation.TargetApi;
  6. import android.content.BroadcastReceiver;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.SharedPreferences;
  10. import android.os.AsyncTask;
  11. import android.os.Build;
  12. import android.os.Bundle;
  13. import android.support.v7.app.AppCompatActivity;
  14. import android.text.TextUtils;
  15. import android.view.KeyEvent;
  16. import android.view.View;
  17. import android.view.View.OnClickListener;
  18. import android.view.inputmethod.EditorInfo;
  19. import android.widget.Button;
  20. import android.widget.EditText;
  21. import android.widget.TextView;
  22. import android.widget.Toast;
  23.  
  24. import com.dattz.sprout.R;
  25. import com.dattz.sprout.exceptions.FailedToConnectException;
  26. import com.dattz.sprout.helpers.Helper;
  27. import com.dattz.sprout.helpers.Server;
  28.  
  29. import org.json.JSONException;
  30. import org.json.JSONObject;
  31.  
  32. import java.io.IOException;
  33.  
  34. /**
  35.  * A login screen that offers login via email/password.
  36.  */
  37. public class LoginActivity extends AppCompatActivity {
  38.  
  39.     private static final String TAG = LoginActivity.class.getSimpleName();
  40.     private UserLoginTask mAuthTask = null;
  41.  
  42.     // UI references.
  43.     private EditText mEmailView;
  44.     private EditText mPasswordView;
  45.     private View mProgressView;
  46.     private View mLoginFormView;
  47.  
  48.     private SharedPreferences spUser;
  49.  
  50.     private BroadcastReceiver mRegistrationBroadcastReceiver;
  51.  
  52.     @Override
  53.     protected void onCreate(Bundle savedInstanceState) {
  54.         super.onCreate(savedInstanceState);
  55.         setContentView(R.layout.activity_login);
  56.         // Set up the login form.
  57.         mEmailView = (EditText) findViewById(R.id.email);
  58.         mPasswordView = (EditText) findViewById(R.id.password);
  59.         mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
  60.             @Override
  61.             public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
  62.                 if (id == R.id.login || id == EditorInfo.IME_NULL) {
  63.                     attemptLogin();
  64.                     return true;
  65.                 }
  66.                 return false;
  67.             }
  68.         });
  69.  
  70.         Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
  71.         mEmailSignInButton.setOnClickListener(new OnClickListener() {
  72.             @Override
  73.             public void onClick(View view) {
  74.                 attemptLogin();
  75.             }
  76.         });
  77.  
  78.         mLoginFormView = findViewById(R.id.login_form);
  79.         mProgressView = findViewById(R.id.login_progress);
  80.  
  81.         spUser = getSharedPreferences(Helper.PREFERENCES_USER, Context.MODE_PRIVATE);
  82.         if (spUser.contains("email")) {
  83.             showProgress(true);
  84.             Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
  85.             LoginActivity.this.startActivity(intent);
  86.         }
  87.     }
  88.  
  89.     /**
  90.      * Attempts to sign in or register the account specified by the login form.
  91.      * If there are form errors (invalid email, missing fields, etc.), the
  92.      * errors are presented and no actual login attempt is made.
  93.      */
  94.     private void attemptLogin() {
  95.         if (mAuthTask != null) {
  96.             return;
  97.         }
  98.  
  99.         // Reset errors.
  100.         mEmailView.setError(null);
  101.         mPasswordView.setError(null);
  102.  
  103.         // Store values at the time of the login attempt.
  104.         String email = mEmailView.getText().toString();
  105.         String password = mPasswordView.getText().toString();
  106.  
  107.         boolean cancel = false;
  108.         View focusView = null;
  109.  
  110.         // Check for a valid password, if the user entered one.
  111.         if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
  112.             mPasswordView.setError(getString(R.string.error_invalid_password));
  113.             focusView = mPasswordView;
  114.             cancel = true;
  115.         }
  116.  
  117.         // Check for a valid email address.
  118.         if (TextUtils.isEmpty(email)) {
  119.             mEmailView.setError(getString(R.string.error_field_required));
  120.             focusView = mEmailView;
  121.             cancel = true;
  122.         } else if (!isEmailValid(email)) {
  123.             mEmailView.setError(getString(R.string.error_invalid_email));
  124.             focusView = mEmailView;
  125.             cancel = true;
  126.         }
  127.  
  128.         if (cancel) {
  129.             // There was an error; don't attempt login and focus the first
  130.             // form field with an error.
  131.             focusView.requestFocus();
  132.         } else {
  133.             // Show a progress spinner, and kick off a background task to
  134.             // perform the user login attempt.
  135.             showProgress(true);
  136.             mAuthTask = new UserLoginTask(email, password);
  137.             mAuthTask.execute((Void) null);
  138.         }
  139.     }
  140.  
  141.     private boolean isEmailValid(String email) {
  142.         return email.contains("@");
  143.     }
  144.  
  145.     private boolean isPasswordValid(String password) {
  146.         return password.length() > 4;
  147.     }
  148.  
  149.     /**
  150.      * Shows the progress UI and hides the login form.
  151.      */
  152.     @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
  153.     private void showProgress(final boolean show) {
  154.         if (show) Helper.hideKeyboard(this);
  155.         else mEmailView.requestFocus();
  156.  
  157.         // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
  158.         // for very easy animations. If available, use these APIs to fade-in
  159.         // the progress spinner.
  160.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
  161.             int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
  162.  
  163.             mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  164.             mLoginFormView.animate().setDuration(shortAnimTime).alpha(
  165.                     show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
  166.                 @Override
  167.                 public void onAnimationEnd(Animator animation) {
  168.                     mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  169.                 }
  170.             });
  171.  
  172.             mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  173.             mProgressView.animate().setDuration(shortAnimTime).alpha(
  174.                     show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
  175.                 @Override
  176.                 public void onAnimationEnd(Animator animation) {
  177.                     mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  178.                 }
  179.             });
  180.         } else {
  181.             // The ViewPropertyAnimator APIs are not available, so simply show
  182.             // and hide the relevant UI components.
  183.             mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  184.             mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  185.         }
  186.  
  187.  
  188.     }
  189.  
  190.     /**
  191.      * Represents an asynchronous login/registration task used to authenticate
  192.      * the user.
  193.      */
  194.     public class UserLoginTask extends AsyncTask<Void, Void, JSONObject> {
  195.  
  196.         private final String mEmail;
  197.         private final String mPassword;
  198.  
  199.         private boolean connectionFail = false;
  200.  
  201.         UserLoginTask(String email, String password) {
  202.             mEmail = email;
  203.             mPassword = password;
  204.         }
  205.  
  206.         @Override
  207.         protected JSONObject doInBackground(Void... params) {
  208.             try {
  209.                 return Server.attemptLogin(mEmail, mPassword);
  210.             } catch (IOException e) {
  211.                 connectionFail = true;
  212.             } catch (FailedToConnectException e) {
  213.                 connectionFail = true;
  214.             } catch (JSONException e) {
  215.                 connectionFail = true;
  216.             }
  217.             return null;
  218.         }
  219.  
  220.         protected void onPostExecute(final JSONObject jo) {
  221.             mAuthTask = null;
  222.             showProgress(false);
  223.  
  224.             if (jo != null) {
  225.                 try {
  226.                     if (jo.getString("status").equals(Helper.JSON_ERROR))
  227.                         throw new Exception();
  228.  
  229.                     // Login User:
  230.                     SharedPreferences.Editor editor = spUser.edit();
  231.                     editor.putString("email", jo.getString("email"));
  232.                     editor.putString("name", jo.getString("name"));
  233.                     editor.apply();
  234.  
  235.                     Toast.makeText(LoginActivity.this, "Logged in as " + jo.getString("name"),
  236.                             Toast.LENGTH_SHORT).show();
  237.  
  238.                     // Move to Home Activity
  239.                     Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
  240.                     LoginActivity.this.startActivity(intent);
  241.                 } catch (Exception e) { // We are mainly catching the JSONException.
  242.                     mPasswordView.setError(getString(R.string.error_incorrect_password));
  243.                     mPasswordView.requestFocus();
  244.                 }
  245.             }
  246.             else if (connectionFail == true) {
  247.                 Toast.makeText(LoginActivity.this, "There was a problem while connecting to the server.", Toast.LENGTH_SHORT).show();
  248.                 mEmailView.requestFocus();
  249.             }
  250.             else {
  251.                 mPasswordView.setError(getString(R.string.error_incorrect_password));
  252.                 mPasswordView.requestFocus();
  253.             }
  254.  
  255.         }
  256.  
  257.         @Override
  258.         protected void onCancelled() {
  259.             mAuthTask = null;
  260.             showProgress(false);
  261.         }
  262.     }
  263. }
Add Comment
Please, Sign In to add comment