单击按钮时,应用程序意外崩溃

时间:2018-10-20 09:31:08

标签: java android android-layout android-activity

我对Android开发完全陌生,正在使用Android应用程序,我的应用程序包括注册和登录活动。因此,我正在进行注册活动,但是当我单击“注册”按钮时,应用程序停止工作。

我也知道这是由于NullPointerException引起的,但是我无法解决问题。

我收到的错误是应用程序意外停止了……希望我对大家说清楚。

SignupActivity.java

package com.example.kiit.shoppar;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

public class SignupActivity extends AppCompatActivity {
    Button reg;
    EditText fname, lname, pass, inputEmail, phone;
    FirebaseAuth auth;

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

        fname = (EditText) findViewById(R.id.txtfname);
        lname = (EditText) findViewById(R.id.txtlname);
        pass = (EditText) findViewById(R.id.txtpass);
        inputEmail = (EditText) findViewById(R.id.txtemail);
        phone = (EditText) findViewById(R.id.txtphone);
        reg = (Button) findViewById(R.id.btnreg);
        reg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        final String firstName = fname.getText().toString().trim();
        final String lastName = lname.getText().toString().trim();
        final String email = inputEmail.getText().toString().trim();
        final String password = pass.getText().toString().trim();
        final String phoneno = phone.getText().toString().trim();

        if (TextUtils.isEmpty(firstName)) {
            Toast.makeText(getApplicationContext(), "Enter first name!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(lastName)) {
            Toast.makeText(getApplicationContext(), "Enter last name!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(email)) {
            Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(phoneno)) {
            Toast.makeText(getApplicationContext(), "Enter phone number!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (password.length() < 6) {
            Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (phoneno.length() < 10) {
            Toast.makeText(getApplicationContext(), "Invalid Phone Number!", Toast.LENGTH_SHORT).show();
            return;
        }
        //progressBar.setVisibility(View.VISIBLE);
        //create user

        auth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();

                //progressBar.setVisibility(View.GONE);
                // If sign in fails, display a message to the user. If sign in succeeds
                // the auth state listener will be notified and logic to handle the
                // signed in user can be handled in the listener.
                if (!task.isSuccessful()) {
                    Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
                            Toast.LENGTH_SHORT).show();
                } else {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    final FirebaseUser user = task.getResult().getUser();
                    map.put("user_id", user.getUid());
                    map.put("email", email);
                    map.put("last_connection", Calendar.getInstance(Locale.US).getTimeInMillis());
                    DatabaseReference userDbRef = FirebaseDatabase.getInstance().getReference().child("user").child(user.getUid());
                    userDbRef.setValue(map)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        // Update the username
                                        UserProfileChangeRequest updateRequest =
                                                new UserProfileChangeRequest.Builder()
                                                        .setDisplayName(firstName)
                                                        .build();

                                        auth.getCurrentUser().updateProfile(updateRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                 startActivity(new Intent(SignupActivity.this, LoginActivity.class));
                                                finish();
                                            }
                                        });

                                    } else {
                                        //user.delete();
                                        Toast.makeText(SignupActivity.this,
                                                "Could not add the user to the database", Toast.LENGTH_SHORT).show();
                                    }
                                 }
                              });
                          }
                      }
                 });
            }
        });
    }
}

错误

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kiit.shoppar, PID: 14665
java.lang.NullPointerException: Attempt to invoke virtual method 
'com.google.android.gms.tasks.Task  com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference
at com.example.kiit.shoppar.SignupActivity$1.onClick(SignupActivity.java:90)
at android.view.View.performClick(View.java:6294)
at android.view.View.onKeyUp(View.java:12470)
at android.widget.TextView.onKeyUp(TextView.java:7475)
at android.view.KeyEvent.dispatch(KeyEvent.java:2715)
at android.view.View.dispatchKeyEvent(View.java:11713)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:440)
at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1819)
at android.app.Activity.dispatchKeyEvent(Activity.java:3267)
at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:534)
at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:58)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:316)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:354)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4733)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4605)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4293)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4350)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4326)
at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4487)
at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2435)
at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1998)
at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1989)
at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2412)
at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:325)
at android.os.Looper.loop(Looper.java:142)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Application terminated.

1 个答案:

答案 0 :(得分:0)

您的实例变量auth为空或从未正确分配,您应该先调用auth = FirebaseAuth.getInstance()吗?