没有这样的实例方法:“ com.example.android.instagramclone.Login.LoginActivity.getCurrentUser”

时间:2018-12-29 09:55:51

标签: android

我想在FirebaseAuth类中使用getCurrentUser方法,但是我的代码尝试在此活动中调用getCurrentUser方法,该方法不存在。 为什么会发生?如何解决该问题并获取正确的用户实例?

    package com.example.android.instagramclone.Login;

    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.design.widget.TextInputEditText;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.example.android.instagramclone.Home.HomeActivity;
    import com.example.android.instagramclone.R;
    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.FirebaseUser;

    public class LoginActivity extends AppCompatActivity {

        private static final String TAG = "LoginActivity";

        private Context mContext = LoginActivity.this;

        //Firebase
        private FirebaseAuth mAuth;
        private FirebaseAuth.AuthStateListener mAuthListener;

        //personal info
        private String email;
        private String userName;
        private String password;

        private TextInputEditText mEmail;
        private TextInputEditText mPassword;


        //objects on the layout
        private Button btnLogin;
        private ProgressBar mProgressBar;
        private TextView mPleaseWait;


        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);

            Log.d(TAG, "onCreate: setting up LoginActivity.");
            initWidgets();
            setupFirebase();
            init();

        }

        @Override
        protected void onStart() {
            super.onStart();
            mAuth.addAuthStateListener(mAuthListener);
        }


        @Override
        protected void onStop() {
            super.onStop();
            if (mAuthListener != null) {
                mAuth.removeAuthStateListener(mAuthListener);
            }
        }

        //initialize widgets.
        private void initWidgets() {
            Log.d(TAG, "initWidgets: Initializing widgets.");

            mProgressBar = (ProgressBar) findViewById(R.id.loginRequestLoadingProgressBar);
            mPleaseWait = (TextView) findViewById(R.id.pleaseWait);
            mEmail = (TextInputEditText) findViewById(R.id.input_email);
            mPassword = (TextInputEditText) findViewById(R.id.input_password);


            mProgressBar.setVisibility(View.GONE);
            mPleaseWait.setVisibility(View.GONE);

        }


        private boolean isStringNull(String str) {
            Log.d(TAG, "isStringNull: checking if null");

            if (str.equals("") || str == null) {
                return true;
            } else {
                return false;
            }
        }


        /**
         * -------------------- Firebase Section----------------------------------------------*
         */

        private void init() {

            //Login button
            btnLogin = (Button) findViewById(R.id.btn_login);

            //set up button Listener
            btnLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "onClick: attempting to log in.");

                    //To check inputs are not null
                    String email = mEmail.getText().toString();
                    String password = mPassword.getText().toString();

                    //if both of them are filled out
                    if (isStringNull(email) || isStringNull(password)) {
                        Toast.makeText(mContext, "You must fill out all the fields", Toast.LENGTH_SHORT).show();
                    } else {
                        //Processing to log in
                        mProgressBar.setVisibility(View.VISIBLE);
                        mPleaseWait.setVisibility(View.VISIBLE);

                        //signInWithEmailAndPassword(email, password);
                        mAuth.signInWithEmailAndPassword(email, password)
                                .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                                    @Override
                                    public void onComplete(@NonNull Task<AuthResult> task) {
                                        FirebaseUser user = mAuth.getCurrentUser();

                                        //If log in failed.
                                        if (!task.isSuccessful()) {
                                            Log.w(TAG, "signInWithEmail:failed", task.getException());
                                            Toast.makeText(mContext, "Email is not verified. \n Please check your Email.", Toast.LENGTH_SHORT).show();
                                            mProgressBar.setVisibility(View.GONE);
                                            mPleaseWait.setVisibility(View.GONE);

                                            //If log in successful.
                                        } else {

                                            try {
                                                //if the account is already verified
                                                if (user.isEmailVerified()) {
                                                    Log.d(TAG, "onComplete: success. Email is verified.");

                                                    Toast.makeText(mContext, "Email is verified.", Toast.LENGTH_SHORT).show();
                                                    Intent intent = new Intent(mContext, HomeActivity.class);
                                                    startActivity(intent);

                                                    // If the account is not verified yet.
                                                } else {
                                                    // display a message to the user.
                                                    Log.w(TAG, "signInWithEmail:failure", task.getException());
                                                    Toast.makeText(mContext, "Authentication failed.",
                                                            Toast.LENGTH_SHORT).show();

                                                    mProgressBar.setVisibility(View.GONE);
                                                    mPleaseWait.setVisibility(View.GONE);
                                                    mAuth.signOut();
                                                }
                                            } catch (NullPointerException e) {
                                                Log.d(TAG, "onComplete: NullPointerException: " + e.getMessage());
                                            }

                                        }

                                        // ...
                                    }
                                });
                    }
                }
            });

            //Setting up the link to RegisterActivity.
            TextView linkSignUp = (TextView) findViewById(R.id.link_signup);
            linkSignUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "onClick: navigating to register screen");
                    Intent intent = new Intent(mContext, RegisterActivity.class);
                    startActivity(intent);
                }

            });
            //If the user is logged in, navigate the user to HomeActivity.
            FirebaseUser user = mAuth.getCurrentUser();

            if(user != null){
                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                startActivity(intent);
                finish();
            }
        }





                    /**
                     * setting up firebase
                     */
            private void setupFirebase () {

                Log.d(TAG, "setupFirebase: started.");

                mAuth = FirebaseAuth.getInstance();

                mAuthListener = new FirebaseAuth.AuthStateListener() {
                    @Override
                    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                        FirebaseUser user = firebaseAuth.getCurrentUser();

                        if (user != null) {
                            Log.d(TAG, "onAuthStateChanged: sign_in");

                        } else {
                            Log.d(TAG, "onAuthStateChanged: authentification failed.");
                        }
                    }
                };

            }


        }

这是我的gradle文件。

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.android.instagramclone"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //Design Library for Coodinator Layout and toolbars
    //noinspection GradleCompatible
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    //firebase
    implementation 'com.google.firebase:firebase-core:16.0.1'
    //design support
    implementation "com.android.support:design:28.0.0"

    //annotaion?
    implementation 'org.jetbrains:annotations-java5:15.0'

    //Resolve nullable
    implementation 'com.android.support:support-annotations:+'

    //circle image
    implementation 'de.hdodenhof:circleimageview:2.2.0'

    //universal image loader
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

    //for firebase

    implementation 'com.firebaseui:firebase-ui-auth:4.1.0'

    // for Firebase database
    implementation 'com.google.firebase:firebase-database:16.0.1'


}
apply plugin: 'com.google.gms.google-services'

身份验证成功后,我想转到HomeActivity,但这只是直接返回LoginActivity。     它没有向我显示日志中的任何错误,因此我观看了“ getCurrentUser”变量。

它说: 没有这样的实例方法:'com.example.android.instagramclone.Login.LoginActivity.getCurrentUser'

//If the user is logged in, navigate the user to HomeActivity.
        FirebaseUser user = mAuth.getCurrentUser();
if(user != null){
            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
            startActivity(intent);
            finish();
        }

2 个答案:

答案 0 :(得分:0)

尝试使缓存无效

从菜单File -> Invalidate Caches/ Restart-> Invalidate and Restart

答案 1 :(得分:0)

谢谢,我解决了我的问题。 我取消了“用户”以及mAuth。 另外,我发现我在HomeActivity中编写了mAuth.SignOut。 那是我的全部错误。