Android等待异步firebase onDataChange()结果

时间:2019-07-08 07:42:48

标签: java android multithreading firebase asynchronous

我要检查Firebase中是否存在用户mailkey(不带特殊字符“ @”和“。”的电子邮件地址)。如果是这样,则返回true。我在DatabaseProfileManager类中调用方法mailKeyExisting()。这包含onDataChannge方法的async(这使我很麻烦)。实际上,问题是fireKey中存在mailKey,但它返回false。布尔值在方法中设置为true,但返回false,因为在构造函数中,我将其设置为false以防止NPE。如果Firebase包含布尔值,则布尔值将被设置为true,但是某个地方存在问题,并且此问题与异步事物有关。我在这里读了很多文章,现在我已经工作了好几天。

我尝试了CountdownLatch。我尝试过移动单行并更早地初始化了某些部分,但是那太荒谬了,只是愚蠢...我插入了很多Log.d()...

DatabaseProfileManager

public class DatabaseProfileManager {

    /**
     * TODO [DONE] 1 Constructor with GoogleSignInAccount
     * TODO [DONE] 2 Generate MailKey
     * TODO [DONE] 3 Check if Firebase already contains this MailKey
     * if not, return a false (rest will be handled in GoogleSignInActivity)
     * if yes, return true (rest will be handled in GoogleSignInActivity)
     **/

    private GoogleSignInAccount account;
    private DatabaseReference root;
    private String mailKey;
    private Boolean mailKeyExisting;

    public DatabaseProfileManager(GoogleSignInAccount account) {
        this.account = account;
        this.root = FirebaseDatabase.getInstance().getReference("profiles");
        this.mailKey = account.getEmail().replace("@", "").replace(".", "");
        this.mailKeyExisting = false;

    }

    public Boolean mailKeyExisting() {
        Log.d("HMDebugInfo", "DatabaseProfileManager.mailKeyExisting() method got called, it should return true or false");
        root.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Log.d("HMDebugInfo", "DatabaseProfileManager.mailKeyExisting() --> onDataChange() got called, its a void");
                if (dataSnapshot == null) {
                    Log.d("HMDebugInfo", "DatabaseProfileManager.mailKeyExisting() --> onDataChange(): dataSnapshot (from type DataSnapshot) is NULL");
                } else {
                    Log.d("HMDebugInfo", "DatabaseProfileManager.mailKeyExisting() --> onDataChange(): dataSnapshot (from type DataSnapshot) is NOT NULL, so start checking if mailKey already exists");
                    if (dataSnapshot.hasChild(mailKey)) {
                        Log.d("HMDebugInfo", "DatabaseProfileManager.mailKeyExisting() --> onDataChange(): mailKey is already in FireBase, set mailKeyExisting (from type Boolean) to true");
                        mailKeyExisting = true;
                    } else {
                        Log.d("HMDebugInfo", "DatabaseProfileManager.mailKeyExisting() --> onDataChange(): mailKey is NOT in FireBase, set mailKeyExisting (from type Boolean) to false");
                        mailKeyExisting = false;
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d("HMDebugInfo", "DatabaseProfileManager.mailKeyExisting() --> onCancelled(): DatabaseError: " + databaseError.getMessage());
            }
        });
        Log.d("HMDebugInfo", "Before return mailKeyExisting: " + mailKeyExisting);
        return mailKeyExisting;
    }

GoogleSignInActivity

public class GoogleSignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    public static final int REQ_CODE = 9001;
    public static GoogleSignInAccount account;
    public static DatabaseProfileManager dbProfile;
    public Intent home;
    public SignInButton btn_signin;
    public GoogleApiClient client;
    public GoogleSignInOptions options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_sign_in);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getSupportActionBar().hide();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // Java Init
        home = new Intent(this, HomeActivity.class);
        options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
        client = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, options).build();

        // UI INIT
        btn_signin = findViewById(R.id.btn_login);


        btn_signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signIn();
            }
        });

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    public void signIn() {
        Intent intent = Auth.GoogleSignInApi.getSignInIntent(client);
        startActivityForResult(intent, REQ_CODE);
    }

    public void handleResult(GoogleSignInResult result) {
        if (result.isSuccess()) {
            account = result.getSignInAccount();
/*            String name = account.getDisplayName();
            String email = account.getEmail();
            editor.putString("loginToken", account.getIdToken());
            editor.commit();*/
            updateUI(true);

        } else {
            updateUI(false);
        }
    }

    public void updateUI(Boolean isLoggedIn) {
        if (isLoggedIn) {
            dbProfile = new DatabaseProfileManager(account);
            Boolean b = dbProfile.mailKeyExisting();
            Intent home = new Intent(this, HomeActivity.class);
            Intent profil = new Intent(this, ProfilActivity.class);
            // TODO 1 entry is in Firebase, but mailKeyExisting() returns false
            if (b) {
                Log.d("HMDebugInfo", "GoogleSignInActivity.updateUI() if part");
                startActivity(home);
                finish();
            } else {
                Log.d("HMDebugInfo", "GoogleSignInActivity.mailKeyExisting returns: " + b);
                Log.d("HMDebugInfo", "GoogleSignInActivity.updateUI() else part");
                startActivity(home);
                finish();
                startActivity(profil);
                Log.i("HMDebugInfo", "GoogleSignInActivity user has no or no complete entry");
            }
        } else {
            Toast.makeText(this, "Login failed", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CODE) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleResult(result);

        }

    }

登录后当前的日志输出:

D/HMDebugInfo: DatabaseProfileManager.mailKeyExisting() method got called, it should return true or false
D/HMDebugInfo: Before return mailKeyExisting: false
D/HMDebugInfo: GoogleSignInActivity.mailKeyExisting returns: false
D/HMDebugInfo: GoogleSignInActivity.updateUI() else part
I/HMDebugInfo: GoogleSignInActivity user has no or no complete entry
D/HMDebugInfo: onCreate(): init EditTexts and Button
D/HMDebugInfo: onCreate(): init databaseProfileManager (from type DatabaseProfileManager)
D/HMDebugInfo: DatabaseProfileManager.mailKeyExisting() --> onDataChange() got called, its a void
D/HMDebugInfo: DatabaseProfileManager.mailKeyExisting() --> onDataChange(): dataSnapshot (from type DataSnapshot) is NOT NULL, so start checking if mailKey already exists
D/HMDebugInfo: DatabaseProfileManager.mailKeyExisting() --> onDataChange(): mailKey is already in FireBase, set mailKeyExisting (from type Boolean) to true

0 个答案:

没有答案