应用程序在点击注册按钮时崩溃

时间:2018-09-03 15:44:47

标签: java android

我正在使用Firebase为应用创建简单的登录/注册。到目前为止,我仅对注册功能进行了编码,并且在运行该功能时只要点击它,应用程序就会崩溃。相关脚本如下所示。

注册页面的Java代码:

package com.healthandhelpapp;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
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;

public class SignUpPage extends AppCompatActivity implements View.OnClickListener {


    private FirebaseAuth mAuth;
    EditText editTextUsername, editTextPassword;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up_page);

        editTextUsername=findViewById(R.id.enterEmail);
        editTextPassword=findViewById(R.id.enterPassword);

        mAuth = FirebaseAuth.getInstance();

        findViewById(R.id.butSGUP).setOnClickListener(this);
    }

    private  void registerUser(){

        String email = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();
if(email.isEmpty()){

    editTextUsername.setError("Email is required");

editTextUsername.requestFocus();
    return;
}

          if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){

editTextUsername.setError("Email is invalid");
editTextUsername.requestFocus();

          }


if (password.isEmpty()){


    editTextPassword.setError("Password is required");
    editTextPassword.requestFocus();
    return;
}


if (password.length()<7){

    editTextPassword.setError("Password is too short");
    editTextPassword.requestFocus();
}

mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if(task.isSuccessful()){
            Toast.makeText(getApplicationContext(), "User Registered Successfully", Toast.LENGTH_SHORT).show();


        }
    }
});

    }


    @Override
    public  void onClick(View view){

        switch (view.getId()){

            case R.id.butSGUP:

                registerUser();

                    break;


            case R.id.tgtLogIn:

                startActivity(new Intent(this, LogInPage.class));


        }


    }



}

这是我的应用Gradle脚本

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.healthandhelpapp"
        minSdkVersion 19
        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'])
    implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-auth:11.6.0'

    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'
}

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

这是android清单

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

<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=".Intro">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

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

    </manifest>

最后,这是注册页面的xml脚本。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#699dee"
    tools:context=".SignUpPage">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="287dp"
        android:layout_height="147dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="42dp"
        android:fontFamily="sans-serif"
        android:text="Welcome! Since you have not yet registered enter your E-Mail Address and password in the respective fields below."
        android:textAlignment="center"
        android:textSize="20dp"
        android:textStyle="italic" />

    <EditText
        android:id="@+id/enterEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="222dp"
        android:background="#699"
        android:ems="10"
        android:hint="E-Mail Address"
        android:inputType="textEmailAddress"
        android:textColorHint="#fff" />

    <EditText
        android:id="@+id/enterPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="155dp"
        android:background="#699"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        android:textColorHint="#fff" />

    <Button
        android:id="@+id/butSGUP"
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="49dp"
        android:background="#f2f2f5"
        android:fontFamily="sans-serif"
        android:text="Sign Up" />

    <TextView
        android:id="@+id/tgtLogIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="17dp"
        android:text="Already have an account; Log In from here" />
</RelativeLayout>

编辑:这是我从调试中获得的日志的重要部分

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.healthandhelpapp, PID: 14754
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                  at com.healthandhelpapp.SignUpPage.registerUser(SignUpPage.java:38)
                  at com.healthandhelpapp.SignUpPage.onClick(SignUpPage.java:91)
                  at android.view.View.performClick(View.java:6367)
                  at android.view.View$PerformClick.run(View.java:25032)
                  at android.os.Handler.handleCallback(Handler.java:790)
                  at android.os.Handler.dispatchMessage(Handler.java:99)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6753)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:482)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

编辑2:我已经添加了权限并更改了编辑文本问题。现在它不会崩溃,但是功能stilld不会运行,即用户没有得到注册

4 个答案:

答案 0 :(得分:0)

解决方案:

在清单中添加INTERNET权限。

希望这是您的错误。

答案 1 :(得分:0)

您缺少清单文件的权限。 放进去...

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

如果出现其他问题,请附加日志。

更正此...

........

public class SignUpPage extends AppCompatActivity implements 
View.OnClickListener {


private FirebaseAuth mAuth;
private EditText editTextUsername, editTextPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up_page);

    editTextUsername=findViewById(R.id.enterEmail);
    editTextPassword=findViewById(R.id.editText2);
    mAuth = FirebaseAuth.getInstance();

    findViewById(R.id.butSGUP).setOnClickListener(this);
}

private  void registerUser(){

....................

如果不是这样,则在调用的每个函数上对其进行初始化。我不知道这是个错误还是什么,但我已经经历过几次相同的事情。

答案 2 :(得分:0)

1)您需要在清单中添加Internet权限

2)

editTextUsername=findViewById(R.id.enterEmail);
        editTextPassword=findViewById(R.id.enteredPassword);

替换为:-

editTextUsername=findViewById(R.id.enterEmail);
            editTextPassword=findViewById(R.id.editText2);

注意:-您正在获取Nullpointer异常,因为它没有在xml中找到视图。

我希望这可以解决您的问题!

答案 3 :(得分:0)

您应将if(email.isEmpty())更改为if(email.getText().toString().equals(""))。我认为,到现在为止,它始终返回false,因此会在else代码中使用。因此,在尝试获取NullPointerException的字符串时会得到EditText

错误总是发生还是仅在EditText为空时单击事件发生?