0
我們正在爲與FIREBASE接口的LOGIN開發一個Activity。 我們有一個OnClickListener按鈕,其中的AddValueListener嵌套在DatabaseRefence上 問題是AddValueListener永遠不會被調用,並且如果我們使用鎖存器,應用程序將凍結,因爲鎖存器永遠不會降爲零 BUT如果我們在AddValueListener下注釋代碼,我們的應用程序將進入它並且它可以工作。按鈕和Firebase監聽器 - OnDataChange不叫 - Android
我們在做什麼錯了?
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[]{
"[email protected]:hello", "[email protected]: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);
}
Android studio也給我們這個子類與Async,也許我們需要使用它?如何?
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;
}
感謝
感謝,我會努力 – Kalos92