Advertisement
Guest User

Untitled

a guest
Apr 20th, 2017
580
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.23 KB | None | 0 0
  1. package it.polito.mad17.viral.sliceapp;
  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.telephony.PhoneNumberUtils;
  22. import android.text.TextUtils;
  23. import android.util.Log;
  24. import android.view.KeyEvent;
  25. import android.view.View;
  26. import android.view.View.OnClickListener;
  27. import android.view.inputmethod.EditorInfo;
  28. import android.widget.ArrayAdapter;
  29. import android.widget.AutoCompleteTextView;
  30. import android.widget.Button;
  31. import android.widget.EditText;
  32. import android.widget.TextView;
  33. import android.widget.Toast;
  34.  
  35. import com.google.firebase.database.DataSnapshot;
  36. import com.google.firebase.database.DatabaseError;
  37. import com.google.firebase.database.DatabaseReference;
  38. import com.google.firebase.database.FirebaseDatabase;
  39. import com.google.firebase.database.ValueEventListener;
  40.  
  41. import java.util.ArrayList;
  42. import java.util.List;
  43. import java.util.Objects;
  44. import java.util.concurrent.CountDownLatch;
  45. import java.util.concurrent.Semaphore;
  46. import java.util.regex.Pattern;
  47. import java.lang.String;
  48.  
  49. import static android.Manifest.permission.READ_CONTACTS;
  50.  
  51. /**
  52. * A login screen that offers login via email/password.
  53. */
  54. public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
  55.  
  56.  
  57. /**
  58. * Id to identity READ_CONTACTS permission request.
  59. */
  60. private static final int REQUEST_READ_CONTACTS = 0;
  61.  
  62. /**
  63. * A dummy authentication store containing known user names and passwords.
  64. * TODO: remove after connecting to a real authentication system.
  65. */
  66. private static final String[] DUMMY_CREDENTIALS = new String[]{
  67. "foo@example.com:hello", "bar@example.com:world"
  68. };
  69. /**
  70. * Keep track of the login task to ensure we can cancel it if requested.
  71. */
  72. private UserLoginTask mAuthTask = null;
  73.  
  74. // UI references.
  75. private AutoCompleteTextView mPhoneView;
  76. private EditText mPasswordView;
  77. private View mProgressView;
  78. private View mLoginFormView;
  79. private String pwdDB,phoneDB;
  80. private boolean cancel = false;
  81. private View focusView = null;
  82. private boolean flag=false;
  83. private DatabaseReference db;
  84.  
  85. @Override
  86. protected void onCreate(Bundle savedInstanceState) {
  87. super.onCreate(savedInstanceState);
  88. setContentView(R.layout.activity_login);
  89. //Firebase.setAndroidContext(this);
  90. // Set up the login form.
  91. mPhoneView = (AutoCompleteTextView) findViewById(R.id.phoneNumber);
  92. populateAutoComplete();
  93.  
  94. mPasswordView = (EditText) findViewById(R.id.password);
  95. mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
  96. @Override
  97. public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
  98. if (id == R.id.login || id == EditorInfo.IME_NULL) {
  99. attemptLogin();
  100. return true;
  101. }
  102. return false;
  103. }
  104. });
  105. }
  106.  
  107. private void attemptLogin() {
  108. if (mAuthTask != null) {
  109. return;
  110. }
  111.  
  112. // Reset errors.
  113. mPhoneView.setError(null);
  114. mPasswordView.setError(null);
  115.  
  116. // Store values at the time of the login attempt.
  117. final String phone = mPhoneView.getText().toString();
  118. final String password = mPasswordView.getText().toString();
  119.  
  120.  
  121. boolean verifyMail = false;
  122.  
  123.  
  124. // Check for a valid phone number.
  125. if (phone.isEmpty()) {
  126. mPhoneView.requestFocus();
  127. mPhoneView.setError(getString(R.string.error_field_required));
  128. return;
  129. }
  130. if (isPhoneValid(phone) == false) {
  131. mPhoneView.requestFocus();
  132. mPhoneView.setError(getString(R.string.error_invalid_phone));
  133. return;
  134. /// / focusView = mPhoneView;
  135. // cancel = true;
  136. }
  137.  
  138. // Check for a valid password, if the user entered one.
  139. if (TextUtils.isEmpty(password)) {
  140. mPasswordView.requestFocus();
  141. mPasswordView.setError(getString(R.string.error_empty_password));
  142. return;
  143. }
  144. //Check for a password having the right length
  145. // 8 >= pwd <= 16
  146. if (isPasswordValid(password) == false) {
  147. mPasswordView.requestFocus();
  148. mPasswordView.setError(getString(R.string.error_short_password));
  149. return;
  150. }
  151.  
  152.  
  153. final CountDownLatch latch = new CountDownLatch(1);
  154. db = FirebaseDatabase.getInstance("https://sliceapp-a55d6.firebaseio.com/").getReference();
  155.  
  156. System.out.println("AAAAA " + db.child("Users").child(phone).toString());
  157.  
  158. // Thread t = new Thread(new Runnable() {
  159. // @Override
  160. // public void run() {
  161. db.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
  162.  
  163. @Override
  164. public void onDataChange(DataSnapshot dataSnapshot) {
  165. Log.d("BEFORE FOR CYCLE", "CIAO");
  166. //Log are never shown
  167. for (DataSnapshot d : dataSnapshot.getChildren()) {
  168. System.out.println("CCCCC " + d.getKey());
  169. if (d.getKey().equals(phone)) {
  170. phoneDB = d.getKey();
  171. System.out.println("Phone Number is " + phoneDB);
  172. pwdDB = d.child("password").getValue().toString();
  173. System.out.println("The password is " + pwdDB);
  174. }
  175. }
  176. // latch.countDown();
  177. }
  178.  
  179. @Override
  180. public void onCancelled(DatabaseError databaseError) {
  181. Log.d("FAILURE", databaseError.toString());
  182. }
  183.  
  184. });
  185.  
  186. //}
  187.  
  188. // });
  189.  
  190.  
  191.  
  192. // t.start();
  193.  
  194. // try {
  195. // latch.await();
  196. // } catch (InterruptedException e) {
  197. // e.printStackTrace();
  198. //}
  199.  
  200. //If we comment all this code the listener is called
  201.  
  202. System.out.println("phoneDB: " + phoneDB + " pwdDB: " + pwdDB);
  203. if(phoneDB.isEmpty()){
  204. mPhoneView.requestFocus();
  205. mPhoneView.setError("The phone number field is empty!");
  206. return;
  207. }else if(!phoneDB.equals(phone)){
  208. mPhoneView.requestFocus();
  209. mPhoneView.setError("The phone number is wrong!");
  210. return;
  211. }
  212.  
  213. if(pwdDB.isEmpty()){
  214. mPasswordView.requestFocus();
  215. mPasswordView.setError("The password field is empty!");
  216. return;
  217. }else if(!pwdDB.equals(password)){
  218. mPasswordView.requestFocus();
  219. mPasswordView.setError("The password is wrong!");
  220. return;
  221. }
  222.  
  223. // System.out.println("phoneDB: " + phoneDB + " pwdDB: " + pwdDB);
  224.  
  225. }
  226.  
  227. public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
  228.  
  229. private final String mPhone;
  230. private final String mPassword;
  231.  
  232. UserLoginTask(String phone, String password) {
  233. mPhone = phone;
  234. mPassword = password;
  235. }
  236.  
  237. @Override
  238. protected Boolean doInBackground(Void... params) {
  239. // TODO: attempt authentication against a network service.
  240.  
  241. try {
  242. // Simulate network access.
  243. Thread.sleep(2000);
  244. } catch (InterruptedException e) {
  245. return false;
  246. }
  247.  
  248. for (String credential : DUMMY_CREDENTIALS) {
  249. String[] pieces = credential.split(":");
  250. if (pieces[0].equals(mPhone)) {
  251. // Account exists, return true if the password matches.
  252. return pieces[1].equals(mPassword);
  253. }
  254. }
  255.  
  256. // TODO: register the new account here.
  257. return true;
  258. }
  259.  
  260. public class Login extends AppCompatActivity implements View.OnClickListener {
  261.  
  262. static final String TAG = "FCM";
  263.  
  264. // [START declare_auth_listener]
  265. private FirebaseAuth.AuthStateListener mAuthListener;
  266. FirebaseUser user;
  267. // check if GPS enabled
  268. private String myID, userUid;
  269. CallbackManager callbackManager;
  270. private FirebaseAuth mAuth;
  271. private String android_id;
  272. private DatabaseReference myRef;
  273. DatabaseReference myDBRef;
  274. @Override
  275. protected void onCreate(Bundle savedInstanceState) {
  276. super.onCreate(savedInstanceState);
  277. setContentView(R.layout.activity_login);
  278. preferences = getSharedPreferences(check.PREFERENCES, Context.MODE_PRIVATE);
  279. strToken = preferences.getString(DEVICETOKEN, "").toString();
  280. gpsTracker = new GPSTracker(Login.this);
  281. txtLogin = (TextView) findViewById(R.id.login_btn);
  282. //setOnClick listner
  283. txtLogin.setOnClickListener(this);
  284. android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
  285. mAuth = FirebaseAuth.getInstance();
  286. getUserToken();
  287. txtRegister.setTypeface(check.NeueRegular);
  288. myRef = FirebaseDatabase.getInstance().getReference("localID");
  289. myDBRef = FirebaseDatabase.getInstance().getReference();
  290. mAuthListener = new FirebaseAuth.AuthStateListener() {
  291. @Override
  292. public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
  293. FirebaseUser user = firebaseAuth.getCurrentUser();
  294. if (user != null) {
  295. myRef.child(android_id).setValue(user.getEmail());
  296. // User is signed in
  297. Log.d(TAG, "on Auth State Changed : signed_in : " + user.getEmail());
  298. } else {
  299. // User is signed out
  300. Log.d(TAG, "on Auth State Changed : signed_out");
  301. }
  302. }
  303. };
  304.  
  305. }
  306. @Override
  307. public void onStart() {
  308. super.onStart();
  309. mAuth.addAuthStateListener(mAuthListener);
  310. }
  311.  
  312. @Override
  313. public void onStop() {
  314. super.onStop();
  315. if (mAuthListener != null) {
  316. mAuth.removeAuthStateListener(mAuthListener);
  317. }
  318. }
  319.  
  320.  
  321. @Override
  322. public void onClick(View v) {
  323. switch (v.getId()) {
  324.  
  325. case R.id.login_btn:
  326. signIn(strEmail, strPassword);
  327. break;
  328. }
  329. }
  330. private void signIn(String email, String password) {
  331. Log.d(TAG, "signIn:" + email);
  332. if (!validateForm()) {
  333. return;
  334. }
  335. mAuth.signInWithEmailAndPassword(email, password)
  336. .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  337. @Override
  338. public void onComplete(@NonNull Task<AuthResult> task) {
  339. Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
  340.  
  341. // If sign in fails, display a message to the user. If sign in succeeds
  342. // the auth state listener will be notified and logic to handle the
  343. // signed in user can be handled in the listener.
  344. if (!task.isSuccessful()) {
  345. Log.w(TAG, "signInWithEmail:failed", task.getException());
  346. Toast.makeText(Login.this, "failed auth..",
  347. Toast.LENGTH_SHORT).show();
  348. }else {
  349.  
  350.  
  351. }
  352. }
  353. });
  354. // [END sign_in_with_email]
  355. }
  356. private void getUserToken() {
  357. if (user != null) {
  358. userUid = user.getUid();
  359. }
  360. }
  361.  
  362. private boolean validateForm() {
  363. boolean valid = true;
  364.  
  365. String emails = edit_email.getText().toString();
  366. if (TextUtils.isEmpty(emails)) {
  367. edit_email.setError("Required.");
  368. valid = false;
  369. } else {
  370. edit_email.setError(null);
  371. }
  372. String passwords = edit_password.getText().toString();
  373. if (TextUtils.isEmpty(passwords)) {
  374. edit_password.setError("Required.");
  375. valid = false;
  376. } else {
  377. edit_password.setError(null);
  378. }
  379.  
  380. return valid;
  381. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement