【问题标题】:When the application starts, it crashes当应用程序启动时,它会崩溃
【发布时间】:2019-11-05 01:53:28
【问题描述】:

问题是当我在谷歌授权运行这段代码时,它立即崩溃:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAuth = FirebaseAuth.getInstance();
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        //mGoogleSignInClient = GoogleSignIn.getClient(this, gso);



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

                } else {

                }
            }

        };

        et_email = (EditText) findViewById(R.id.et_email);
        et_password = (EditText) findViewById(R.id.et_password);
        mDetailTextView = (TextView) findViewById(R.id.mDetailTextView);
        mStatusTextView = (TextView) findViewById(R.id.mStatusTextView);

        findViewById(R.id.BVoiti).setOnClickListener(this);
        findViewById(R.id.change_email).setOnClickListener(this);
        findViewById(R.id.change_password).setOnClickListener(this);
        findViewById(R.id.btn_vk).setOnClickListener(this);
        findViewById(R.id.BReg).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_google) {
            signIn();
        }
    }



    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleSignInClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }


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

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
                // ...
            }
        }
    }

    public void signing(String email, String password){
        mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()) {
                    Toast.makeText(MainActivity.this, "Авторизация успешна", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "Авторизация провалена", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void registration (String email, String password){
        mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()){
                    Toast.makeText(MainActivity.this, "Регистрация успешна, теперь войдите", Toast.LENGTH_SHORT).show();
                } else{
                    Toast.makeText(MainActivity.this, "Регистрация провалена", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
                            updateUI(null);
                        }

                        // ...
                    }
                });
    }

    private void updateUI(FirebaseUser user) {
        if (user != null) {
            mStatusTextView.setText( user.getEmail());
            mDetailTextView.setText( user.getUid());

            findViewById(R.id.btn_google).setVisibility(View.GONE);
            findViewById(R.id.btn_vk).setVisibility(View.VISIBLE);
        } else {
            mStatusTextView.setText("Вышел");
            mDetailTextView.setText(null);

            findViewById(R.id.btn_google).setVisibility(View.VISIBLE);
            findViewById(R.id.btn_vk).setVisibility(View.GONE);
        }
    }



}

但是日志中的错误:

2019-06-22 17:55:42.652 29327-23222/? E/AudioSource:停止收听是 调用已关闭的 AudioSource 2019-06-22 17:55:43.240 2093-2616/? E/TouchFilter:setTouchFilter LOG 启用参数:0 2019-06-22 17:55:43.554 31234-31234/com.anntoxa.foodforyou E/AndroidRuntime: 致命异常: main 进程:com.anntoxa.foodforyou,PID:31234 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.anntoxa.foodforyou/com.anntoxa.foodforyou.MainActivity}: java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)' 为空 对象引用 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2805) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2883) 在 android.app.ActivityThread.-wrap11(未知来源:0) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:164) 在 android.app.ActivityThread.main(ActivityThread.java:6523) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857) 引起:java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)' 为空 对象引用 在 com.anntoxa.foodforyou.MainActivity.updateUI(MainActivity.java:176) 在 com.anntoxa.foodforyou.MainActivity.onCreate(MainActivity.java:51) 在 android.app.Activity.performCreate(Activity.java:7023) 在 android.app.Activity.performCreate(Activity.java:7014) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2758) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2883) 在 android.app.ActivityThread.-wrap11(未知来源:0) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1613) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:164) 在 android.app.ActivityThread.main(ActivityThread.java:6523) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857) 2019-06-22 17:55:43.564 2093-2156/? E/ActivityManager_tangan: 应用 崩溃,杀死它 2019-06-22 17:55:43.569 384-384/? E/低内存杀手: 写入 /proc/31234/oom_score_adj 时出错;错误号=22

【问题讨论】:

  • Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object referencenull,检查你分配给TextViewfindviewbyid是否正确。
  • 并从 onCreate 中删除这一行:super.onStart()

标签: java android firebase android-layout


【解决方案1】:

你应该移动这个块:

mDetailTextView = (TextView) findViewById(R.id.mDetailTextView);
mStatusTextView = (TextView) findViewById(R.id.mStatusTextView);

onCreate 中调用updateUI 之前

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多