Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package it.polito.mad17.viral.sliceapp;
- import android.animation.Animator;
- import android.animation.AnimatorListenerAdapter;
- import android.annotation.TargetApi;
- import android.content.pm.PackageManager;
- import android.support.annotation.NonNull;
- import android.support.design.widget.Snackbar;
- import android.support.v7.app.AppCompatActivity;
- import android.app.LoaderManager.LoaderCallbacks;
- import android.content.CursorLoader;
- import android.content.Loader;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.AsyncTask;
- import android.os.Build;
- import android.os.Bundle;
- import android.provider.ContactsContract;
- import android.telephony.PhoneNumberUtils;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.KeyEvent;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.inputmethod.EditorInfo;
- import android.widget.ArrayAdapter;
- import android.widget.AutoCompleteTextView;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.google.firebase.database.DataSnapshot;
- import com.google.firebase.database.DatabaseError;
- import com.google.firebase.database.DatabaseReference;
- import com.google.firebase.database.FirebaseDatabase;
- import com.google.firebase.database.ValueEventListener;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Objects;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.Semaphore;
- import java.util.regex.Pattern;
- import java.lang.String;
- import static android.Manifest.permission.READ_CONTACTS;
- /**
- * A login screen that offers login via email/password.
- */
- public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
- /**
- * Id to identity READ_CONTACTS permission request.
- */
- private static final int REQUEST_READ_CONTACTS = 0;
- /**
- * A dummy authentication store containing known user names and passwords.
- * TODO: remove after connecting to a real authentication system.
- */
- private static final String[] DUMMY_CREDENTIALS = new String[]{
- "foo@example.com:hello", "bar@example.com:world"
- };
- /**
- * Keep track of the login task to ensure we can cancel it if requested.
- */
- private UserLoginTask mAuthTask = null;
- // UI references.
- private AutoCompleteTextView mPhoneView;
- private EditText mPasswordView;
- private View mProgressView;
- private View mLoginFormView;
- private String pwdDB,phoneDB;
- private boolean cancel = false;
- private View focusView = null;
- private boolean flag=false;
- private DatabaseReference db;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- //Firebase.setAndroidContext(this);
- // Set up the login form.
- mPhoneView = (AutoCompleteTextView) findViewById(R.id.phoneNumber);
- populateAutoComplete();
- mPasswordView = (EditText) findViewById(R.id.password);
- mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
- @Override
- public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
- if (id == R.id.login || id == EditorInfo.IME_NULL) {
- attemptLogin();
- return true;
- }
- return false;
- }
- });
- }
- private void attemptLogin() {
- if (mAuthTask != null) {
- return;
- }
- // Reset errors.
- mPhoneView.setError(null);
- mPasswordView.setError(null);
- // Store values at the time of the login attempt.
- final String phone = mPhoneView.getText().toString();
- final String password = mPasswordView.getText().toString();
- boolean verifyMail = false;
- // Check for a valid phone number.
- if (phone.isEmpty()) {
- mPhoneView.requestFocus();
- mPhoneView.setError(getString(R.string.error_field_required));
- return;
- }
- if (isPhoneValid(phone) == false) {
- mPhoneView.requestFocus();
- mPhoneView.setError(getString(R.string.error_invalid_phone));
- return;
- /// / focusView = mPhoneView;
- // cancel = true;
- }
- // Check for a valid password, if the user entered one.
- if (TextUtils.isEmpty(password)) {
- mPasswordView.requestFocus();
- mPasswordView.setError(getString(R.string.error_empty_password));
- return;
- }
- //Check for a password having the right length
- // 8 >= pwd <= 16
- if (isPasswordValid(password) == false) {
- mPasswordView.requestFocus();
- mPasswordView.setError(getString(R.string.error_short_password));
- return;
- }
- final CountDownLatch latch = new CountDownLatch(1);
- db = FirebaseDatabase.getInstance("https://sliceapp-a55d6.firebaseio.com/").getReference();
- System.out.println("AAAAA " + db.child("Users").child(phone).toString());
- // Thread t = new Thread(new Runnable() {
- // @Override
- // public void run() {
- db.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
- @Override
- public void onDataChange(DataSnapshot dataSnapshot) {
- Log.d("BEFORE FOR CYCLE", "CIAO");
- //Log are never shown
- for (DataSnapshot d : dataSnapshot.getChildren()) {
- System.out.println("CCCCC " + d.getKey());
- if (d.getKey().equals(phone)) {
- phoneDB = d.getKey();
- System.out.println("Phone Number is " + phoneDB);
- pwdDB = d.child("password").getValue().toString();
- System.out.println("The password is " + pwdDB);
- }
- }
- // latch.countDown();
- }
- @Override
- public void onCancelled(DatabaseError databaseError) {
- Log.d("FAILURE", databaseError.toString());
- }
- });
- //}
- // });
- // t.start();
- // try {
- // latch.await();
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- //}
- //If we comment all this code the listener is called
- System.out.println("phoneDB: " + phoneDB + " pwdDB: " + pwdDB);
- if(phoneDB.isEmpty()){
- mPhoneView.requestFocus();
- mPhoneView.setError("The phone number field is empty!");
- return;
- }else if(!phoneDB.equals(phone)){
- mPhoneView.requestFocus();
- mPhoneView.setError("The phone number is wrong!");
- return;
- }
- if(pwdDB.isEmpty()){
- mPasswordView.requestFocus();
- mPasswordView.setError("The password field is empty!");
- return;
- }else if(!pwdDB.equals(password)){
- mPasswordView.requestFocus();
- mPasswordView.setError("The password is wrong!");
- return;
- }
- // System.out.println("phoneDB: " + phoneDB + " pwdDB: " + pwdDB);
- }
- public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
- private final String mPhone;
- private final String mPassword;
- UserLoginTask(String phone, String password) {
- mPhone = phone;
- mPassword = password;
- }
- @Override
- protected Boolean doInBackground(Void... params) {
- // TODO: attempt authentication against a network service.
- try {
- // Simulate network access.
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- return false;
- }
- for (String credential : DUMMY_CREDENTIALS) {
- String[] pieces = credential.split(":");
- if (pieces[0].equals(mPhone)) {
- // Account exists, return true if the password matches.
- return pieces[1].equals(mPassword);
- }
- }
- // TODO: register the new account here.
- return true;
- }
- public class Login extends AppCompatActivity implements View.OnClickListener {
- static final String TAG = "FCM";
- // [START declare_auth_listener]
- private FirebaseAuth.AuthStateListener mAuthListener;
- FirebaseUser user;
- // check if GPS enabled
- private String myID, userUid;
- CallbackManager callbackManager;
- private FirebaseAuth mAuth;
- private String android_id;
- private DatabaseReference myRef;
- DatabaseReference myDBRef;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- preferences = getSharedPreferences(check.PREFERENCES, Context.MODE_PRIVATE);
- strToken = preferences.getString(DEVICETOKEN, "").toString();
- gpsTracker = new GPSTracker(Login.this);
- txtLogin = (TextView) findViewById(R.id.login_btn);
- //setOnClick listner
- txtLogin.setOnClickListener(this);
- android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
- mAuth = FirebaseAuth.getInstance();
- getUserToken();
- txtRegister.setTypeface(check.NeueRegular);
- myRef = FirebaseDatabase.getInstance().getReference("localID");
- myDBRef = FirebaseDatabase.getInstance().getReference();
- mAuthListener = new FirebaseAuth.AuthStateListener() {
- @Override
- public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
- FirebaseUser user = firebaseAuth.getCurrentUser();
- if (user != null) {
- myRef.child(android_id).setValue(user.getEmail());
- // User is signed in
- Log.d(TAG, "on Auth State Changed : signed_in : " + user.getEmail());
- } else {
- // User is signed out
- Log.d(TAG, "on Auth State Changed : signed_out");
- }
- }
- };
- }
- @Override
- public void onStart() {
- super.onStart();
- mAuth.addAuthStateListener(mAuthListener);
- }
- @Override
- public void onStop() {
- super.onStop();
- if (mAuthListener != null) {
- mAuth.removeAuthStateListener(mAuthListener);
- }
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.login_btn:
- signIn(strEmail, strPassword);
- break;
- }
- }
- private void signIn(String email, String password) {
- Log.d(TAG, "signIn:" + email);
- if (!validateForm()) {
- return;
- }
- mAuth.signInWithEmailAndPassword(email, password)
- .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull Task<AuthResult> task) {
- Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
- // If sign in fails, display a message to the user. If sign in succeeds
- // the auth state listener will be notified and logic to handle the
- // signed in user can be handled in the listener.
- if (!task.isSuccessful()) {
- Log.w(TAG, "signInWithEmail:failed", task.getException());
- Toast.makeText(Login.this, "failed auth..",
- Toast.LENGTH_SHORT).show();
- }else {
- }
- }
- });
- // [END sign_in_with_email]
- }
- private void getUserToken() {
- if (user != null) {
- userUid = user.getUid();
- }
- }
- private boolean validateForm() {
- boolean valid = true;
- String emails = edit_email.getText().toString();
- if (TextUtils.isEmpty(emails)) {
- edit_email.setError("Required.");
- valid = false;
- } else {
- edit_email.setError(null);
- }
- String passwords = edit_password.getText().toString();
- if (TextUtils.isEmpty(passwords)) {
- edit_password.setError("Required.");
- valid = false;
- } else {
- edit_password.setError(null);
- }
- return valid;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement