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