尝试在Android上打开新活动时出现空对象引用错误?

时间:2017-09-19 08:38:05

标签: android android-layout nullpointerexception

这是我的XML活动代码,打开新活动的代码会触发此项目的空异常错误,但是当我在另一个项目上尝试相同的代码时,它在模拟器上运行良好,为什么会出现此错误坚持? 错误日志中产生的错误是:

  

java.lang.RuntimeException:无法启动活动   ComponentInfo {com.swaziprocurement.sppraapp / com.swaziprocurement.sppraapp.Main2Activity}:   java.lang.NullPointerException:尝试调用虚方法' void   android.widget.Button.setOnClickListener(android.view.View $ OnClickListener)'   在空对象引用上

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.swaziprocurement.sppraapp.MainActivity">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="User Registration Form"
        android:textSize="20dp"
        android:textStyle="bold"
        android:id="@+id/textView"
        android:layout_centerHorizontal="true"
        android:gravity="center"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/EditTextFullName"
        android:layout_below="@+id/textView"
        android:layout_marginTop="20dp"
        android:hint="Enter Your Full Name"
        android:gravity="center"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/EditTextEmail"
        android:layout_below="@+id/EditTextFullName"
        android:layout_marginTop="20dp"
        android:inputType="textEmailAddress"
        android:hint="Enter Your Email"
        android:gravity="center"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/EditTextPassword"
        android:layout_below="@+id/EditTextEmail"
        android:layout_marginTop="20dp"
        android:inputType="textPassword"
        android:hint="Enter Your Password"
        android:gravity="center"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click Here To Register"
        android:layout_below="@+id/EditTextPassword"
        android:id="@+id/ButtonRegister"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login Menu"
        android:id="@+id/button2"
        android:layout_below="@+id/ButtonRegister"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

Java代码:

package com.swaziprocurement.sppraapp;

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

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
Button Register,buttonOpen;
EditText FullName,Email,Password;

    RequestQueue requestQueue;

    String NameHolder,PasswordHolder,EmailHolder;

    ProgressDialog progressDialog;
    String HttpUrl="https://android-examples.000webhostapp.com/User-Registration.php";

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

        FullName=(EditText)findViewById(R.id.EditTextFullName);
        Email=(EditText)findViewById(R.id.EditTextEmail);
        Password=(EditText)findViewById(R.id.EditTextPassword);

        Register=(Button)findViewById(R.id.ButtonRegister);
        buttonOpen=(Button)findViewById(R.id.button2);




        requestQueue= Volley.newRequestQueue(MainActivity.this);

        progressDialog=new ProgressDialog(this);




        Register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckEditTextIsEmptyOrNot();
                if (CheckEditText)
                    UserRegistration();
                else{
                    Toast.makeText(MainActivity.this,"Please fill all form fields",Toast.LENGTH_SHORT).show();
                }

            }
        });

        buttonOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openAct();

            }
        });


    }
    public void UserRegistration(){

        // Showing progress dialog at user registration time.
        progressDialog.setMessage("Please Wait, We are Inserting Your Data on Server");
        progressDialog.show();

        // Creating string request with post method.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String ServerResponse) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Showing Echo Response Message Coming From Server.
                        Toast.makeText(MainActivity.this, ServerResponse, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Showing error message if something goes wrong.
                        Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                // Creating Map String Params.
                Map<String, String> params = new HashMap<String, String>();

                // Adding All values to Params.
                // The firs argument should be same sa your MySQL database table columns.
                params.put("User_Email", EmailHolder);
                params.put("User_Password", PasswordHolder);
                params.put("User_Full_Name", NameHolder);

                return params;
            }

        };

        // Creating RequestQueue.
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        // Adding the StringRequest object into requestQueue.
        requestQueue.add(stringRequest);

    }
    public void CheckEditTextIsEmptyOrNot(){

        // Getting values from EditText.
        NameHolder = FullName.getText().toString().trim();
        EmailHolder = Email.getText().toString().trim();
        PasswordHolder = Password.getText().toString().trim();

        // Checking whether EditText value is empty or not.
        if(TextUtils.isEmpty(NameHolder) || TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {

            // If any of EditText is empty then set variable value as False.
            CheckEditText = false;

        }
        else {

            // If any of EditText is filled then set variable value as True.
            CheckEditText = true ;
        }
    }

    public void openAct(){

        startActivity(new Intent(MainActivity.this,Main2Activity.class));
    }
    }

这是第二项活动

package com.swaziprocurement.sppraapp;

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

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class Main2Activity extends AppCompatActivity {
    Button button,LoginButton;
    EditText Email,Password;

    Boolean CheckEditText;

    RequestQueue requestQueue;

    String EmailHolder,PasswordHolder;

    ProgressDialog progressDialog;

    String HttpUrl = "https://android-examples.000webhostapp.com/user_login.php";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        button =(Button)findViewById(R.id.button);
        progressDialog=new ProgressDialog(this);

        LoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckEditTextIsEmptyOrNot();

                if (CheckEditText) {

                    UserLogin();

                } else {

                    Toast.makeText(Main2Activity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent(Main2Activity.this,MainActivity.class);
                startActivity(intent);
            }
        });
    }

    public void CheckEditTextIsEmptyOrNot() {

        // Getting values from EditText.
        EmailHolder = Email.getText().toString().trim();
        PasswordHolder = Password.getText().toString().trim();

        // Checking whether EditText value is empty or not.
        if (TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)) {

            // If any of EditText is empty then set variable value as False.
            CheckEditText = false;

        } else {

            // If any of EditText is filled then set variable value as True.
            CheckEditText = true;
        }
    }

    public void UserLogin() {

        // Showing progress dialog at user registration time.
        progressDialog.setMessage("Please Wait");
        progressDialog.show();

        // Creating string request with post method.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String ServerResponse) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Matching server responce message to our text.
                        if(ServerResponse.equalsIgnoreCase("Data Matched")) {

                            // If response matched then show the toast.
                            Toast.makeText(Main2Activity.this, "Logged In Successfully", Toast.LENGTH_LONG).show();

                            // Finish the current Login activity.
                            finish();

                            // Opening the user profile activity using intent.
                            Intent intent = new Intent(Main2Activity.this, Main3Activity.class);

                            // Sending User Email to another activity using intent.
                            intent.putExtra("UserEmailTAG", EmailHolder);

                            startActivity(intent);
                        }
                        else {

                            // Showing Echo Response Message Coming From Server.
                            Toast.makeText(Main2Activity.this, ServerResponse, Toast.LENGTH_LONG).show();

                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Showing error message if something goes wrong.
                        Toast.makeText(Main2Activity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                // Creating Map String Params.
                Map<String, String> params = new HashMap<String, String>();

                // Adding All values to Params.
                // The firs argument should be same sa your MySQL database table columns.
                params.put("User_Email", EmailHolder);
                params.put("User_Password", PasswordHolder);

                return params;
            }

        };
        // Creating RequestQueue.
        RequestQueue requestQueue = Volley.newRequestQueue(Main2Activity.this);

        // Adding the StringRequest object into requestQueue.
        requestQueue.add(stringRequest);


    }
}

第二个活动的XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.swaziprocurement.sppraapp.Main2Activity">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:textSize="20dp"
        android:textStyle="bold"
        android:text="Volley User Login System"
        android:gravity="center"
        android:layout_marginTop="20dp"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Your Email"
        android:gravity="center"
        android:id="@+id/editText_Email"
        android:layout_below="@+id/textView"
        android:layout_marginTop="20dp"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Your Email"
        android:gravity="center"
        android:id="@+id/editText_Password"
        android:inputType="textPassword"
        android:layout_below="@+id/editText_Email"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="CLICK HERE TO LOGIN"
        android:id="@+id/button_login"
        android:layout_below="@id/editText_Password"
        android:layout_marginTop="20dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Registration Menu"
        android:id="@+id/button"
        android:layout_below="@+id/button_login"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

2 个答案:

答案 0 :(得分:1)

初始化您的LoginButton,

LoginButton  =(Button)findViewById(R.id.button_login);

而不是

LoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckEditTextIsEmptyOrNot();

                if (CheckEditText) {

                    UserLogin();

                } else {

                    Toast.makeText(Main2Activity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });

答案 1 :(得分:0)

您需要初始化按钮,在空引用

上调用OnClickListener
LoginButton  =(Button)findViewById(R.id.button_login);

在致电LoginButton.setOnClickListener()之前,请先启动登录按钮。