Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.dattz.sprout.activities;
- import android.animation.Animator;
- import android.animation.AnimatorListenerAdapter;
- import android.annotation.TargetApi;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.os.AsyncTask;
- import android.os.Build;
- import android.os.Bundle;
- import android.support.v7.app.AppCompatActivity;
- import android.text.TextUtils;
- import android.view.KeyEvent;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.inputmethod.EditorInfo;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.dattz.sprout.R;
- import com.dattz.sprout.exceptions.FailedToConnectException;
- import com.dattz.sprout.helpers.Helper;
- import com.dattz.sprout.helpers.Server;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.IOException;
- /**
- * A login screen that offers login via email/password.
- */
- public class LoginActivity extends AppCompatActivity {
- private static final String TAG = LoginActivity.class.getSimpleName();
- private UserLoginTask mAuthTask = null;
- // UI references.
- private EditText mEmailView;
- private EditText mPasswordView;
- private View mProgressView;
- private View mLoginFormView;
- private SharedPreferences spUser;
- private BroadcastReceiver mRegistrationBroadcastReceiver;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- // Set up the login form.
- mEmailView = (EditText) findViewById(R.id.email);
- mPasswordView = (EditText) findViewById(R.id.password);
- mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
- @Override
- public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
- if (id == R.id.login || id == EditorInfo.IME_NULL) {
- attemptLogin();
- return true;
- }
- return false;
- }
- });
- Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
- mEmailSignInButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- attemptLogin();
- }
- });
- mLoginFormView = findViewById(R.id.login_form);
- mProgressView = findViewById(R.id.login_progress);
- spUser = getSharedPreferences(Helper.PREFERENCES_USER, Context.MODE_PRIVATE);
- if (spUser.contains("email")) {
- showProgress(true);
- Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
- LoginActivity.this.startActivity(intent);
- }
- }
- /**
- * Attempts to sign in or register the account specified by the login form.
- * If there are form errors (invalid email, missing fields, etc.), the
- * errors are presented and no actual login attempt is made.
- */
- private void attemptLogin() {
- if (mAuthTask != null) {
- return;
- }
- // Reset errors.
- mEmailView.setError(null);
- mPasswordView.setError(null);
- // Store values at the time of the login attempt.
- String email = mEmailView.getText().toString();
- String password = mPasswordView.getText().toString();
- boolean cancel = false;
- View focusView = null;
- // Check for a valid password, if the user entered one.
- if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
- mPasswordView.setError(getString(R.string.error_invalid_password));
- focusView = mPasswordView;
- cancel = true;
- }
- // Check for a valid email address.
- if (TextUtils.isEmpty(email)) {
- mEmailView.setError(getString(R.string.error_field_required));
- focusView = mEmailView;
- cancel = true;
- } else if (!isEmailValid(email)) {
- mEmailView.setError(getString(R.string.error_invalid_email));
- focusView = mEmailView;
- cancel = true;
- }
- if (cancel) {
- // There was an error; don't attempt login and focus the first
- // form field with an error.
- focusView.requestFocus();
- } else {
- // Show a progress spinner, and kick off a background task to
- // perform the user login attempt.
- showProgress(true);
- mAuthTask = new UserLoginTask(email, password);
- mAuthTask.execute((Void) null);
- }
- }
- private boolean isEmailValid(String email) {
- return email.contains("@");
- }
- private boolean isPasswordValid(String password) {
- return password.length() > 4;
- }
- /**
- * Shows the progress UI and hides the login form.
- */
- @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
- private void showProgress(final boolean show) {
- if (show) Helper.hideKeyboard(this);
- else mEmailView.requestFocus();
- // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
- // for very easy animations. If available, use these APIs to fade-in
- // the progress spinner.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
- int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- mLoginFormView.animate().setDuration(shortAnimTime).alpha(
- show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- });
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mProgressView.animate().setDuration(shortAnimTime).alpha(
- show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- }
- });
- } else {
- // The ViewPropertyAnimator APIs are not available, so simply show
- // and hide the relevant UI components.
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- }
- /**
- * Represents an asynchronous login/registration task used to authenticate
- * the user.
- */
- public class UserLoginTask extends AsyncTask<Void, Void, JSONObject> {
- private final String mEmail;
- private final String mPassword;
- private boolean connectionFail = false;
- UserLoginTask(String email, String password) {
- mEmail = email;
- mPassword = password;
- }
- @Override
- protected JSONObject doInBackground(Void... params) {
- try {
- return Server.attemptLogin(mEmail, mPassword);
- } catch (IOException e) {
- connectionFail = true;
- } catch (FailedToConnectException e) {
- connectionFail = true;
- } catch (JSONException e) {
- connectionFail = true;
- }
- return null;
- }
- protected void onPostExecute(final JSONObject jo) {
- mAuthTask = null;
- showProgress(false);
- if (jo != null) {
- try {
- if (jo.getString("status").equals(Helper.JSON_ERROR))
- throw new Exception();
- // Login User:
- SharedPreferences.Editor editor = spUser.edit();
- editor.putString("email", jo.getString("email"));
- editor.putString("name", jo.getString("name"));
- editor.apply();
- Toast.makeText(LoginActivity.this, "Logged in as " + jo.getString("name"),
- Toast.LENGTH_SHORT).show();
- // Move to Home Activity
- Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
- LoginActivity.this.startActivity(intent);
- } catch (Exception e) { // We are mainly catching the JSONException.
- mPasswordView.setError(getString(R.string.error_incorrect_password));
- mPasswordView.requestFocus();
- }
- }
- else if (connectionFail == true) {
- Toast.makeText(LoginActivity.this, "There was a problem while connecting to the server.", Toast.LENGTH_SHORT).show();
- mEmailView.requestFocus();
- }
- else {
- mPasswordView.setError(getString(R.string.error_incorrect_password));
- mPasswordView.requestFocus();
- }
- }
- @Override
- protected void onCancelled() {
- mAuthTask = null;
- showProgress(false);
- }
- }
- }
Add Comment
Please, Sign In to add comment