minafaw3

LoginActivity

Apr 14th, 2016
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.34 KB | None | 0 0
  1. package massive.com.nuwabna.Activities;
  2.  
  3. import android.animation.Animator;
  4. import android.animation.AnimatorListenerAdapter;
  5. import android.annotation.TargetApi;
  6. import android.content.pm.PackageManager;
  7. import android.support.annotation.NonNull;
  8. import android.support.design.widget.Snackbar;
  9. import android.support.v7.app.AppCompatActivity;
  10. import android.app.LoaderManager.LoaderCallbacks;
  11.  
  12. import android.content.CursorLoader;
  13. import android.content.Loader;
  14. import android.database.Cursor;
  15. import android.net.Uri;
  16. import android.os.AsyncTask;
  17.  
  18. import android.os.Build;
  19. import android.os.Bundle;
  20. import android.provider.ContactsContract;
  21. import android.text.TextUtils;
  22. import android.view.KeyEvent;
  23. import android.view.View;
  24. import android.view.View.OnClickListener;
  25. import android.view.inputmethod.EditorInfo;
  26. import android.widget.ArrayAdapter;
  27. import android.widget.AutoCompleteTextView;
  28. import android.widget.Button;
  29. import android.widget.EditText;
  30. import android.widget.TextView;
  31.  
  32. import java.util.ArrayList;
  33. import java.util.List;
  34.  
  35. import massive.com.nuwabna.R;
  36.  
  37. import static android.Manifest.permission.READ_CONTACTS;
  38.  
  39. /**
  40. * A login screen that offers login via email/password.
  41. */
  42. public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
  43.  
  44. /**
  45. * Id to identity READ_CONTACTS permission request.
  46. */
  47. private static final int REQUEST_READ_CONTACTS = 0;
  48.  
  49. /**
  50. * A dummy authentication store containing known user names and passwords.
  51. * TODO: remove after connecting to a real authentication system.
  52. */
  53. private static final String[] DUMMY_CREDENTIALS = new String[]{
  54. };
  55. /**
  56. * Keep track of the login task to ensure we can cancel it if requested.
  57. */
  58. private UserLoginTask mAuthTask = null;
  59.  
  60. // UI references.
  61. private AutoCompleteTextView mEmailView;
  62. private EditText mPasswordView;
  63. private View mProgressView;
  64. private View mLoginFormView;
  65.  
  66. @Override
  67. protected void onCreate(Bundle savedInstanceState) {
  68. super.onCreate(savedInstanceState);
  69. setContentView(R.layout.activity_login);
  70. // Set up the login form.
  71. mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
  72. populateAutoComplete();
  73.  
  74. mPasswordView = (EditText) findViewById(R.id.password);
  75. mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
  76. @Override
  77. public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
  78. if (id == R.id.login || id == EditorInfo.IME_NULL) {
  79. attemptLogin();
  80. return true;
  81. }
  82. return false;
  83. }
  84. });
  85.  
  86. Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
  87. mEmailSignInButton.setOnClickListener(new OnClickListener() {
  88. @Override
  89. public void onClick(View view) {
  90. attemptLogin();
  91. }
  92. });
  93.  
  94. mLoginFormView = findViewById(R.id.login_form);
  95. mProgressView = findViewById(R.id.login_progress);
  96. }
  97.  
  98. private void populateAutoComplete() {
  99. if (!mayRequestContacts()) {
  100. return;
  101. }
  102.  
  103. getLoaderManager().initLoader(0, null, this);
  104. }
  105.  
  106. private boolean mayRequestContacts() {
  107. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
  108. return true;
  109. }
  110. if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
  111. return true;
  112. }
  113. if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
  114. Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
  115. .setAction(android.R.string.ok, new View.OnClickListener() {
  116. @Override
  117. @TargetApi(Build.VERSION_CODES.M)
  118. public void onClick(View v) {
  119. requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
  120. }
  121. });
  122. } else {
  123. requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
  124. }
  125. return false;
  126. }
  127.  
  128. /**
  129. * Callback received when a permissions request has been completed.
  130. */
  131. @Override
  132. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
  133. @NonNull int[] grantResults) {
  134. if (requestCode == REQUEST_READ_CONTACTS) {
  135. if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  136. populateAutoComplete();
  137. }
  138. }
  139. }
  140.  
  141.  
  142. /**
  143. * Attempts to sign in or register the account specified by the login form.
  144. * If there are form errors (invalid email, missing fields, etc.), the
  145. * errors are presented and no actual login attempt is made.
  146. */
  147. private void attemptLogin() {
  148. if (mAuthTask != null) {
  149. return;
  150. }
  151.  
  152. // Reset errors.
  153. mEmailView.setError(null);
  154. mPasswordView.setError(null);
  155.  
  156. // Store values at the time of the login attempt.
  157. String email = mEmailView.getText().toString();
  158. String password = mPasswordView.getText().toString();
  159.  
  160. boolean cancel = false;
  161. View focusView = null;
  162.  
  163. // Check for a valid password, if the user entered one.
  164. if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
  165. mPasswordView.setError(getString(R.string.error_invalid_password));
  166. focusView = mPasswordView;
  167. cancel = true;
  168. }
  169.  
  170. // Check for a valid email address.
  171. if (TextUtils.isEmpty(email)) {
  172. mEmailView.setError(getString(R.string.error_field_required));
  173. focusView = mEmailView;
  174. cancel = true;
  175. } else if (!isEmailValid(email)) {
  176. mEmailView.setError(getString(R.string.error_invalid_email));
  177. focusView = mEmailView;
  178. cancel = true;
  179. }
  180.  
  181. if (cancel) {
  182. // There was an error; don't attempt login and focus the first
  183. // form field with an error.
  184. focusView.requestFocus();
  185. } else {
  186. // Show a progress spinner, and kick off a background task to
  187. // perform the user login attempt.
  188. showProgress(true);
  189. mAuthTask = new UserLoginTask(email, password);
  190. mAuthTask.execute((Void) null);
  191. }
  192. }
  193.  
  194. private boolean isEmailValid(String email) {
  195. //TODO: Replace this with your own logic
  196. return email.contains("@");
  197. }
  198.  
  199. private boolean isPasswordValid(String password) {
  200. //TODO: Replace this with your own logic
  201. return password.length() > 4;
  202. }
  203.  
  204. /**
  205. * Shows the progress UI and hides the login form.
  206. */
  207. @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
  208. private void showProgress(final boolean show) {
  209. // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
  210. // for very easy animations. If available, use these APIs to fade-in
  211. // the progress spinner.
  212. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
  213. int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
  214.  
  215. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  216. mLoginFormView.animate().setDuration(shortAnimTime).alpha(
  217. show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
  218. @Override
  219. public void onAnimationEnd(Animator animation) {
  220. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  221. }
  222. });
  223.  
  224. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  225. mProgressView.animate().setDuration(shortAnimTime).alpha(
  226. show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
  227. @Override
  228. public void onAnimationEnd(Animator animation) {
  229. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  230. }
  231. });
  232. } else {
  233. // The ViewPropertyAnimator APIs are not available, so simply show
  234. // and hide the relevant UI components.
  235. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  236. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  237. }
  238. }
  239.  
  240. @Override
  241. public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
  242. return new CursorLoader(this,
  243. // Retrieve data rows for the device user's 'profile' contact.
  244. Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
  245. ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
  246.  
  247. // Select only email addresses.
  248. ContactsContract.Contacts.Data.MIMETYPE +
  249. " = ?", new String[]{ContactsContract.CommonDataKinds.Email
  250. .CONTENT_ITEM_TYPE},
  251.  
  252. // Show primary email addresses first. Note that there won't be
  253. // a primary email address if the user hasn't specified one.
  254. ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
  255. }
  256.  
  257. @Override
  258. public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
  259. List<String> emails = new ArrayList<>();
  260. cursor.moveToFirst();
  261. while (!cursor.isAfterLast()) {
  262. emails.add(cursor.getString(ProfileQuery.ADDRESS));
  263. cursor.moveToNext();
  264. }
  265.  
  266. addEmailsToAutoComplete(emails);
  267. }
  268.  
  269. @Override
  270. public void onLoaderReset(Loader<Cursor> cursorLoader) {
  271.  
  272. }
  273.  
  274. private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
  275. //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
  276. ArrayAdapter<String> adapter =
  277. new ArrayAdapter<>(LoginActivity.this,
  278. android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
  279.  
  280. mEmailView.setAdapter(adapter);
  281. }
  282.  
  283.  
  284. private interface ProfileQuery {
  285. String[] PROJECTION = {
  286. ContactsContract.CommonDataKinds.Email.ADDRESS,
  287. ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
  288. };
  289.  
  290. int ADDRESS = 0;
  291. int IS_PRIMARY = 1;
  292. }
  293.  
  294. /**
  295. * Represents an asynchronous login/registration task used to authenticate
  296. * the user.
  297. */
  298. public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
  299.  
  300. private final String mEmail;
  301. private final String mPassword;
  302.  
  303. UserLoginTask(String email, String password) {
  304. mEmail = email;
  305. mPassword = password;
  306. }
  307.  
  308. @Override
  309. protected Boolean doInBackground(Void... params) {
  310. // TODO: attempt authentication against a network service.
  311.  
  312. try {
  313. // Simulate network access.
  314. Thread.sleep(2000);
  315. } catch (InterruptedException e) {
  316. return false;
  317. }
  318.  
  319. for (String credential : DUMMY_CREDENTIALS) {
  320. String[] pieces = credential.split(":");
  321. if (pieces[0].equals(mEmail)) {
  322. // Account exists, return true if the password matches.
  323. return pieces[1].equals(mPassword);
  324. }
  325. }
  326.  
  327. // TODO: register the new account here.
  328. return true;
  329. }
  330.  
  331. @Override
  332. protected void onPostExecute(final Boolean success) {
  333. mAuthTask = null;
  334. showProgress(false);
  335.  
  336. if (success) {
  337. finish();
  338. } else {
  339. mPasswordView.setError(getString(R.string.error_incorrect_password));
  340. mPasswordView.requestFocus();
  341. }
  342. }
  343.  
  344. @Override
  345. protected void onCancelled() {
  346. mAuthTask = null;
  347. showProgress(false);
  348. }
  349. }
  350. }
Advertisement
Add Comment
Please, Sign In to add comment