单击按钮时,Android应用程序意外停止工作

时间:2018-10-19 20:11:20

标签: java android android-studio 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();
                                        }
                                    }
                                });
                            }
                      }
                });

            }
        });
    }

}

activity_signup.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SignupActivity">

<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/txtfname"
    android:hint="First Name" android:layout_marginTop="8dp" app:layout_constraintTop_toTopOf="parent"
    android:layout_marginEnd="8dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginRight="8dp"
    android:layout_marginStart="8dp" app:layout_constraintStart_toStartOf="parent"
    android:layout_marginLeft="8dp" android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.017"/>
<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/txtlname" android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/txtfname" android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toBottomOf="parent" android:layout_marginEnd="8dp"
    app:layout_constraintEnd_toEndOf="parent" android:layout_marginRight="8dp" android:layout_marginStart="8dp"
    app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
    app:layout_constraintHorizontal_bias="0.0" app:layout_constraintVertical_bias="0.0"
    android:hint="Last Name"/>
<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:ems="10"
    android:id="@+id/txtpass" android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toBottomOf="parent" android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/txtlname" android:layout_marginEnd="8dp"
    app:layout_constraintEnd_toEndOf="parent" android:layout_marginRight="8dp" android:layout_marginStart="8dp"
    app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
    app:layout_constraintHorizontal_bias="0.0" app:layout_constraintVertical_bias="0.0"
    android:hint="Password"/>
<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="textEmailAddress"
    android:ems="10"
    android:id="@+id/txtemail" app:layout_constraintEnd_toEndOf="parent"
    android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
    app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
    android:layout_marginStart="8dp" android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toBottomOf="parent" android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/txtpass" app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.0" android:hint="E-mail"/>
<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:ems="10"
    android:id="@+id/txtphone" app:layout_constraintEnd_toEndOf="parent"
    android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
    app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
    android:layout_marginStart="8dp" android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toBottomOf="parent" android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/txtemail" app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.0" android:hint="Phone Number"/>

<View
    android:id="@+id/divider3"
    android:layout_width="368dp"
    android:layout_height="1dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="152dp"
    android:background="?android:attr/listDivider"
    android:visibility="visible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtphone"
    app:layout_constraintVertical_bias="0.0" />

<Button
    android:id="@+id/btnreg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="Registration"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/divider3"
    app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>

AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kiit.shoppar">

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".SignupActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".LoginActivity" />
    <activity android:name=".MainActivity"></activity>
</application>

</manifest>

错误

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.

0 个答案:

没有答案