Advertisement
Guest User

Untitled

a guest
Sep 5th, 2017
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.88 KB | None | 0 0
  1. package com.example.fetch;
  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.  
  36. import android.util.Log;
  37. import android.os.Bundle;
  38. import android.text.TextUtils;
  39. import android.util.Log;
  40. import android.view.View;
  41. import android.widget.EditText;
  42. import android.widget.TextView;
  43. import android.widget.Toast;
  44.  
  45. import static android.Manifest.permission.READ_CONTACTS;
  46.  
  47. import com.google.android.gms.tasks.OnCompleteListener;
  48. import com.google.android.gms.tasks.Task;
  49. import com.google.firebase.auth.AuthResult;
  50. import com.google.firebase.auth.FirebaseAuth;
  51. import com.google.firebase.auth.FirebaseUser;
  52.  
  53.  
  54. /**
  55. * A login screen that offers login via email/password.
  56. */
  57. public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
  58.  
  59. /**
  60. * Id to identity READ_CONTACTS permission request.
  61. */
  62. private static final int REQUEST_READ_CONTACTS = 0;
  63.  
  64.  
  65. //Firebase
  66. private FirebaseAuth mAuth;
  67. private FirebaseAuth.AuthStateListener mAuthListener;
  68. private static final String TAG = "EmailPassword";
  69.  
  70. /**
  71. * A dummy authentication store containing known user names and passwords.
  72. * TODO: remove after connecting to a real authentication system.
  73. */
  74. private static final String[] DUMMY_CREDENTIALS = new String[]{
  75. "foo@example.com:hello", "bar@example.com:world"
  76. };
  77. /**
  78. * Keep track of the login task to ensure we can cancel it if requested.
  79. */
  80. private UserLoginTask mAuthTask = null;
  81.  
  82. // UI references.
  83. private AutoCompleteTextView mEmailView;
  84. private EditText mPasswordView;
  85. private View mProgressView;
  86. private View mLoginFormView;
  87.  
  88. @Override
  89. protected void onCreate(Bundle savedInstanceState) {
  90. super.onCreate(savedInstanceState);
  91. setContentView(R.layout.activity_login);
  92.  
  93.  
  94. // Set up the login form.
  95. mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
  96. //populateAutoComplete();
  97.  
  98. mPasswordView = (EditText) findViewById(R.id.password);
  99. mLoginFormView = findViewById(R.id.login_form);
  100. mProgressView = findViewById(R.id.login_progress);
  101. // findViewById(R.id.email_sign_in_button).setOnClickListener(this);
  102. // findViewById(R.id.email_create_account_button).setOnClickListener(this);
  103.  
  104.  
  105.  
  106. // mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
  107. // @Override
  108. // public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
  109. // if (id == R.id.login || id == EditorInfo.IME_NULL) {
  110. // attemptLogin();
  111. // return true;
  112. // }
  113. // return false;
  114. // }
  115. // });
  116. mAuth = FirebaseAuth.getInstance();
  117. Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
  118. mEmailSignInButton.setOnClickListener(new OnClickListener() {
  119. @Override
  120. public void onClick(View view) {
  121.  
  122. // mAuthListener = new FirebaseAuth.AuthStateListener() {
  123. // @Override
  124. // public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
  125. // FirebaseUser user = firebaseAuth.getCurrentUser();
  126. // if (user != null) {
  127. // // User is signed in
  128. // Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
  129. // } else {
  130. // // User is signed out
  131. // Log.d(TAG, "onAuthStateChanged:signed_out");
  132. // }
  133. // // ...
  134. // }
  135. // };
  136. String email = mEmailView.getText().toString();
  137. String password = mPasswordView.getText().toString();
  138. Log.d(TAG, "Account:" + email + " " + password);
  139.  
  140. createAccount(email,password);
  141. }
  142. });
  143. }
  144.  
  145.  
  146. private void createAccount(String email, String password) {
  147. Log.d(TAG, "createAccount:" + email);
  148. mAuth.createUserWithEmailAndPassword(email, password)
  149. .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  150. @Override
  151. public void onComplete(@NonNull Task<AuthResult> task) {
  152. Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
  153. if (!task.isSuccessful()) {
  154. Toast.makeText(LoginActivity.this, "Authentication failed.",
  155. Toast.LENGTH_SHORT).show();
  156. }
  157. }
  158. });
  159. // [END create_user_with_email]
  160. }
  161.  
  162. private void populateAutoComplete() {
  163. if (!mayRequestContacts()) {
  164. return;
  165. }
  166.  
  167. getLoaderManager().initLoader(0, null, this);
  168. }
  169.  
  170. private boolean mayRequestContacts() {
  171. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
  172. return true;
  173. }
  174. if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
  175. return true;
  176. }
  177. if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
  178. Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
  179. .setAction(android.R.string.ok, new View.OnClickListener() {
  180. @Override
  181. @TargetApi(Build.VERSION_CODES.M)
  182. public void onClick(View v) {
  183. requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
  184. }
  185. });
  186. } else {
  187. requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
  188. }
  189. return false;
  190. }
  191.  
  192. /**
  193. * Callback received when a permissions request has been completed.
  194. */
  195. @Override
  196. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
  197. @NonNull int[] grantResults) {
  198. if (requestCode == REQUEST_READ_CONTACTS) {
  199. if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  200. populateAutoComplete();
  201. }
  202. }
  203. }
  204.  
  205.  
  206. /**
  207. * Attempts to sign in or register the account specified by the login form.
  208. * If there are form errors (invalid email, missing fields, etc.), the
  209. * errors are presented and no actual login attempt is made.
  210. */
  211. private void attemptLogin() {
  212. if (mAuthTask != null) {
  213. return;
  214. }
  215.  
  216. // Reset errors.
  217. mEmailView.setError(null);
  218. mPasswordView.setError(null);
  219.  
  220. // Store values at the time of the login attempt.
  221. String email = mEmailView.getText().toString();
  222. String password = mPasswordView.getText().toString();
  223.  
  224. boolean cancel = false;
  225. View focusView = null;
  226.  
  227. // Check for a valid password, if the user entered one.
  228. if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
  229. mPasswordView.setError(getString(R.string.error_invalid_password));
  230. focusView = mPasswordView;
  231. cancel = true;
  232. }
  233.  
  234. // Check for a valid email address.
  235. if (TextUtils.isEmpty(email)) {
  236. mEmailView.setError(getString(R.string.error_field_required));
  237. focusView = mEmailView;
  238. cancel = true;
  239. } else if (!isEmailValid(email)) {
  240. mEmailView.setError(getString(R.string.error_invalid_email));
  241. focusView = mEmailView;
  242. cancel = true;
  243. }
  244.  
  245. if (cancel) {
  246. // There was an error; don't attempt login and focus the first
  247. // form field with an error.
  248. focusView.requestFocus();
  249. } else {
  250. // Show a progress spinner, and kick off a background task to
  251. // perform the user login attempt.
  252. showProgress(true);
  253. mAuthTask = new UserLoginTask(email, password);
  254. mAuthTask.execute((Void) null);
  255. }
  256. }
  257.  
  258. private boolean isEmailValid(String email) {
  259. //TODO: Replace this with your own logic
  260. return email.contains("@");
  261. }
  262.  
  263. private boolean isPasswordValid(String password) {
  264. //TODO: Replace this with your own logic
  265. return password.length() > 4;
  266. }
  267.  
  268. /**
  269. * Shows the progress UI and hides the login form.
  270. */
  271. @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
  272. private void showProgress(final boolean show) {
  273. // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
  274. // for very easy animations. If available, use these APIs to fade-in
  275. // the progress spinner.
  276. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
  277. int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
  278.  
  279. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  280. mLoginFormView.animate().setDuration(shortAnimTime).alpha(
  281. show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
  282. @Override
  283. public void onAnimationEnd(Animator animation) {
  284. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  285. }
  286. });
  287.  
  288. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  289. mProgressView.animate().setDuration(shortAnimTime).alpha(
  290. show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
  291. @Override
  292. public void onAnimationEnd(Animator animation) {
  293. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  294. }
  295. });
  296. } else {
  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. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  301. }
  302. }
  303.  
  304. @Override
  305. public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
  306. return new CursorLoader(this,
  307. // Retrieve data rows for the device user's 'profile' contact.
  308. Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
  309. ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
  310.  
  311. // Select only email addresses.
  312. ContactsContract.Contacts.Data.MIMETYPE +
  313. " = ?", new String[]{ContactsContract.CommonDataKinds.Email
  314. .CONTENT_ITEM_TYPE},
  315.  
  316. // Show primary email addresses first. Note that there won't be
  317. // a primary email address if the user hasn't specified one.
  318. ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
  319. }
  320.  
  321. @Override
  322. public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
  323. List<String> emails = new ArrayList<>();
  324. cursor.moveToFirst();
  325. while (!cursor.isAfterLast()) {
  326. emails.add(cursor.getString(ProfileQuery.ADDRESS));
  327. cursor.moveToNext();
  328. }
  329.  
  330. addEmailsToAutoComplete(emails);
  331. }
  332.  
  333. @Override
  334. public void onLoaderReset(Loader<Cursor> cursorLoader) {
  335.  
  336. }
  337.  
  338. private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
  339. //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
  340. ArrayAdapter<String> adapter =
  341. new ArrayAdapter<>(LoginActivity.this,
  342. android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
  343.  
  344. mEmailView.setAdapter(adapter);
  345. }
  346.  
  347.  
  348. private interface ProfileQuery {
  349. String[] PROJECTION = {
  350. ContactsContract.CommonDataKinds.Email.ADDRESS,
  351. ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
  352. };
  353.  
  354. int ADDRESS = 0;
  355. int IS_PRIMARY = 1;
  356. }
  357.  
  358. /**
  359. * Represents an asynchronous login/registration task used to authenticate
  360. * the user.
  361. */
  362. public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
  363.  
  364. private final String mEmail;
  365. private final String mPassword;
  366.  
  367. UserLoginTask(String email, String password) {
  368. mEmail = email;
  369. mPassword = password;
  370. }
  371.  
  372. @Override
  373. protected Boolean doInBackground(Void... params) {
  374. // TODO: attempt authentication against a network service.
  375.  
  376. try {
  377. // Simulate network access.
  378. Thread.sleep(2000);
  379. } catch (InterruptedException e) {
  380. return false;
  381. }
  382.  
  383. for (String credential : DUMMY_CREDENTIALS) {
  384. String[] pieces = credential.split(":");
  385. if (pieces[0].equals(mEmail)) {
  386. // Account exists, return true if the password matches.
  387. return pieces[1].equals(mPassword);
  388. }
  389. }
  390.  
  391. // TODO: register the new account here.
  392. return true;
  393. }
  394.  
  395. @Override
  396. protected void onPostExecute(final Boolean success) {
  397. mAuthTask = null;
  398. showProgress(false);
  399.  
  400. if (success) {
  401. finish();
  402. } else {
  403. mPasswordView.setError(getString(R.string.error_incorrect_password));
  404. mPasswordView.requestFocus();
  405. }
  406. }
  407.  
  408. @Override
  409. protected void onCancelled() {
  410. mAuthTask = null;
  411. showProgress(false);
  412. }
  413.  
  414.  
  415. }
  416. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement