Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import android.animation.Animator;
- import android.animation.AnimatorListenerAdapter;
- import android.annotation.TargetApi;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.content.SharedPreferences;
- import android.os.AsyncTask;
- import android.os.Build;
- import android.os.Bundle;
- import android.support.v7.app.ActionBarActivity;
- import android.text.TextUtils;
- import android.view.KeyEvent;
- import android.view.View;
- import android.view.inputmethod.EditorInfo;
- import android.widget.AutoCompleteTextView;
- import android.widget.CheckBox;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- /**
- * A login screen that offers login via username/password
- */
- public class LoginActivity extends ActionBarActivity
- {
- // Keep track of the login task to ensure we can cancel it if requested.
- private UserLoginTask mAuthTask = null;
- // UI references.
- private AutoCompleteTextView mNickView;
- private EditText mPasswordView;
- private View mProgressView;
- private View mScrollView;
- private View mSignInButton;
- private View mRegisterButton;
- private AlertDialog mAlertDialog;
- private EditText mMailEditText;
- private String mPassword;
- private String mNickname;
- private static final String SHARED_PREFERENCES = "SHRD_PREF";
- private static final String USER_NICKNAME = "USR_NICK";
- private static final String USER_PASSWORD = "USR_PWD";
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- findViews();
- if (isCredentialsStoredYet())
- {
- attemptLoginOrRegister(UserTasks.LOGIN);
- }
- setListeners();
- }
- private void findViews()
- {
- // Find the buttons.
- mSignInButton = findViewById(R.id.activity_login_sign_in_button);
- mRegisterButton = findViewById(R.id.activity_login_register_button);
- // Set up the login form.
- mNickView = (AutoCompleteTextView) findViewById(R.id.activity_login_nick);
- mProgressView = findViewById(R.id.activity_login_progress);
- mScrollView = findViewById(R.id.activity_login_scrollview);
- mPasswordView = (EditText) findViewById(R.id.activity_login_password);
- }
- private AlertDialog.Builder buildDialog(String mailString)
- {
- final AlertDialog.Builder alertDialogBuilder =
- new AlertDialog.Builder(LoginActivity.this);
- alertDialogBuilder.setTitle("Insert mail");
- alertDialogBuilder.setMessage("email");
- // Set an EditText view to get user input
- mMailEditText = new EditText(LoginActivity.this);
- if (mailString != null)
- mMailEditText.setText(mailString);
- alertDialogBuilder.setView(mMailEditText);
- alertDialogBuilder.setPositiveButton(
- "Ok", new DialogInterface.OnClickListener()
- {
- public void onClick(DialogInterface dialog, int whichButton)
- {
- String email = mMailEditText.getText().toString();
- if (!TextUtils.isEmpty(email) && !isEmailValid(
- email))
- {
- String s = getString(
- R.string
- .activity_login_error_invalid_email); //TODO delete this reference
- // after debug and place it inside setError below
- mMailEditText.setError(s);
- Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT)
- .show();
- }
- else
- {
- attemptLoginOrRegister(UserTasks.REGISTER, email);
- }
- }
- });
- alertDialogBuilder.setNegativeButton(
- "Cancel", new DialogInterface.OnClickListener()
- {
- public void onClick(DialogInterface dialog, int whichButton)
- {
- dialog.cancel();
- }
- });
- mAlertDialog = alertDialogBuilder.create();
- return alertDialogBuilder;
- }
- private void setListeners()
- {
- mPasswordView.setOnEditorActionListener(
- new TextView.OnEditorActionListener()
- {
- @Override
- public boolean onEditorAction(
- TextView textView, int id, KeyEvent keyEvent)
- {
- if (id == R.id.activity_login_imeaction
- || id == EditorInfo.IME_NULL)
- {
- attemptLoginOrRegister(UserTasks.LOGIN);
- return true;
- }
- return false;
- }
- });
- mSignInButton.setOnClickListener(
- new View.OnClickListener()
- {
- @Override
- public void onClick(View view)
- {
- attemptLoginOrRegister(UserTasks.LOGIN);
- }
- });
- mRegisterButton.setOnClickListener(
- new View.OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- buildDialog(null).show();
- }
- });
- }
- /* Check if the user has already stored its credentials before
- */
- private boolean isCredentialsStoredYet()
- {
- SharedPreferences sp = getSharedPreferences(
- SHARED_PREFERENCES, MODE_PRIVATE);
- mPassword = sp.getString(USER_PASSWORD, null);
- mNickname = sp.getString(USER_NICKNAME, null);
- return mPassword != null && mNickname != null;
- }
- /*
- * Attempts to sign in or register with 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 attemptLoginOrRegister(UserTasks taskType, String... params)
- {
- if (mAuthTask != null) return;
- // Reset errors.
- mNickView.setError(null);
- mPasswordView.setError(null);
- // Check if the user was already stored
- if (mNickname == null || mPassword == null)
- {
- mNickname = mNickView.getText().toString();
- mPassword = mPasswordView.getText().toString();
- }
- // Store values at the time of the login attempt.
- boolean cancel = false;
- View focusView = null;
- // Check for a valid password, if the user entered one.
- if (!TextUtils.isEmpty(mPassword) && !isPasswordValid(mPassword))
- {
- mPasswordView.setError(
- getResources().getString(
- R.string.activity_login_error_invalid_password));
- focusView = mPasswordView;
- cancel = true;
- }
- // Check for a valid nick.
- if (TextUtils.isEmpty(mNickname))
- {
- mNickView
- .setError(
- getString(R.string.activity_login_error_field_required));
- focusView = mNickView;
- cancel = true;
- }
- else if (!isNickValid(mNickname))
- {
- mNickView
- .setError(getString(R.string.activity_login_error_invalid_nickname));
- focusView = mNickView;
- 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);
- CheckBox checkBox = (CheckBox) findViewById(
- R.id
- .activity_login_remember_checkBox);
- if (checkBox.isChecked())
- { storeCredentials(); }
- mAuthTask = new UserLoginTask(mNickname, mPassword, taskType);
- mAuthTask.execute(params);
- }
- }
- private void storeCredentials()
- {
- SharedPreferences.Editor editor = getSharedPreferences
- (SHARED_PREFERENCES, MODE_PRIVATE).edit();
- editor.putString(USER_NICKNAME, mNickname);
- editor.putString(USER_PASSWORD, mPassword);
- editor.apply();
- }
- private boolean isNickValid(String nick)
- {
- //Actually, the user can insert any character as nickname
- return nick != null && !nick.isEmpty();
- }
- private boolean isEmailValid(String email)
- {
- return email.contains("@") && email.contains(".") && !email.contains(" ");
- }
- private boolean isPasswordValid(String password)
- {
- return !(password.length() < 6 || password.contains(" "));
- }
- /**
- * Shows the progress UI and hides the login form.
- */
- @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
- public void showProgress(final boolean show)
- {
- // 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);
- mScrollView.setVisibility(show ? View.GONE : View.VISIBLE);
- mScrollView.animate().setDuration(shortAnimTime).alpha(
- show ? 0 : 1).setListener(
- new AnimatorListenerAdapter()
- {
- @Override
- public void onAnimationEnd(Animator animation)
- {
- mScrollView.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);
- mScrollView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- }
- public enum UserTasks
- {
- LOGIN, REGISTER
- }
- /**
- * Represents an asynchronous login/registration task used to authenticate
- * the user.
- */
- public class UserLoginTask extends AsyncTask<String, Void, Boolean>
- {
- private final String mNick;
- private final String mPassword;
- private final UserTasks mTaskType;
- private int mIdResponseCode;
- UserLoginTask(String nick, String password, UserTasks taskType)
- {
- mNick = nick;
- mPassword = password;
- mTaskType = taskType;
- }
- @Override
- protected Boolean doInBackground(String... params)
- {
- // This is a simplified version that doesn't require further libraries and an
- // Internet connection.
- mIdResponseCode = 0;
- switch (mTaskType)
- {
- case LOGIN:
- {
- mIdResponseCode = 1;
- return true;
- }
- case REGISTER:
- {
- mIdResponseCode = 2;
- return true;
- }
- default:
- mIdResponseCode = -1;
- return false;
- }
- }
- @Override
- protected void onPostExecute(final Boolean success)
- {
- mAuthTask = null;
- showProgress(false);
- if (success)
- {
- Toast.makeText(LoginActivity.this, "Hi", Toast.LENGTH_SHORT).show();
- finish();
- }
- else
- {
- if (mIdResponseCode <= 0)
- {
- mPasswordView.setError(
- getString(R.string.activity_login_error_unauthorized));
- mPasswordView.requestFocus();
- SharedPreferences.Editor editor =
- getApplicationContext().getSharedPreferences
- (LoginActivity.SHARED_PREFERENCES, MODE_PRIVATE).edit();
- editor.remove(LoginActivity.USER_NICKNAME);
- editor.remove(LoginActivity.USER_PASSWORD);
- editor.apply();
- }
- }
- }
- @Override
- protected void onCancelled()
- {
- mAuthTask = null;
- showProgress(false);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement