android - onPostInitComplete只能在每次调用getRemoteService时调用一次

时间:2017-02-03 06:40:58

标签: android firebase firebase-authentication

我正在构建一个使用firebase身份验证登录用户的Android应用。起初一切正常,直到几天前我在更新Android SDK并运行app我的设备后尝试登录。

提前致谢...

这是我的代码:

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.client.Firebase;
import com.firebase.client.Query;
import com.firebase.client.annotations.NotNull;
import com.firebase.simplelogin.FirebaseSimpleLoginError;
import com.firebase.simplelogin.FirebaseSimpleLoginUser;
import com.firebase.simplelogin.SimpleLogin;
import com.firebase.simplelogin.SimpleLoginAuthenticatedHandler;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInApi;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.ResultCallbacks;
import com.google.android.gms.common.api.Status;
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.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import android.Manifest;


public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
    RelativeLayout loginBtn;
    private static final String TAG = "LoginActivity";
    TextView tv;
    private static final int REQUEST_CODE = 9001;
    protected EditText loginEmail, loginPassw;
    FirebaseAuth mFirebaseAuth;
    Firebase ref;
    private static final int SIGN_IN = 9001;
    DatabaseReference mDatabase;
    public static String userName = "";
    private Button signupBtn;
    ProgressDialog pDialog;


    public static GoogleApiClient googleClient;

    //This will be places above the oncreate method
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permision, int[] grantRequest){
        if(requestCode == REQUEST_CODE){
            if(grantRequest[0] == PackageManager.PERMISSION_GRANTED){
                ref = new Firebase(Constants.FIREBASE_URI);
                mFirebaseAuth = FirebaseAuth.getInstance();
            }else{
                Toast.makeText(getApplicationContext(), "PERMISSION IS NOT GRANTED...", Toast.LENGTH_LONG).show();
            }
        }
        else{
            super.onRequestPermissionsResult(requestCode, permision, grantRequest);
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_page);

        Firebase.setAndroidContext(this);
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        mDatabase = database.getReference(Constants.USERS);

        if(Build.VERSION.SDK_INT >= 23){
            if(checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED){
                //Do the needful
                ref = new Firebase(Constants.FIREBASE_URI);
                mFirebaseAuth = FirebaseAuth.getInstance();
            }
            else{
                //Permission not granted
                Toast.makeText(getApplicationContext(), "Permission is not granted", Toast.LENGTH_LONG).show();
                requestPermissions(new String[]{Manifest.permission.INTERNET}, REQUEST_CODE);
            }
        }else {

            ref = new Firebase(Constants.FIREBASE_URI);
            mFirebaseAuth = FirebaseAuth.getInstance();
        }

        loginEmail = (EditText)findViewById(R.id.log_user);
        loginPassw = (EditText)findViewById(R.id.log_passw);
        loginBtn = (RelativeLayout)findViewById(R.id.logit);
        SimpleLogin authClient = new SimpleLogin(ref, getApplicationContext());
        SignInButton b = (SignInButton)findViewById(R.id.googlebtn);
        signupBtn = (Button)findViewById(R.id.signup);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        googleClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        //This snippet will be placed in between oncreate method

        tv = (TextView)findViewById(R.id.idtext);

        signupBtn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view){
                signUp();
            }
        });


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


        loginBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                TextView btnText = (TextView)findViewById(R.id.btnText);
                if(btnText.getTextColors().equals("#fff")){
                    Toast.makeText(getApplicationContext(), "votw", Toast.LENGTH_LONG).show();
                }
                String logInEmailField = loginEmail.getText().toString();
                String passField = loginPassw.getText().toString();
                if(logInEmailField.isEmpty() || passField.isEmpty()){
                    errorLogin();
                }else{
                    loader();
                    noError(logInEmailField, passField);
                }

            }
        });


        ActionBar ac = getSupportActionBar();
        if(ac != null) {
            ac.hide();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == SIGN_IN){
            GoogleSignInResult gsr = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleResult(gsr);

        }
    }

    public void handleResult(GoogleSignInResult result){
        Log.d(TAG, "" + result.isSuccess());
        if(result.isSuccess()){
            dismissProgress();
            GoogleSignInAccount gsA = result.getSignInAccount();
            userName = gsA.getDisplayName();

            setUserFullname(userName);
            Intent i = new Intent(this, MainActivity.class);
            //i.putExtra(Constants.PASS_PROFILE, name);
            i.putExtra(Constants.PASS_PROFILE, true);
            startActivity(i);
        }else{

        }
    }

    private void setUserFullname(String name){
        SharedPreferences sPref = getSharedPreferences("PASS", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sPref.edit();
        edit.putString("passer", name);
        edit.apply();
    }

    private void errorLogin(){
        AlertDialog.Builder errorDialog = new AlertDialog.Builder(LoginActivity.this);
        errorDialog.setMessage(R.string.emptyField)
                .setTitle(R.string.errTitle)
                .setPositiveButton(android.R.string.ok, null);
        AlertDialog dialog = errorDialog.create();
        dialog.show();
    }

    ProgressDialog progress;
    private void noError(String email, String passw) {
        User user = new User();

            mFirebaseAuth.signInWithEmailAndPassword(email, passw).addOnCompleteListener(LoginActivity.this,
                    new OnCompleteListener<AuthResult>() {

                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                dismissProgress();
                                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(i);

                            } else if (!task.isSuccessful()){
                                dismissProgress();
                                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this)
                                        .setMessage(task.getException().getMessage())
                                        .setTitle(R.string.errTitle)
                                        .setPositiveButton(android.R.string.ok, null);
                                AlertDialog dialog = builder.create();
                                dialog.show();
                            }
                        }
                    });

    }

    private void loader(){
        pDialog = new ProgressDialog(this);
        pDialog.setProgress(1000);
        pDialog.setMessage("Please wait");
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.show();
    }

    private void dismissProgress(){
        pDialog.dismiss();
        pDialog.dismiss();
    }

    private void errAlert(String signUpErr){
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setMessage(signUpErr)
                .setTitle("Login Error")
                .setPositiveButton(android.R.string.ok, null);
        AlertDialog alert = builder.create();
        alert.show();
    }

    public void signUp(){
        startActivity(new Intent(this, SignUpActivity.class));
    }

    public void signIn(){
        loader();
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleClient);
        startActivityForResult(signInIntent, SIGN_IN);
    }



    @Override
    public void onConnectionFailed(ConnectionResult errorResul){
        Log.d(TAG, "connetionFailed" + errorResul);
    }

}

我收到此错误:

02-03 07:20:17.325 1541-2214/? E/AsyncOperation: serviceID=16, operation=ValidateAuthServiceOperation
                                                 java.lang.NullPointerException: onPostInitComplete can be called only once per call to getRemoteService
                                                     at iri.a(:com.google.android.gms:74)
                                                     at ioj.a(:com.google.android.gms:987)
                                                     at ipf.a(:com.google.android.gms:66)
                                                     at ixg.a(:com.google.android.gms:284)
                                                     at eks.a(:com.google.android.gms:125)
                                                     at eks.a(:com.google.android.gms:113)
                                                     at ixn.run(:com.google.android.gms:113)
                                                     at jaq.run(:com.google.android.gms:450)
                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                     at jew.run(:com.google.android.gms:17)
                                                     at java.lang.Thread.run(Thread.java:848)

2 个答案:

答案 0 :(得分:0)

我也遇到了类似的错误。我正在使用getReference(“.info / connected”)跟踪firebase连接状态。

private ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            boolean connected = snapshot.getValue(Boolean.class);

        } 

上面的监听器经常被调用,连接为true和false。当我检查logcat时出现以下错误

/? E/AsyncOperation: serviceID=16, operation=ValidateAuthServiceOperation
                                                 java.lang.NullPointerException: onPostInitComplete can be called only once per call to getRemoteService
                                                     at iri.a(:com.google.android.gms:74)
                                                     at ioj.a(:com.google.android.gms:987)
                                                     at ipf.a(:com.google.android.gms:66)
                                                     at ixg.a(:com.google.android.gms:284)
                                                     at eks.a(:com.google.android.gms:125)
                                                     at eks.a(:com.google.android.gms:113)
                                                     at ixn.run(:com.google.android.gms:113)
                                                     at jaq.run(:com.google.android.gms:450)
                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                     at jew.run(:com.google.android.gms:17)
                                                     at java.lang.Thread.run(Thread.java:848) 

我认为由于这个错误,firebase连接会丢失并经常恢复,所以为什么没有firebase数据库代码正常工作。

答案 1 :(得分:0)

我终于找到了解决方案,这是我的错误。问题是我限制了我的设备的背景数据。启用它并尝试再次登录后,它可以正常工作。