Guest User

dialog_issue2

a guest
Jan 28th, 2015
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.79 KB | None | 0 0
  1. /**
  2.  * A login screen that offers login via username/password
  3.  */
  4. public class LoginActivity extends ActionBarActivity
  5. {
  6.    // Keep track of the login task to ensure we can cancel it if requested.
  7.   private UserLoginTask mAuthTask = null;
  8.  
  9.   // UI references.
  10.   private AutoCompleteTextView mNickView;
  11.   private EditText mPasswordView;
  12.   private View mProgressView;
  13.   private View mScrollView;
  14.   private View mSignInButton;
  15.   private View mRegisterButton;
  16.   private AlertDialog mAlertDialog;
  17.   private EditText mMailEditText;
  18.  
  19.   private String mPassword;
  20.   private String mNickname;
  21.  
  22.   static final String SHARED_PREFERENCES = "SHRD_PREF";
  23.   static final String USER_NICKNAME = "USR_NICK";
  24.   static final String USER_PASSWORD = "USR_PWD";
  25.   private static final String DIALOG_CONTENT = "DIAL_CONT";
  26.   private static final String CLIENT_RESOURCE_REFERENCE = "CR_REFER";
  27.  
  28.   @Override
  29.   protected void onCreate(Bundle savedInstanceState)
  30.   {
  31.     super.onCreate(savedInstanceState);
  32.     setContentView(R.layout.activity_login);
  33.  
  34.     findViews();
  35.  
  36.     if (isCredentialsStoredYet())
  37.     {
  38.       attemptLoginOrRegister(UserTasks.LOGIN);
  39.     }
  40.     setListeners();
  41.   }
  42.  
  43.   private void findViews()
  44.   {
  45.     // Find the buttons.
  46.     mSignInButton = findViewById(R.id.activity_login_sign_in_button);
  47.     mRegisterButton = findViewById(R.id.activity_login_register_button);
  48.  
  49.     // Set up the login form.
  50.     mNickView = (AutoCompleteTextView) findViewById(R.id.activity_login_nick);
  51.     mProgressView = findViewById(R.id.activity_login_progress);
  52.     mScrollView = findViewById(R.id.activity_login_scrollview);
  53.     mPasswordView = (EditText) findViewById(R.id.activity_login_password);
  54.   }
  55.  
  56.   private AlertDialog.Builder buildDialog(String mailString)
  57.   {
  58.     final AlertDialog.Builder alertDialogBuilder =
  59.       new AlertDialog.Builder(LoginActivity.this);
  60.  
  61.     alertDialogBuilder.setTitle("Insert mail");
  62.     alertDialogBuilder.setMessage("email");
  63.     // Set an EditText view to get user input
  64.     mMailEditText = new EditText(getApplicationContext());
  65.     if (mailString != null)
  66.       mMailEditText.setText(mailString);
  67.     alertDialogBuilder.setView(mMailEditText);
  68.     alertDialogBuilder.setPositiveButton(
  69.       "Ok", new DialogInterface.OnClickListener()
  70.       {
  71.         public void onClick(DialogInterface dialog, int whichButton)
  72.         {
  73.           String email = mMailEditText.getText().toString();
  74.           if (!TextUtils.isEmpty(email) && !isEmailValid(
  75.             email))
  76.           {
  77.             String s = getString(
  78.               R.string
  79.                 .activity_login_error_invalid_email); //TODO delete this reference
  80.                 // after debug and place it inside setError below
  81.             mMailEditText.setError(s);
  82.             Toast.makeText(getApplicationContext(), "Hi", Toast.LENGTH_SHORT);
  83.           }
  84.           else
  85.           {
  86.             attemptLoginOrRegister(UserTasks.REGISTER, email);
  87.           }
  88.         }
  89.       });
  90.     alertDialogBuilder.setNegativeButton(
  91.       "Cancel", new DialogInterface.OnClickListener()
  92.       {
  93.         public void onClick(DialogInterface dialog, int whichButton)
  94.         {
  95.           dialog.cancel();
  96.         }
  97.       });
  98.  
  99.     mAlertDialog = alertDialogBuilder.create();
  100.     return alertDialogBuilder;
  101.   }
  102.  
  103.   private void setListeners()
  104.   {
  105.     mPasswordView.setOnEditorActionListener(
  106.       new TextView.OnEditorActionListener()
  107.       {
  108.         @Override
  109.         public boolean onEditorAction(
  110.           TextView textView, int id, KeyEvent keyEvent)
  111.         {
  112.           if (id == R.id.activity_login_imeaction
  113.             || id == EditorInfo.IME_NULL)
  114.           {
  115.             attemptLoginOrRegister(UserTasks.LOGIN);
  116.             return true;
  117.           }
  118.           return false;
  119.         }
  120.       });
  121.  
  122.     mSignInButton.setOnClickListener(
  123.       new View.OnClickListener()
  124.       {
  125.         @Override
  126.         public void onClick(View view)
  127.         {
  128.           attemptLoginOrRegister(UserTasks.LOGIN);
  129.         }
  130.       });
  131.  
  132.     mRegisterButton.setOnClickListener(
  133.       new View.OnClickListener()
  134.       {
  135.         @Override
  136.         public void onClick(View v)
  137.         {
  138.           buildDialog(null).show();
  139.         }
  140.       });
  141.   }
  142.  
  143.  
  144.   /* Check if the user has already stored its credentials before
  145.    */
  146.   private boolean isCredentialsStoredYet()
  147.   {
  148.     SharedPreferences sp = getSharedPreferences(
  149.       SHARED_PREFERENCES, MODE_PRIVATE);
  150.  
  151.     mPassword = sp.getString(USER_PASSWORD, null);
  152.     mNickname = sp.getString(USER_NICKNAME, null);
  153.  
  154.     return mPassword != null && mNickname != null;
  155.   }
  156.  
  157.  
  158.   /*
  159.    * Attempts to sign in or register with the account specified by the login
  160.    * form.
  161.    * If there are form errors (invalid email, missing fields, etc.), the
  162.    * errors are presented and no actual login attempt is made.
  163.    */
  164.   private void attemptLoginOrRegister(UserTasks taskType, String... params)
  165.   {
  166.     if (mAuthTask != null) return;
  167.  
  168.     // Reset errors.
  169.     mNickView.setError(null);
  170.     mPasswordView.setError(null);
  171.  
  172.     // Check if the user was already stored
  173.     if (mNickname == null || mPassword == null)
  174.     {
  175.       mNickname = mNickView.getText().toString();
  176.       mPassword = mPasswordView.getText().toString();
  177.     }
  178.  
  179.     // Store values at the time of the login attempt.
  180.     boolean cancel = false;
  181.     View focusView = null;
  182.  
  183.     // Check for a valid password, if the user entered one.
  184.     if (!TextUtils.isEmpty(mPassword) && !isPasswordValid(mPassword))
  185.     {
  186.       mPasswordView.setError(
  187.         getResources().getString(
  188.           R.string.activity_login_error_invalid_password));
  189.       focusView = mPasswordView;
  190.       cancel = true;
  191.     }
  192.  
  193.     // Check for a valid nick.
  194.     if (TextUtils.isEmpty(mNickname))
  195.     {
  196.       mNickView
  197.         .setError(
  198.           //getString(R.string.activity_login_error_field_required));
  199.           "Error");
  200.       focusView = mNickView;
  201.       cancel = true;
  202.     }
  203.     else if (!isNickValid(mNickname))
  204.     {
  205.       mNickView
  206.         .setError(getString(R.string.activity_login_error_invalid_nickname));
  207.       focusView = mNickView;
  208.       cancel = true;
  209.     }
  210.  
  211.     if (cancel)
  212.     {
  213.       // There was an error; don't attempt login and focus the first
  214.       // form field with an error.
  215.       focusView.requestFocus();
  216.     }
  217.     else
  218.     {
  219.       // Show a progress spinner, and kick off a background task to
  220.       // perform the user login attempt.
  221.       showProgress(true);
  222.       CheckBox checkBox = (CheckBox) findViewById(
  223.         R.id
  224.           .activity_login_remember_checkBox);
  225.       if (checkBox.isChecked())
  226.       { storeCredentials(); }
  227.       mAuthTask = new UserLoginTask(mNickname, mPassword, taskType);
  228.       mAuthTask.execute(params);
  229.     }
  230.   }
  231.  
  232.   private void storeCredentials()
  233.   {
  234.     SharedPreferences.Editor editor = getSharedPreferences
  235.       (SHARED_PREFERENCES, MODE_PRIVATE).edit();
  236.     editor.putString(USER_NICKNAME, mNickname);
  237.     editor.putString(USER_PASSWORD, mPassword);
  238.     editor.apply();
  239.   }
  240.  
  241.   private boolean isNickValid(String nick)
  242.   {
  243.     //Actually, the user can insert any character as nickname
  244.     return nick != null && !nick.isEmpty();
  245.   }
  246.  
  247.   private boolean isEmailValid(String email)
  248.   {
  249.     return email.contains("@") && email.contains(".") && !email.contains(" ");
  250.   }
  251.  
  252.   private boolean isPasswordValid(String password)
  253.   {
  254.     return !(password.length() < 6 || password.contains(" "));
  255.   }
  256.  
  257.   /**
  258.    * Shows the progress UI and hides the login form.
  259.    */
  260.   @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
  261.   public void showProgress(final boolean show)
  262.   {
  263.     // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
  264.     // for very easy animations. If available, use these APIs to fade-in
  265.     // the progress spinner.
  266.     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
  267.     {
  268.       int shortAnimTime =
  269.         getResources().getInteger(android.R.integer.config_shortAnimTime);
  270.  
  271.       mScrollView.setVisibility(show ? View.GONE : View.VISIBLE);
  272.       mScrollView.animate().setDuration(shortAnimTime).alpha(
  273.         show ? 0 : 1).setListener(
  274.         new AnimatorListenerAdapter()
  275.         {
  276.           @Override
  277.           public void onAnimationEnd(Animator animation)
  278.           {
  279.             mScrollView.setVisibility(show ? View.GONE : View.VISIBLE);
  280.           }
  281.         });
  282.  
  283.       mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  284.       mProgressView.animate().setDuration(shortAnimTime).alpha(
  285.         show ? 1 : 0).setListener(
  286.         new AnimatorListenerAdapter()
  287.         {
  288.           @Override
  289.           public void onAnimationEnd(Animator animation)
  290.           {
  291.             mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  292.           }
  293.         });
  294.     }
  295.     else
  296.     {
  297.       // The ViewPropertyAnimator APIs are not available, so simply show
  298.       // and hide the relevant UI components.
  299.       mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  300.       mScrollView.setVisibility(show ? View.GONE : View.VISIBLE);
  301.     }
  302.   }
  303.  
  304.  
  305.   public enum UserTasks
  306.   {
  307.     LOGIN, REGISTER
  308.   }
  309.  
  310.   /**
  311.    * Represents an asynchronous login/registration task used to authenticate
  312.    * the user.
  313.    */
  314.   public class UserLoginTask extends AsyncTask<String, Void, Boolean>
  315.   {
  316.     private final String mNick;
  317.     private final String mPassword;
  318.     private final UserTasks mTaskType;
  319.     private int mIdResponseCode;
  320.  
  321.     UserLoginTask(String nick, String password, UserTasks taskType)
  322.     {
  323.       mNick = nick;
  324.       mPassword = password;
  325.       mTaskType = taskType;
  326.     }
  327.  
  328.     @Override
  329.     protected Boolean doInBackground(String... params)
  330.     {
  331.       mIdResponseCode = 0;
  332.       switch (mTaskType)
  333.       {
  334.         case LOGIN:
  335.         {
  336.           mIdResponseCode = 1;
  337.           return true;
  338.         }
  339.         case REGISTER:
  340.         {
  341.           mIdResponseCode = 2;
  342.           return true;
  343.         }
  344.         default:
  345.           return false;
  346.       }
  347.     }
  348.  
  349.     @Override
  350.     protected void onPostExecute(final Boolean success)
  351.     {
  352.       mAuthTask = null;
  353.       showProgress(false);
  354.  
  355.       if (success) finish();
  356.       else
  357.       {
  358.         if (mIdResponseCode <= 0)
  359.         {
  360.             mPasswordView.setError(
  361.               getString(R.string.activity_login_error_unauthorized));
  362.             mPasswordView.requestFocus();
  363.             SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences
  364.               (LoginActivity.SHARED_PREFERENCES, MODE_PRIVATE).edit();
  365.             editor.remove(LoginActivity.USER_NICKNAME);
  366.             editor.remove(LoginActivity.USER_PASSWORD);
  367.             editor.apply();
  368.         }
  369.       }
  370.     }
  371.  
  372.     @Override
  373.     protected void onCancelled()
  374.     {
  375.       mAuthTask = null;
  376.       showProgress(false);
  377.     }
  378. }
Advertisement
Add Comment
Please, Sign In to add comment