简体   繁体   中英

Button click causing null pointer

在此处输入图片说明 Every time I click on the button, the app crashes. I have trouble finding the bug, but I'm sure it has to do something with either the onClickListener, or the onClick function.

Note: I'm using Parse API for some back end stuff. But I highly doubt it has anything to do with any of the Parse stuff.

Here's what my code looks like:

public class SignUpActivity extends Activity {

    protected EditText mUserName;
    protected EditText mPassword;
    protected EditText mEmail;
    protected Button mSignUpButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_sign_up);

        mUserName = (EditText) findViewById(R.id.usernameField);
        mPassword = (EditText) findViewById(R.id.passwordField);
        mEmail = (EditText) findViewById(R.id.emailField);
        mSignUpButton = (Button) findViewById(R.id.signupButton);

        mSignUpButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String username = mUserName.getText().toString();
                String password = mPassword.getText().toString();
                String email = mEmail.getText().toString();

                username = username.trim();
                password = password.trim();
                email = email.trim();

                if(username.isEmpty() || password.isEmpty() || email.isEmpty()){
                    AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
                    builder.setMessage(R.string.signup_error_message)
                           .setTitle(R.string.signup_error_title)
                           .setPositiveButton(android.R.string.ok, null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
                else{

                    setProgressBarIndeterminateVisibility(true);
                    ParseUser newUser = new ParseUser();
                    newUser.setUsername(username);
                    newUser.setPassword(password);
                    newUser.setEmail(email);
                    newUser.signUpInBackground(new SignUpCallback() {

                        @Override
                        public void done(ParseException e) {
                            setProgressBarIndeterminateVisibility(false);
                            if(e == null){
                                // success
                                Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                            }
                            else{
                                AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
                                builder.setMessage(e.getMessage())
                                       .setTitle(R.string.signup_error_title)
                                       .setPositiveButton(android.R.string.ok, null);
                                AlertDialog dialog = builder.create();
                                dialog.show();
                            }
                        }
                    });
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.sign_up, menu);
        return true;
    }

}

Here's my Log Cat:

04-14 14:19:05.881: E/AndroidRuntime(1156): FATAL EXCEPTION: main 04-14 14:19:05.881:
E/AndroidRuntime(1156): Process: com.ebad.ribbit, PID: 1156 04-14 14:19:05.881: 
E/AndroidRuntime(1156): java.lang.NullPointerException 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.ebad.ribbit.SignUpActivity$1.onClick(SignUpActivity.java:40) 04-14 14:19:05.881: 
E/AndroidRuntime(1156): at android.view.View.performClick(View.java:4438) 04-14 14:19:05.881: 
E/AndroidRuntime(1156): at android.view.View$PerformClick.run(View.java:18422) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Handler.handleCallback(Handler.java:733) 04-14 14:19:05.881: 
E/AndroidRuntime(1156): at android.os.Handler.dispatchMessage(Handler.java:95) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Looper.loop(Looper.java:136) 04-14 14:19:05.881: 
E/AndroidRuntime(1156): at android.app.ActivityThread.main(ActivityThread.java:5017) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at java.lang.reflect.Method.invokeNative(Native Method) 04-14 14:19:05.881: 
E/AndroidRuntime(1156): at java.lang.reflect.Method.invoke(Method.java:515) 04-14 14:19:05.881: 
E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-14 14:19:05.881: 
E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at dalvik.system.NativeStart.main(Native Method)

EDIT:

As requested, here is line 40:

String username = mUserName.getText().toString();

EDIT 2:

Here is the log cat after adding Log.i(TAG, mUserName == null ? "mUserName is null" : mUserName.getText() == null ? "mUserName.getText() is null" : "nothing is null"); :

04-14 15:21:47.955: E/AndroidRuntime(1318): FATAL EXCEPTION: main
04-14 15:21:47.955: E/AndroidRuntime(1318): Process: com.ebad.ribbit, PID: 1318
04-14 15:21:47.955: E/AndroidRuntime(1318): java.lang.NullPointerException
04-14 15:21:47.955: E/AndroidRuntime(1318):     at com.ebad.ribbit.SignUpActivity$1.onClick(SignUpActivity.java:43)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at android.view.View.performClick(View.java:4438)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at android.view.View$PerformClick.run(View.java:18422)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at android.os.Handler.handleCallback(Handler.java:733)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at android.os.Looper.loop(Looper.java:136)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at java.lang.reflect.Method.invokeNative(Native Method)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at java.lang.reflect.Method.invoke(Method.java:515)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-14 15:21:47.955: E/AndroidRuntime(1318):     at dalvik.system.NativeStart.main(Native Method)

EDIT 3:

Upon Request, here is my activity_sign_up.xml:

<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=".SignUpActivity" >

    <EditText
        android:id="@+id/userNameField"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:hint="@string/username_hint"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/passwordField"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/userNameField"
        android:ems="10"
        android:hint="@string/password_hint"
        android:inputType="textPassword" />

    <EditText
        android:id="@+id/emailField"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/passwordField"
        android:ems="10"
        android:hint="@string/email_hint"
        android:inputType="textEmailAddress" />

    <Button
        android:id="@+id/signupButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/emailField"
        android:layout_below="@+id/emailField"
        android:layout_marginTop="50dp"
        android:text="@string/sign_up_button_label" />

</RelativeLayout>

If mUsername is null , calling getText() on it will cause a NullPointerException . You should check that it's not null before doing this. Try changing to the following:

        if(mUserName == null || mPassword == null || mEmail == null){
            AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
            builder.setMessage(R.string.signup_error_message)
                   .setTitle(R.string.signup_error_title)
                   .setPositiveButton(android.R.string.ok, null);
            AlertDialog dialog = builder.create();
            dialog.show();
        }

        String username = mUserName.getText().toString();
        String password = mPassword.getText().toString();
        String email = mEmail.getText().toString();

        username = username.trim();
        password = password.trim();
        email = email.trim();

Do this please:

@Override
public void onClick(View v) {
     if(mUserName != null && mPassword != null && mEmail != null && mUserName.getText() != null && mPassword.getText() != null && mEmail.getText() != null)
     {
          Your original code here.
     }
}

Update: Typo

 mUserName = (EditText) findViewById(R.id.usernameField); should be userNameField?  
 <EditText android:id="@+id/userNameField" ...

Try

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

https://developer.android.com/guide/topics/ui/dialogs.html

Also make sure that SignUpActivity is declared in the app manifest. I guess make sure that all activities are set up in the manifest.

EDIT 1 If line 40 is the issue, then mUserName is null or mUserName.getText() is null. So create a couple checks before hand and also add some debug logs to just verify that they are not null.

Make sure that R.layout.activity_sign_up has usernameField as an id. Also make sure in any other app/res/layout folders (ie layout-v14), that all R.layout.activity_sign_up has the edittext as well.

If this errors occurred in your line 40, that means your are getting null from your EditText.

Try it in every place you are getting a string. At least it will save you from getting null pointer exception from EditText.

String username = String.valueOf(mUserName.getText());
String password = String.valueOf(mPassword.getText());
String email = String.valueOf(mEmail.getText());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM