当前位置: 首页 > 知识库问答 >
问题:

正在获取NPE无法启动活动:即使使用setContentView[duplicate]也尝试调用空对象引用的虚拟方法

狄令
2023-03-14

我将跟随本教程探索Firebase,并使用三个java类使用电子邮件身份验证

    null
    null
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.firebaselearning, PID: 8008
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.firebaselearning/com.example.firebaselearning.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.example.firebaselearning.RegisterActivity.onCreate(RegisterActivity.java:60)
    at android.app.Activity.performCreate(Activity.java:7136)
    at android.app.Activity.performCreate(Activity.java:7127)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loop(Looper.java:193) 
    at android.app.ActivityThread.main(ActivityThread.java:6669) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
public class MainActivity extends AppCompatActivity {

//views
Button mRegisterBtn, mLogInBtn;

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

    //initialise view
    mRegisterBtn = findViewById(R.id.registerbutton);
    mLogInBtn = findViewById(R.id.login);

    //handle register button click
    mRegisterBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //start register activity
            startActivity(new Intent(MainActivity.this, RegisterActivity.class));
        }
    });
  }
}
public class RegisterActivity extends AppCompatActivity {

//views
EditText mEmailET, mPassword;
Button mRegistrationBTN;

//progressbar to display progress which registering
ProgressDialog progressDialog;
//declare instance of fireAuth
private FirebaseAuth mAuth;

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

    //actionbar and its title
    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle("Create Account");

    //enable back button
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowHomeEnabled(true);

    //init
    mEmailET = findViewById(R.id.editTextTextEmailAddress);
    mPassword = findViewById(R.id.editTextTextPassword);
    mRegistrationBTN = findViewById(R.id.registerbutton);

    //initialising firebaseAuth instance
    mAuth = FirebaseAuth.getInstance();

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Registering user ...");


    //handle register btn click
    mRegistrationBTN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //input email, password
            String email = mEmailET.getText().toString().trim();
            String password = mPassword.getText().toString().trim();
            //validate
            if(Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                //show error and focus to edittext
                mEmailET.setError("Invalid Email");
                mEmailET.setFocusable(true);
            }else if (password.length()<6){
                //set error and focus to password
                mPassword.setError("Password length must be at least 6 characters");
                mPassword.setFocusable(true);
            }else{
                //register the user
                registerUser(email,password);
            }

        }
    });

}

private void registerUser(String email, String password){
    //email and password is valid ,shows progress dialog and start registering user
    progressDialog.show();

    mAuth.createUserWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, dismiss dialog and start register activity
                        progressDialog.dismiss();
                        FirebaseUser user = mAuth.getCurrentUser();
                        assert user != null;
                        Toast.makeText(RegisterActivity.this,"Registered..."+user.getEmail(), Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(RegisterActivity.this, ProfileActivity.class));
                        finish();
                    } else {
                        // If sign in fails, display a message to the user.
                        progressDialog.dismiss();
                        Toast.makeText(RegisterActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
                    }
                }
            }) .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            //error, dismiss progrss dialog and get and show error message
            progressDialog.dismiss();
            Toast.makeText(RegisterActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    });
}
@Override
public boolean onSupportNavigateUp() {
    onBackPressed(); //go previous activity on clicking back
    return super.onSupportNavigateUp();
  }
}

我认为我的xml文件的名称是相同的。

共有1个答案

郗福
2023-03-14

由于引用了Activity_Main.xml布局(MainActivity的视图)中的RegisterActivity(在其Activity_Register.xml的视图中有另一个register按钮)中的RegisterActivity中的register按钮,导致出错

抱歉浪费你的时间。因此,activity_main中的register按钮没有在register.java中初始化

 类似资料:
  • 我正在尝试实现一个外部色轮,它应该出现在的片段一直在崩溃我的应用程序。我想我明白为什么会发生这种情况,但是在尝试修复它大约6个小时后,我就要放弃了。我知道之前有人问过这个问题,但是我无法为我的特定问题导出一个修复程序。下面是我的代码: 这是Logcat错误: 如果有人能帮我解决这个问题,那就太好了。提前谢谢^^ 编辑:这是我的XML,按要求:

  • 我的应用程序有问题,我想解决它,但我无法访问解决方案,请帮助我,,,

  • 问题内容: 我收到以下错误 尝试在空对象引用上调用虚拟方法’void android.widget.StackView.setAdapter(android.widget.Adapter)’ 在这条线上 完整的片段 EventsFragment.java 是 Stack_Adapter.java Stack_Items 问题答案: 您正在执行: 你是。返回。 你为什么用? 在哪里?您应该从正确的x

  • 我的应用程序有问题,想解决它,但我无法访问解决方案,请帮帮我,,

  • 我将使用库,并尝试在应用程序启动时使用以下方法获取令牌。 应用程序在发布时崩溃 AndroidManifest Build.Gradle: 此外,我尝试在SharedPreferences中缓存令牌,但似乎从未调用onNewToken()。 会有什么问题?

  • 问题内容: 我尝试使用片段来打开数据库,但是,当我单击按钮开始搜索时,程序意外终止,并显示如下错误: 主片段: DBManager类: 顺便说一句,我在MainAcitivity中使用了有关DBManager的代码,并且成功了。将代码复制到上面的片段后,它失败了,该怎么办? 问题答案: 之前和之后你都做不到。 因为,您正在执行片段实例化时。该方法将始终返回null。另外,尽量不要将参考文献保留在您